text:
Q: How to notify a client from wf4-wcf-server asynchronously? during the last days I spent a lot of time to find a solution on how to send simple messages from a workflow (WF4)-server to a client (in my case WPF).
There exist some examples how to reply on a request (via callback), but I can not find any example how to contact the client asynchronously.
I want to be able to have a communication like this:

*

*[8:00 am] Client: "Hello Server, this is my request. Please start your workflow 'MakeCoffee' using this recipe.".

*[8:01 am] WF-Server: "Hello Client, I'm on it."

*[8:05 am] WF-Server: "I can't find any coffee. I will buy some."

*[8:10 am] WF-Server: "I am boiling the water."

*[8:15 am] WF-Server: "Do you want sugar?"

*[8:17 am] Client: "Yes."

*[8:18 am] WF-Server: "I am done."

Until now, I found these solutions:
1. WCF - Service with CallBack-Channel
This example seems to be pretty cool, but I do not see how to use this with my Workflow-Service - for there is no "implementing service" class. Everything is visual, so I can not apply the "SubscribeClient"-method (or at least I do not know where to place the service implementation).
2. Workflow with notifying events
This example is a nice solution - but (for my understanding) this does not work with a separate workflow-server - it seems to require that the workflow-server and the client are the same.
3. Accessing OperationContext
This example creates a WorkflowServiceHost on client-side, but it is not very easy to handle and I can't adjust it to my requirements.
Does anyone know a handy solution/pattern on how to send messages from a (separate) workflow-server to a client? The client does not know, when the server might send him messages and how many it will be.
I am kind of new to WF4 and would be very thankful for every hint/advise/idea.
Thanks in advance,
Timo
UPDATE
According to the comment from Maurice,  I tried to use a simple service in my client, but unfortunately, my client does not receive and show any of the messages.
This is my client-code:
public partial class MainWindow : Window
{
    private ServiceHost _serviceHost;
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        ApplicationInterface._app = this;
        //prepare the serviceHost
        string clientAddress = "http://localhost:8000/ClientService";
        System.ServiceModel.Channels.Binding bBinding = new BasicHttpBinding();
        _serviceHost.AddServiceEndpoint(typeof(IClientService), bBinding, clientAddress);
        _serviceHost.Open();
    }

    public ListBox GetEventListBox()
    {
        return this.lstEvents;
    }
}

This is my IClientService-Interface:
[ServiceContract]
public interface IClientService
{
    [OperationContract(IsOneWay=true)]
    void MeldeStatus(String statusText);
}

This is the implementation of the IClientService-Interface:
public class ClientService : IClientService
{
    public void MeldeStatus(string statusText)
    {
        ApplicationInterface.AddEvent(statusText);
    }
}

This is the static ApplicationInterface:
public static class ApplicationInterface
{
    public static MainWindow _app { get; set; }

    public static void AddEvent(String eventText)
    {
        if (_app != null)
        {
            new ListBoxTextWriter(_app.GetEventListBox()).WriteLine(eventText);
        }
    }
}

And this the ListBoxTextWriter-class, which should add the messages to a given ListBox:
public class ListBoxTextWriter : TextWriter
{
    const string textClosed = "This TextWriter must be opened before use";

    private Encoding _encoding;
    private bool _isOpen = false;
    private ListBox _listBox;

    public ListBoxTextWriter()
    {
        // Get the static list box
        _listBox = ApplicationInterface._app.GetEventListBox();
        if (_listBox != null)
            _isOpen = true;
    }

    public ListBoxTextWriter(ListBox listBox)
    {
        this._listBox = listBox;
        this._isOpen = true;
    }

    public override Encoding Encoding
    {
        get
        {
            if (_encoding == null)
            {
                _encoding = new UnicodeEncoding(false, false);
            }
            return _encoding;
        }
    }

    public override void Close()
    {
        this.Dispose(true);
    }

    protected override void Dispose(bool disposing)
    {
        this._isOpen = false;
        base.Dispose(disposing);
    }

    public override string ToString()
    {
        return "";
    }

    public override void Write(char value)
    {
        if (!this._isOpen)
            throw new ApplicationException(textClosed); ;

        this._listBox.Dispatcher.BeginInvoke
            (new Action(() => this._listBox.Items.Add(value.ToString())));
    }

    public override void Write(string value)
    {
        if (!this._isOpen)
            throw new ApplicationException(textClosed); ;

        if (value != null)
            this._listBox.Dispatcher.BeginInvoke
                (new Action(() => this._listBox.Items.Add(value)));
    }

    public override void Write(char[] buffer, int index, int count)
    {
        String toAdd = "";

        if (!this._isOpen)
            throw new ApplicationException(textClosed); ;

        if (buffer == null || index < 0 || count < 0)
            throw new ArgumentOutOfRangeException("buffer");

        if ((buffer.Length - index) < count)
            throw new ArgumentException("The buffer is too small");

        for (int i = 0; i < count; i++)
            toAdd += buffer[i];

        this._listBox.Dispatcher.BeginInvoke
            (new Action(() => this._listBox.Items.Add(toAdd)));
    }
}

My WF-Server uses this Send-Activity:
<Send Action="MeldeStatus" EndpointConfigurationName="BasicHttpBinding_Client" sap:VirtualizedContainerService.HintSize="255,90" OperationName="MeldeStatus" ProtectionLevel="None" ServiceContractName="p:IClientService">
  <SendParametersContent>
    <p1:InArgument x:TypeArguments="x:String" x:Key="statusText">Yes, it works.</p1:InArgument>
  </SendParametersContent>
</Send>

This is the configuration of my endpoint at the WF-server:
<system.serviceModel>
  <bindings>
    <basicHttpBinding>
      <binding name="DefaultHTTPBinding" allowCookies="true" />
    </basicHttpBinding>
  </bindings>
  <behaviors>
    <serviceBehaviors>
      <behavior>
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="true"/>
      </behavior>
    </serviceBehaviors>
  </behaviors>
  <services>
    <service name="WFServer.ReklamationErfassen">
      <endpoint address="http://localhost:7812/ReklamationErfassen.xamlx"
                binding="basicHttpBinding"
                bindingConfiguration="DefaultHTTPBinding"
                contract="IReklamationService" />
    </service>
  </services>
  <client>
      <endpoint address="http://localhost:8000/ClientService" binding="basicHttpBinding"
          bindingConfiguration="DefaultHTTPBinding" contract="IClientService"
          name="BasicHttpBinding_Client" />
  </client>
</system.serviceModel>
<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

I do not get any messages, error or warnings - can somebody please have a quick check on the given code?
Thanks again,
Timo

A: Lots of ways to do this but two of the easiest are:

*

*Use the Send activity to send SOAP messages to a WCF endpoint to the client app is hosting. If the client needs to respond just add a Receive activity to wait for the answer.

*Use a database table to write the messages to. The client app polls the messages and displays these to the user. If a reply is needed you can resume a bookmark on a custom activity with the response.

The first depends on WCF and for responses on hosting in a WorkflowServiceHost. The second approach is more general in not being dependent on WCF but requires more code and custom activities.


text:
Q: Collection was modified; enumeration operation may not execute randomly popping up - HTTP? I have "Collection was modified; enumeration operation may not execute." exception populating randomly in my logs, it is not a persistent error but a really random and annoying one.
It seems to be originating from System.Net.Http? When adding headers but I am not sure exactly what is causing this error to pop up. I looked everywhere for this error and I understand the concept of the cause however I don't do any manual looping & editing of a list (except adding the headers) that could throw this exception?
I have a service that communicates to an external API using HTTPClient, this works most of the time however it sometimes fails with the above exception, I tried debugging this however I just can't seem to find a resolution! Hopefully, someone can spot the issue and point me in the right way.
Exception:
Source: System.Private.CoreLib
 Message: Collection was modified; enumeration operation may not execute.
 Stack trace:    at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Net.Http.Headers.HttpHeaders.AddHeaderInfo(HeaderDescriptor descriptor, HeaderStoreItemInfo sourceInfo)
   at System.Net.Http.Headers.HttpHeaders.AddHeaders(HttpHeaders sourceHeaders)
   at System.Net.Http.Headers.HttpRequestHeaders.AddHeaders(HttpHeaders sourceHeaders)
   at System.Net.Http.HttpClient.PrepareRequestMessage(HttpRequestMessage request)
   at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.PostAsync(String requestUri, HttpContent content)
   at Hidden.Core.Service.BlaService.MyMethod(MyMethodModel model) in C:\Source\Hidden.Core\Service\BlaService.cs:line 168
   at Hidden.Web.Api.Controllers.ResourceController.MyMethod(MyMethodModel model) in C:\Source\Hidden.Web.Api\Controllers\ResourceController.cs:line 387
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Hidden.Web.Api.Infrastructure.ExceptionHandlerMiddleware.Invoke(HttpContext context, IActionResultExecutor`1 executor) in C:\Source\Hidden.Web.Api\Infrastructure\ExceptionHandlerMiddleware.cs:line 31
 Inner Exception:

My Service:
private static readonly HttpClient client = new HttpClient();

public async Task<HttpResponseMessage> MyMethod(MyMethodModel model)
{
    //Escape chars
    model.Location = model.Location.Replace("'", "''");
    model.DirectoryName = model.DirectoryName.Replace("'", "''");

    //Set Endpoint
    var sharePointEndpoint = $"https://{model.Hostname}/sites/{model.Site}/_api/web/folders";

    //Set default headers
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", model.SharePointToken); //Set token
    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");

    //Pre-Body data setup
    ResourceBodyMetaDataModel metaData = new ResourceBodyMetaDataModel() { type = "SP.Folder" };

    //Body data setup
    var bodyModel = new Dictionary<string, object>();
    bodyModel.Add("__metadata", metaData);
    bodyModel.Add("ServerRelativeUrl", $"{model.Location}/{model.DirectoryName}/");

    //Set content headers
    var strContent = new StringContent(JsonConvert.SerializeObject(bodyModel));
    strContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    strContent.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("odata", "verbose"));

    // Send request, grab response
    var response = await client.PostAsync(sharePointEndpoint, strContent); //Exception Points HERE

    //Return response message
    return response;
}

A: Overview:
It seemed that once I sent multiple requests to my API, these requests was conflicting with each other trying to overwrite the headers. I even tried clearing the headers first and then add them but yet I still encountered the above issue. The issue also started to include the exception: An item with the same key has already been added. Key: System.Net.Http.Headers.HeaderDescriptor.
Resolution:
To solve this I refactored my service to do the following:
//Setup request
var request = new HttpRequestMessage(HttpMethod.Post, sharePointEndpoint)
{
    Content = strContent
};

request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", model.SharePointToken);
request.Headers.Add("Accept", "application/json;odata=verbose");
request.Headers.Add("X-HTTP-Method", "POST");
request.Headers.Add("ContentLength", bodyModelJson.Length.ToString());

// Send request, grab response
var response = await _httpClient.SendAsync(request);

In my case, the headers would depend on what operation I wanted to conduct. I removed the part where I was adding the default headers for HTTPClient and instead, added them within the request being made. As you can see, I now also used SendAsync();
I also injected HTTPClient as singleton. I had to initiate using my Constructor then afterwards whenever I want to use HTTPClient.
MyService:
private readonly HttpClient _httpClient;

public MyService(HttpClient httpClient)
{
    _httpClient = httpClient;
}

Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
    /// SERVICES
    services.AddSingleton<HttpClient>();
}

Hopefully this helps other people experiencing this issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android Studio: Keystore was tampered with, or password was incorrect When I try to build on Android Studio a signed APK-file on another computer (not on the PC on which key was generated), the error is occurs:
Information:Gradle tasks [:app:assembleRelease]
:app:preBuild UP-TO-DATE
:app:preReleaseBuild UP-TO-DATE
:app:checkReleaseManifest
:app:preDebugBuild UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72301Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42301Library UP-TO-DATE
......
:app:prepareComGoogleAndroidGmsPlayServicesWearable810Library UP-TO-DATE
:app:prepareReleaseDependencies
:app:packageRelease FAILED
Error:Execution failed for task ':app:packageRelease'. Failed to read key         SkidkaRu from store "C:\Users\elena\keyappskidkaru.jks": Keystore was tampered   with, or password was incorrect

When, I opened a Terminal window and typed in the following:
keytool -storepasswd -new [inserted password] -keystore [inserted file name]

keytool -keypasswd -alias [inserted alias] -new [inserted new key password] -keystore [inserted keystore file name]

Still, there was an error "Keystore was tampered with, or password was incorrect"
The password exactly right. The key was copied from the computer on which it was generated at the first time.
The application has already been published in the google play market, so I can not create a new keystore.

A: I solve this by using the latest build tool in build.gradle
dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
}

Took me entire day to figure it out.

A: Simplest option is to overwrite the keystore file with a backedup copy from a date it was known to be working. Doing something wrong when attempting to fix the keystore may make the situation worse.

A: Helped up key using AndroidKeystoreBrute library with the same password and key alias. Perhaps the old key is damaged in some way , because in the path alias to it did not show up.


text:
Q: sort mixed python list in cointaining data type order I have a list like this  ['car', 'truck', 8, 4, 'bus', 6, 1] and output should be ['bus', 'car', 1, 4, 'truck', 6, 8] other words it should sort all words in alphabetical order and all integers in numerical order. How can I do this?

A: Separating the values by type, then sorting each type's values, then producing the result:
# The input
a = ['car', 'truck', 8, 4, 'bus', 6, 1]

# Collect the values by type
d = {}
for x in a:
    d.setdefault(type(x), []).append(x)

# Sort each type
d = {k: iter(sorted(v)) for k, v in d.items()}

# The result list
result = [next(d[type(x)]) for x in a]
print(result)

Prints:
['bus', 'car', 1, 4, 'truck', 6, 8]


text:
Q: Cooja/Contiki calculating power of two for large floats with result exceeding 32767 would give false result I am new to C and Cooja, currently using data type float to store values read from a lighting mote. It would require calculating a basic standard deviation, which would involve a large float value power 2 through powf() or pow() or manually multiplying the value by twice. The results would mostly be incorrect and sometimes even appearing in negative. And some results reached a threshold of 32767, in which after I researched on this issue, might point to the issue of data type, where floats with storage size of 2 bytes only support a value range from -32767.0 to +32767.0 and if a value exceeds it will be equivalent to the max value or even go on a cycle for all value range.
Hence, I tried to change all the data types from float to a larger double type with 8 bytes, but it still remains the same incorrect results. Results are printed out using int representation workaround for float values. Is this a data type storage issue, or wrong function used, or these type of large calculations shouldn't be done on single motes? I apologize if the question is quite low-level or stupid. Thank you very much!


text:
Q: Android FFMPEG is not able to read the font file Android FFmpeg failed to read the system's font file, although the font file exists
This is the code:
ffmpeg -i /storage/emulated/0/DCIM/Camera/VID_20220414_215502.mp4 -vf drawtext=fontfile='/system/fonts/DroidSans.ttf':text='Hamer Hamer':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.5:boxborderw=5:x=100:y:100 -movflags +faststart /storage/emulated/0/Movies/random-1660738905069.mp4

This the error shown:
mobile-ffmpeg: [Parsed_drawtext_0 @ 0xb400006e074623d0] Cannot find a valid font for the family Sans


text:
Q: Best practices - should I order newsletter recipients by email host or not? For a newsletter mailing, about 50,000 users, using pear, is it convenient to order the list by mail provider or leave it all randomly?

A: From my experiences using Exim to send large amounts of emails, performance will suffer heavily if your email queue grows too large. Depending on your hardware, once you have around 10,000 emails in the queue, you will start to see significant effects of bogosorting, where the server uses more CPU just juggling the queue than actually getting any useful work done.
One way of avoiding large queues, is of course to get the emails delivered as fast and efficient as possible. One of the many ways of achieving this, is to get Exim to deliver multiple emails over the same TCP connection. This in turn can be achieved by sorting the recipients by domain, but that is not enough! By default, Exim will try to deliver each mail it receives immediately and then each delivery will open its own connection (this gives fast deliveries for very small volumes but will drive server load through the roof for larger volumes). You need to first spool the mails to Exim, and then let a queue runner handle the actual delivery which will then automatically see all other emails in the queue that should go to the same host and will deliver them over the same connection.
Optimizing Exim for sending large amounts of emails is a very complex subject that cannot be solved with just a few magical tricks. Crucial configuration options are (but not limited to): queue_only, queue_run_max, deliver_queue_load_max, remote_max_parallel, split_spool_directory, but also fast spool disk, enough RAM, and making sure Exim starts new queue runners often enough (command-line option when starting the Exim daemon).
How this relates to PEAR escapes me, but perhaps this gives you some ideas of how to approach your problem.


text:
Q: Assigning to a Temporary Dictionary Then Final Dictionary - Advantage? I'm analyzing the update function in the Issue class here: https://github.com/pycontribs/jira/blob/master/jira/resources.py
What I don't understand about the below code is the advantage of assigning twice when the developer could have simply said data['fields] = fields and in the else data['fields'] = {}
Are there any known advantages to the below?
if fields is not None:
   fields_dict = fields
else:
   fields_dict = {}
data['fields'] = fields_dict

if update is not None:
   update_dict = update
else:
   update_dict = {}
data['update'] = update_dict

A: The developer wanted to support None values and switch them to empty dictionaries. However, this could have easily been done using lines like this:
data['fields'] = fields or {}

or
data['fields'] = {} if fields is None else fields

Why do it the way it was done? Most likely the developer was just inexperienced.


text:
Q: Why Cypress gives success after second attempt? In my Cypress tests, I create some data in before block and then my test script is run that locates in it block. I checked business side flow and it seems like there is no error about app side. I just want to understand that why my test's result is success after second attempt. Does Cypress has this kind of solution to handle an error maybe?

A: Cypress has the ability to automatically retry any failed tests. I would check your Cypress configuration's value for retries.openMode.


text:
Q: On which versions of windows we can run dot net application? On which versions of windows we can run dot net application, the platform is already having the .net framework installed. I mean on which windows version we can install .net fx

A: A simple google search yields: https://learn.microsoft.com/en-us/dotnet/framework/migration-guide/versions-and-dependencies
+------------------------------------------------------------------+
|.net framework version| Comes preinstalled on| Can be installed on|
+----------------------+----------------------+--------------------+
|4.7                   | 10 (1607)            | 7     onwards      |
|4.6                   | 10                   | Vista onwards      |
|4.5.1                 | 8.1                  | Vista onwards      |
|4.5                   | 8                    | Vista onwards      |
|4                     |                      | Vista onwards      |
|3.5                   | 7                    | Vista onwards      |
|3.0                   | Vista                | Vista onwards      |
+------------------------------------------------------------------+


text:
Q: Convert .json to .csv in ruby I want to convert .json file into .csv file using ruby. Pleases help me to do this.
Also propose any tool to achieve this.

A: I think the easies way to convert the JSON to CSV in ruby is using json2csv ruby gem.
PS: I may be biased as I am author of this.
json2csv github repo
Running the command
json2csv convert data/sample.json

Input File
In this particular case it will convert following json:
cat data/sample.json

{
    "12345": {
        "Firstname": "Joe",
        "Lastname": "Doe",
        "Address": {
            "Street": "#2140 Taylor Street, 94133",
            "City": "San Francisco",
            "Details": {
                "note": "Pool available"
            }
        }
    },

    "45678": {
        "Firstname": "Jack",
        "Lastname": "Plumber",
        "Address": {
            "Street": "#111 Sutter St, 94104",
            "City": "San Francisco",
            "Details": {
                "note": "Korean Deli near to main entrance"
            }
        }
    }
}

Output
cat data/sample.json.csv

id,Firstname,Lastname,Address.Street,Address.City,Address.Details.note
12345,Joe,Doe,"#2140 Taylor Street, 94133",San Francisco,Pool available
45678,Jack,Plumber,"#111 Sutter St, 94104",San Francisco,Korean Deli near to main entrance

A: Based on @Alex's answer but adding csv headers and example test.
# utils.rb
require "csv"
module Utils
  def self.array_of_hashes_to_csv(array_of_hashes)
    CSV.generate do |csv|
      csv << array_of_hashes.first.keys
      array_of_hashes.each { |hash| csv << hash.values }
    end
  end
end

# utils_test.rb
class UtilsTest < MiniTest::Unit::TestCase
  def test_array_of_hashes_to_csv
    array_of_hashes = [
      { :key1 => "value1", :key2 => "value2" },
      { :key1 => "value3", :key2 => "value4" }
    ]
    expected_result = "key1,key2\nvalue1,value2\nvalue3,value4\n"
    assert_equal(expected_result, Utils.array_of_hashes_to_csv(array_of_hashes))
  end
end

A: Try something like this:
require 'csv'
require 'json'

csv_string = CSV.generate do |csv|
  JSON.parse(File.open("foo.json").read).each do |hash|
    csv << hash.values
  end
end

puts csv_string

A: Ruby code to convert from json to csv.
Handles arrays by converting them to double quoted strings.
#json-to-csv.rb
require 'json'
require 'csv'

file = File.read('./input.json')
hash = JSON.parse(file)

CSV.open('./output.csv', 'w') do |csv|
  headers = hash.first.keys
  csv << headers

  hash.each do |item|
    values = item.values
    printable_values = Array.new
    values.each do |value|

      printable_values << value.to_s.gsub(/\[|\]/,'').gsub(/"/,'\'')

    end

    csv << printable_values

  end

end

A: Edit:
This functionality described below is now available as a gem.  After installing with gem install json_converter, the following snippet can be used to generate a CSV from a valid JSON string or object:
require 'json_converter'
json_converter= JsonConverter.new

# Assume json is a valid JSON string or object
csv = json_converter.generate_csv json

Original Answer:
If your JSON data is relatively simple (no nesting or arrays), Alex's answer is probably the cleanest way of handling this problem.
However, if you do need to take arrays and nested objects into account, I've attempted to port a web version of such a converter to ruby.  It can be found here.  The methods that handle the actual restructuring of data are array_from and flatten.
The array_from method attempts to identify what a "row" of data looks like for a given dataset.  It is not perfect, and you may want to tweak this part for different datasets.
# Attempt to identify what a "row" should look like
def array_from(json)
  queue, next_item = [], json
  while !next_item.nil?

    return next_item if next_item.is_a? Array

    if next_item.is_a? Hash
      next_item.each do |k, v|
        queue.push next_item[k]
      end
    end

    next_item = queue.shift
  end

  return [json]
end

The flatten method recursively iterates over the JSON object(s), and generates an object that represents headers and values.  If an object is nested, the header for its column will be prefixed with its parent key(s), delimited by the / character.
# The path argument is used to construct header columns for nested elements
def flatten(object, path='')
  scalars = [String, Integer, Fixnum, FalseClass, TrueClass]
  columns = {}

  if [Hash, Array].include? object.class
    object.each do |k, v|
      new_columns = flatten(v, "#{path}#{k}/") if object.class == Hash
      new_columns = flatten(k, "#{path}#{k}/") if object.class == Array
      columns = columns.merge new_columns
    end

    return columns
  elsif scalars.include? object.class
      # Remove trailing slash from path
      end_path = path[0, path.length - 1]
      columns[end_path] = object
      return columns
  else
    return {}
  end
end

If there are any null values in the original JSON, you'll need to convert these to something other than nil before attempting the conversion - you'll generally end up with uneven rows if you don't.  The nils_to_strings method handles that:
# Recursively convert all nil values of a hash to empty strings
def nils_to_strings(hash)
  hash.each_with_object({}) do |(k,v), object|
    case v
    when Hash
      object[k] = nils_to_strings v
    when nil
      object[k] = ''
    else
      object[k] = v
    end
  end
end

Here's a brief example of how this would be used:
json = JSON.parse(File.open('in.json').read)
in_array = array_from json
in_array.map! { |x| nils_to_strings x }

out_array = []
in_array.each do |row|
  out_array[out_array.length] = flatten row
end

headers_written = false
CSV.open('out.csv', 'w') do |csv|
  out_array.each do |row|
    csv << row.keys && headers_written = true if headers_written === false
    csv << row.values
  end
end

And finally, here's some example input/output:
Input:
{
  "Forms": [
    {
      "Form": {
        "id": "x",
        "version_id": "x",
        "name": "x",
        "category": "",
        "subcategory": null,
        "is_template": null,
        "moderation_status": "x",
        "display_status": "x",
        "use_ssl": "x",
        "modified": "x",
        "Aggregate_metadata": {
          "id": "x",
          "response_count": "x",
          "submitted_count": "x",
          "saved_count": "x",
          "unread_count": "x",
          "dropout_rate": "x",
          "average_completion_time": null,
          "is_uptodate": "x"
        }
      },
      "User": {
        "username": "somedude@example.com"
      }
    },
    {
      "Form": {
        "id": "x",
        "version_id": "x",
        "name": "x",
        "category": "",
        "subcategory": null,
        "is_template": null,
        "moderation_status": "x",
        "display_status": "x",
        "use_ssl": "x",
        "modified": "x",
        "Aggregate_metadata": {
          "id": "x",
          "response_count": "x",
          "submitted_count": "x",
          "saved_count": "x",
          "unread_count": "x",
          "dropout_rate": "x",
          "average_completion_time": null,
          "is_uptodate": "x"
        }
      },
      "User": {
        "username": "somedude@example.com"
      }
    }
  ]
}

Output:
Form/id,Form/version_id,Form/name,Form/category,Form/subcategory,Form/is_template,Form/moderation_status,Form/display_status,Form/use_ssl,Form/modified,Form/Aggregate_metadata/id,Form/Aggregate_metadata/response_count,Form/Aggregate_metadata/submitted_count,Form/Aggregate_metadata/saved_count,Form/Aggregate_metadata/unread_count,Form/Aggregate_metadata/dropout_rate,Form/Aggregate_metadata/average_completion_time,Form/Aggregate_metadata/is_uptodate,User/username
x,x,x,"","","",x,x,x,x,x,x,x,x,x,x,"",x,somedude@example.com
x,x,x,"","","",x,x,x,x,x,x,x,x,x,x,"",x,somedude@example.com

A: To actually write to file...
require 'csv'
require 'json'

CSV.open("your_csv.csv", "w") do |csv| #open new file for write
  JSON.parse(File.open("your_json.json").read).each do |hash| #open json to parse
    csv << hash.values #write value to file
  end
end

A: This is handle headers & nested json.
require 'csv'
require 'json'

@headers = []
file = File.open('file.json')
JSON.parse(file.read).each do |h|
  h.keys.each do |key|
    @headers << key
  end
end

uniq_headers = @headers.uniq
file = File.open('file.json')
finalrow = []

JSON.parse(file.read).each do |h|
  final = {}
  @headers.each do |key2|
    final[key2] = h[key2]
  end

  finalrow << final
end

CSV.open('output.csv' , 'w') do |csv|
  csv << uniq_headers
  finalrow.each do |deal|
    csv << deal.values
  end
end


text:
Q: How to get value of different checkboxes and calculate value of those checked checkboxes and show in the input field? I have a little problem with getiing the value of diffrent checkboxes when it is checked. Here is my code

<input type="checkbox" id="waterdm"  name="waterdm" value="10" />Water Damage

<input type="checkbox" id="screendm" name="screendm" value="20" />Screen Damage

<input type="checkbox" id="Chargerdm" name="Chargerdm" value="30" />Charger Damage

<input type="checkbox" id="hdphdm" name="hdphdm" value="10" />Headphone Damage

 Calculated Price: <input type="text" name="price" id="price" />

What I want is whenever user check in checkboxes I need to get those value and show the sum of each checkbox value which is checked in to another input box. It Means I need to sum those value of each checkbox
is checked.And when user unchecked any of the checkboxes then that value should subtracted from the that total. I don't have enough experience in jquery. Please help me.

A: You would need to iterate over the cheboxes. And change event makes more sense when you are talking in terms of checkboxes..
Use on to attach events instead of bind
$(document).ready(function () {
    // cache the inputs and bind the events
    var $inputs = $('input[type="checkbox"]')
    $inputs.on('change', function () {
        var sum = 0;
        $inputs.each(function() {
        // iterate and add it to sum only if checked
           if(this.checked)
               sum += parseInt(this.value);
        });
        $("#price").val(sum);
    });
});

Check Fiddle

A:  $(document).ready(function () {
     var waterdm = 0;
     $('input[type="checkbox"]').bind('click', function (e) {
         if (this.checked) {
             waterdm += eval(this.value);
         } else {
             waterdm -= eval(this.value);
         }

         $("#price").val(waterdm);
     });
 });

Demo here

A: Try this
 $(document).ready(function(){
   var waterdm=0;
   $('input[type="checkbox"]').on('click',function()
    {
    waterdm = waterdm+parseInt($(this).val());
    $("#price").val(waterdm);
 });
});

Demo

A: You can use following code
$(document).ready(function(){
    $('input[type="checkbox"]').click(function()
    {
        var val = 0;
        $('input[type="checkbox"]:checked').each(function(){
            val+=parseInt($(this).val());
        });
          $("#price").val(val);
     });
});

Demo

A: If you want to sum all checked checkboxes try something like this:
$('input[type="checkbox"]').bind('click',function()
    {
        var sum = 0;
        $('input[type="checkbox"]:checked').each(function(){
           var val = parseInt($(this).val());
           sum += val;
        });
       $("#price").val(sum);
 });


text:
Q: Eisenstein theorem for algebraic power series in positive characteristic Eisenstein proved that if a power series $\sum_{n\ge0}a_nz^n$ over $\mathbb C$  is algebraic over $\overline{\mathbb Q}(z)$, then it exists positive integers $a$ and $b$ such that for all $n\in\mathbb N$, $ba^na_n$ is an algebraic integer. Obviously, adapting the proof shows that the following is also true in positive characteristic:
Let $\Omega$ be a completion of an algebraic closure of $\mathbb F_q\left(\left(\frac1T\right)\right)$ for the topology induced by the valuation $-\deg$. Let $f(z)=\sum_{n\ge0}a_nz^n$ be a power series over $\Omega$. If $f$ is algebraic over $\overline{\mathbb F_q(T)}(z)$, then it exists $P,Q\in\mathbb F_q[T]$ such that for every $n\in\mathbb N$ $QP^na_n$ belongs to the integral closure of $\mathbb F_q[T]$ in $\overline{\mathbb F_q(T)}$.
Does anyone know where I could find this theorem explicitly enounced and better proved.
Thanks in advance


text:
Q: Forgotten term in the covariant form of $\mathcal{N}=4$ supersymmetric self-dual Yang-Mills theory? For $\mathcal{N}=4$ supersymmetric self-dual Yang-Mills theory, the lightcone formulation reads:
$$
\int d^{4} x \ d^{4} \theta
\left(
\frac{1}{2} V \Box V +
\frac{1}{3} V [\partial_{+} V, \partial_{\bar{z}} V]
\right)
$$
Where $x^{+} = x^{0} + x^{3}$ and $x^{\bar{z}} = x^{1} - i x^{2}$ are the lightcone coordinates.
And $\theta$'s are the odd coordinates in the lightcone Mandelstam supersymmetric formulation.
And $V$ is the chiral superfield:
$$
V = \partial_{+}^{-1} A + \theta_I  \partial_{+}^{-1} \psi^{I} +
\frac{1}{2} \theta_I \theta_J \phi^{I J} + \ldots
$$
Self-dual supersymmetric Yang-Mills action is actually a truncation of the full SYM action to the quadratic term and a triple vertex of definite chirality, as shown here https://arxiv.org/abs/hep-th/9606061. By definite chirality I mean, that in the SYM there is a triple vertex with net chirality equal to 1, it involves following combination of fields:
$$
g^{-} g^{+} g^{+}, \lambda^{+} \lambda^{+} \phi, g^{+} \lambda^{+} \lambda^{-} \ldots
$$
Here $g^{\pm}$ denotes the gluon of the helicity +1 and -1 correspondingly,
and $\lambda^{\pm}$ fermion of helicity $\pm 1/2$.
There is a vertex in the SYM, involving fields, with the chiralities summing to $-1$. The self-dual theory has only the first vertex.
The covariant formulation the paper https://arxiv.org/abs/hep-th/9205075 reads:
$$
\int d^{4} x \ d^{4} \theta
\left(
G^{\dot{\alpha} \dot{\beta}}
F_{\dot{\alpha} \dot{\beta}} +
\bar{\psi}^{I \dot{\alpha}} \nabla_{\dot{\alpha} \alpha} \psi^{I \alpha} +
\phi^{I J} \Box \phi_{I J} +
\phi_{I J} \psi^{\alpha} \psi_{\alpha}
\right)
$$
From this expression I cannot see, how can one obtain the term :
$$
\phi \ \phi \ g^{+}
$$
Because the scalar field seems to be interacting only via Yukawa interaction with fermions.
Presumably, there is an abuse with notation, and the $\Box$ is not an ordinary Laplacian operator, but something else, involving the covariant derivative : $D_{\mu} = \partial_{\mu} + [, A_\mu]$. The most apparent guess is:
$$
D_{\mu} \phi \ D^{\mu} \phi
$$
However, it has a term of $4$th order : $[A_\mu, \phi] [A_\mu, \phi]$, whereas we have only a cubic vertex. Another guess is:
$$
D_{\mu} \phi \ \partial^{\mu} \phi
$$
Here there is only a quadratic and cubic term, but this term looks somehow unnatural.


text:
Q: how i can use standardstylesheets in vf page I am developing app in salesforce and i don't have any idea about standardstylesheets in vf page. In my app i have created my own style sheet added to static resources and i am using my stylesheet not  standardstylesheets of salesforce. This is working fine but now in my vf page if i create any look up input field it is not providing me search link for look up.
Example:
<apex:page controller="controllermethod" standardStylesheets="false" showHeader="false">
 <apex:form >
  <apex:pageBlock mode="edit">

       <apex:outputLabel styleClass="label" value="Project Name " />
       <apex:inputField styleClass="field" value="{!newproj.Name}"/>

      <apex:repeat value="{!moduleList}" var="module">

       <apex:outputLabel styleClass="label" value="Module " id="test"/>
       <apex:inputField styleClass="field" value="{!module.Name}"/>

       <apex:outputLabel styleClass="label" value="Vendor " id="test1"/>
       <apex:inputField styleClass="field" value="{!module.Vendor__c}"/>

      </apex:repeat>

      <apex:commandButton value="Save" action="{!savecreatenew}"/>
      <apex:commandButton value="Cancel" action="{!closePopup}" />

        </apex:pageBlock>
        </apex:form>
</apex:page>

In this vf page module and vendor are look up fields but it is just displaying text box no look up button link.How i can solve this problem.Is it possible to use standardStylesheets component wise?

A: You can mix custom CSS with the standardStylesheets simply by changing your standardStylesheets parameter back to true.
Of course this will add styling to a lot of your components, so you might want to switch out the <apex:pageBlock> for a regular div to give you more control over it. Your styling can be overridden by the Salesforce styles however using !important in appropriate places should help with that.


text:
Q: iOS zeromq sometimes cannot receive message at start in pub/sub I am using ZMQ Stable Release 3.2.4 and compile it into iOS
and also use IOS ZMQ Api.
It works perfectly most of the time. However, sometimes when start the app, the first message is missing and the receiver becomes idle all the time. After restart the app, it works well again.
Is it something I need to set in subSocket in order to make it more stable?
Here is my code:
IP_ADDRESS = @"127.0.0.1";

NSString *kEndPoint = [NSString stringWithFormat:@"tcp://%@:%d", IP_ADDRESS, PUB_PORT];
self.pubSocket = [ctx socketWithType:ZMQ_PUB];
[self.pubSocket connectToEndpoint:kEndPoint];

NSString *rEndPoint = [NSString stringWithFormat:@"tcp://%@:%d", IP_ADDRESS, SUB_PORT];
self.subSocket = [ctx socketWithType:ZMQ_SUB];
[self.subSocket connectToEndpoint:rEndPoint];

sleep(1.5); // add sleep to make sure the socket is ready

[self registerListener:self forTopic:TOPIC_topic_resolution];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    pollitems[0].socket = [subSocket socket] ;
    pollitems[0].events = ZMQ_POLLIN;

    NSData * data = [subSocket receiveDataWithFlags:ZMQ_DONTWAIT];

    // receive data and do logic here
});

A: In our iOS apps that use zmq (libzmq) I usually set a timeout to avoid the dreaded hang forever waiting for receive... try something like this for your setsockopt:
    int timeout = 6000;
zmq_setsockopt(self->zmqSend, ZMQ_SNDTIMEO, &timeout, sizeof(int));
zmq_setsockopt(self->zmqSend, ZMQ_RCVTIMEO, &timeout, sizeof(int));

hope that helps!
JB


text:
Q: Finding the fraction $\frac{a^5+b^5+c^5+d^5}{a^6+b^6+c^6+d^6}$ when knowing the sums $a+b+c+d$ to $a^4+b^4+c^4+d^4$ How can I solve this question with out find a,b,c,d
$$a+b+c+d=2$$
$$a^2+b^2+c^2+d^2=30$$
$$a^3+b^3+c^3+d^3=44$$
$$a^4+b^4+c^4+d^4=354$$
so :$$\frac{a^5+b^5+c^5+d^5}{a^6+b^6+c^6+d^6}=?$$
If the qusetion impossible to solve withot find a,b,c,d then is there any simple way to find a,b,c,d
Is there any help?

A: Here's an approach which involves AM-GM inequality(To bound the numbers).
I have considered the positive values of $(a,b,c,d)$. I can consider $a^2,b^2,c^2$ and $d^2$, since they are all strictly positive.
$\dfrac{a^2+b^2+c^2+d^2}{4} \ge \sqrt{abcd}$
$\dfrac{30}{4} \ge \sqrt{abcd} \implies 56.25 \ge abcd$
Since $a^2+b^2+c^2+d^2=30$ and $56 >|abcd|$, One of the $|a|,|b|,|c|,|d|$ is at most $5$.
Considering $a^4+b^4+c^4+d^4$, one of the $|a|,|b|,|c|,|d|$ is atmost $4$, since $5^4=625$ .
Now we have $a^2+b^2+c^2+d^2=30$, the value of $(|a|,|b|,|c|,|d|)$ is from set  $(1,2,3,4)$.
And also:
Considering $4th$ degree polynomial such that $a,b,c,d$ are the roots of the equation.
$x^4+px^3+qx^2+rx+s=0$
$a+b+c+d=2=-p$
$(a+b+c+d)^2-a^2+b^2+c^2+d^2=2(ab+bc+cd+ad+ac+bd)=q=-13$
Finding $\sum abc$ and $abcd$ with the help of other inequalities and finding the roots of equation is another way to go. (Not quite sure whether constructing polynomial is a great way to go. )

Edit: I have considered the absolute values of $(a,b,c,d)$ . I didn't assume them to be $+ve$.

A: One way to approach such questions is to view $a, b, c, d$ as roots of a single quartic equation $x^4-s_1x^3+s_2x^2-s_3x+s_4=0$, when we have Vieta's relations
$$s_1=a+b+c+d$$$$s_2=ab+ac+ad+bc+bd+cd=(a+b)(c+d)+ab+cd$$$$s_3=abc+abd+acd+bcd$$$$s_4=abcd$$
We then let $p_k=a^k+b^k+c^k+d^k$ with: $$p_0=4$$$$p_1-s_1=0$$$$p_2-p_1s_1+2s_2=0$$$$p_3-p_2s_1+p_1s_2-3s_3=0$$
With the given values of $p_1, p_2, p_3$ these determine $s_1, s_2, s_3$.
For higher powers $(k\ge4)$ we have $$a^k-s_1a^{k-1}+s_2a^{k-2}-s_3a^{k-3}+s_4a^{k-4}=0$$ using the quartic equation. Adding together the corresponding equations for $a , b, c, d$ we obtain the recurrence for $p_k$$$p_k-s_1p_{k-1}+s_2p_{k-2}-s_3p_{k-3}+s_4p_{k-4}=0$$
Since we know $p_4$ we can use the recurrence to find $s_4$, and this is then sufficient to compute $p_5, p_6$ from the recurrence.
If this looks complicated, this is misleading. The relations between the elementary symmetric functions $s_r$ and the sums of powers $p_r$ are useful to know, and render this kind of problem essentially mechanical. You can see that you can solve the problem without solving explicitly for $a, b, c, d$.

Following this scheme we find successively $s_1=2, s_2=-13, s_3=-14, s_4=24$. Then the recurrence gives:$$p_5-2p_4-13p_3+14p_2+24p_1=0$$ and$$p_6-2p_5-13p_4+14p_3+24p_2=0$$
And this gives $p_5=812, p_6=4890$

A: I do not know how to solve it, but $a=-3,b=4,c=2,d=-1$

A: If you inspect the system you can see that the solutions for a,b,c,d are all going to have to be small integers. This constrains the system heavily.
 I managed to solve the system guessing some small numbers, testing them and tweaking minus signs to get the desired result.
After we have found a,b,c,d the fraction becomes trivial.
Any analytical method to solving this system would have to accommodate high order solutions and would inevitably be very complicated. I would like to see analytical solution but doubt any could be as efficient as trial and error in this case.


text:
Q: How can I create a shortcut for running an AppImage without the terminal in Gnome? I am using Navicat for MySQL on Ubuntu 18.04.4 LTS with the native Gnome UI. Prior versions of Navicat used Wine, but this version (15) provides an AppImage file which I have been launching from the terminal. Once launched, it ties up that terminal process until I exit Navicat. This annoys me.
I've found several walkthroughs that pertain to the Wine version on Unity, but nothing for running the AppImage on Gnome. Is there any way I can create a shortcut on the launcher bar (or wherever) in Gnome so I don't have to launch the process from a terminal window?

A: You could do it using appimaged:

*

*Download trial version of navicat15 from here

*chmod +x ~/Downloads/navicat15-mysql-en.AppImage

*mkdir ~/bin

*cp ~/Downloads/navicat15-mysql-en.AppImage ~/bin

*Download appimaged:
wget "https://github.com/AppImage/appimaged/releases/download/continuous/appimaged-x86_64.AppImage"

*chmod a+x appimaged-x86_64.AppImage

*./appimaged-x86_64.AppImage --install

*export PATH=$PATH:/home/user/.local/bin - optional, if your echo $PATH does not contain /home/user/.local/bin directory, where appimaged binary is copied. Could be added in ~/.bashrc

*Run it by appimaged -v - this command will register .AppImage file found in ~/bin directory

*After some time check Applications menu and find out Navicat 15 for MySQL there.

*Interrupt appimaged -v command execution by Ctrl+C.

Tested on Ubuntu 19.10 and Lubuntu 18.04.


text:
Q: Java Reusing interface methods This is the interface I'm using:
interface Command {
    void run(int a, int b, int c);
    void run(int a, int b, int c, int d, int e);
}

void add(Command c){

}

this is execution: (using the first run method)
    add((a, b, c) -> System.out.println(""));

The error i get on the execution is:
    The target type of this expression must be a functional interface

And this only goes away when i comment out the second run method.
I want to be able to execute the same interface using both run methods, and not have to create a new interface just to execute with method 2.
How?

A: A functional interface by design is allowed to have just one method so what you are trying to do can't be done directly, it's clear why: allowing to implement a functional interface with a lambda must create an object which is valid for its declaration, if it has two methods you cant implement them both with a single lambda.
A workaround could be to use variadic arguments, eg:
@FunctionalInterface
interface Command {
 void run(int... args);
}

add(args -> { int z = args[0] + args[1] + args[2]; });


text:
Q: Transferring Data from old to new PS3 So I needed a bigger PS3 and didn't transfer my data over right when I got my new one. I have some single player games that I got really far in saved on my old one but don't want to restart them on my new one. I plan on selling my old one soon so I want to transfer all my saved data over without deleting anything on my new PS3. Any way I can do that?

A: The PS3 system software has a built-in function that makes migration to another system easy and safe (no loss of save data or user data)
It can be done using one of the following 2 ways available:

*

*the backup and restore utility uses an external USB drive that is formatted to FAT32 and creating backup data that is restored on the new system.  Official documentation for this process is available at this link

*the data transfer utility uses an Ethernet cord to directly connect the two systems together and transferring/moving most of the system data over to the new console directly. Official documentation for this process is available at this link
Both of these processes are started from the system settings in the settings section of the XMB ( system menu)
Keep in mind that both processes completely wipe the system the data is being transferred to before the data is transferred.


text:
Q: Level based view color in Android I have numbers between 1 - 100. And every number has to change view's color.
What should I use? I think about using canvas but my image is like this:

If I use canvas, I have to know RGB algorithm for this image, don't I? It goes green to red.
I've stucked about this topic, what should I do? What do you recommend?
My Canvas class is;
public class CircleCanvasView extends View {

Paint paint;
Path path;
int level = 0;

public CircleCanvasView(Context context, int level) {
    super(context);
    init();
    this.level = level;
}

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

public CircleCanvasView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

private void init() {
    paint = new Paint();
    paint.setColor(Color.BLUE);
    paint.setStrokeWidth(10);
    paint.setStyle(Paint.Style.STROKE);

}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

    paint.setStyle(Paint.Style.STROKE);
    canvas.drawCircle(50, 50, 30, paint);

}

A:
If I use canvas, I have to know RGB algorithm for this image, don't I?
  It goes green to red.

Not really. What you need is an interpolator for your color. And you want to change the colors in-between in 100 steps. You have your startColor and your endColor, two int values. Through the color class you can get their single components:
int alpha = Color.alpha(startColor);
int red = Color.red(startColor);
int blue = Color.blue(startColor);
int green = Color.green(startColor);

and
int endalpha = Color.alpha(endColor);
int endred = Color.red(endColor);
int endblue = Color.blue(endColor);
int endgreen = Color.green(endColor);

and you want something like
   int cAlpha = alpha + factor * (endAlpha - alpha);
   int cRed = red + factor * (endAlpha - red);
   int cBlue = blue + factor * (endAlpha - blue);
   int cGreen = green + factor * (endAlpha - green);

with 0 <= factor <= 1
when factor is 0 you have the start components, when factor is 1 yoenter code hereu have the end componets. To get the color at each step:
 int colorAtStep = Color.argb(cAlpha, cRed, cBlue, cGreen);


text:
Q: Table with multiple Dependent Variables How can i create a table with the following data:
Initial Data Table:

End Table Result:

Here would be the code easily inputted into R (which I would read from csv file during operation):
Date = c(20170101,20170101,20170102,20170102,20170102,20170102,20170103)
Person = c("Adam","Adam","Adam","Ben","Ben","Ben","Ben")
Fruit = c("Apple", "Pear","Bananna","Blueberry","Cherry","Grape","Grape")
z= data.frame(Date,Person,Fruit)

A: The tapply() function can arrange values into a matrix object using the c function. The values get encapsulated in lists:
with(z, tapply(Fruit, list(Person,Date), FUN=c))

     20170101    20170102    20170103
Adam Character,2 "Bananna"   NULL
Ben  NULL        Character,3 "Grape"

You can then display that matrix object with pander:
library(pander)
panderOptions('keep.line.breaks', TRUE)
mytable <- with(z, tapply(Fruit, list(Person,Date), FUN=c))
pandoc.table(mytable, style="multiline")

----------------------------------------------------------
       20170101           20170102          20170103
---------- ----------- ------------------------ ----------
 **Adam**  Apple, Pear         Bananna             NULL

 **Ben**      NULL     Blueberry, Cherry, Grape   Grape
----------------------------------------------------------

If you want the lines separating the "cells" you can use style="grid". The output then looks like:
+----------+-------------+--------------------------+------------+
|  Person  |  20170101   |         20170102         |  20170103  |
+==========+=============+==========================+============+
|   Adam   | Apple, Pear |         Bananna          |            |
+----------+-------------+--------------------------+------------+
|   Ben    |             | Blueberry, Cherry, Grape |   Grape    |
+----------+-------------+--------------------------+------------+

If you use paste0 with collapse you can remove the commas and use linefeeds instead:
mytable <- with(z, tapply(Fruit, list(Person,Date), FUN=paste0,  collapse="\n"))

The structure of the matrix is now different, with each entry being a character value of length-1, but that then does get displayed in a pandoc table with each Fruit on a single line:
pandoc.table(mytable, style="multiline")  # or style ="grid" as above
#------------
-------------------------------------------
       20170101   20170102   20170103
---------- ---------- ---------- ----------
 **Adam**    Apple     Bananna       NA
              Pear

 **Ben**       NA     Blueberry    Grape
                        Cherry
                        Grape
-------------------------------------------


text:
Q: fatal: ambiguous argument when using git in my pipelines I am executing the following command :
npm run affected:build:dev -- --base="$(git rev-parse origin/develop^1)"
with expected output to be the hash of the previous commit in develop
ex once run
nx affected:build --configuration=develop "--base=09a1a7cf53c00a2010d907574710c71674acdf80"
this command works fine when I run on the terminal of my computer, but when running inside my bitbucket pipeline, it fails with the following error :
+ npm run affected:build:dev -- --base="$(git rev-parse origin/develop^1)"
fatal: ambiguous argument 'origin/develop^1': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
> anylogi-frontend@1.1.6 affected:build:dev
> nx affected:build --configuration=develop "--base=origin/develop^1"
fatal: Not a valid object name origin/develop^1
fatal: No such ref: 'origin/develop^1'
nx affected:build

I don't understand the cause, my pipeline is running the same versions as my local.
git version 2.25.1
node v16.13.0
npm 8.1.0
what is the syntax that git is expecting ?

A: Just in case the '^' in develop^1 is not correctly interpreted by the shell, try instead:
git rev-parse origin/develop~1

In your case, the first parent (^1) should be the same as the first generation ancestor of the named commit object (~1).
Try also a git log origin/develop in your pipeline, just to confirm that, in the context of said pipeline execution, there is indeed a history fetched and associated with origin/develop.


text:
Q: Finding norm of a linear functional.
Let $\{t_i\}_{i=1}^n$ be given points in the closed interval $[0,1]$. Let $\{\omega_i\}_{i=1}^n$ be given real numbers. Let $f\in C[0,1]$. Define
  $$\varphi(f) = \sum\limits_{i=1}^{n}{\omega_if(t_i)}.$$
  Show that $\varphi$ defines a continuous linear functional on $C[0,1]$ and that
  $$\|\varphi\| = \sum\limits_{i=1}^{n}{|\omega_i|}.$$

To show: $||\phi||=\sum_{i=1} ^n|\omega_i|$
I have done $||\phi||\le\sum_{i=1} ^n|\omega_i|$ by taking max$f(t_i)$ out of the sum.
How to show $||\phi||\ge\sum_{i=1} ^n|\omega_i|?$
I tried several functions but no one is leading to the result.
Can anyone help me out by figuring out the appropriate $f$?

A: Well, what about a function $f\in C([0,1])$ such that $f(t_i) = \text{sgn}(\omega_i)$ and $|f|\leq1$?

A: If $\mu$ is an atomic measure with atoms at $t_j$ with $\mu\{t_j\}=\omega_j$, then
$$
          \varphi(f) = \int_{0}^{1}f(t)d\mu(t).
$$
It follows from the Riesz representation for $C[0,1]^*$ that
$$
               \|\varphi\| = \|\mu\| = \sum_{j}|\omega_j|. \tag{$*$}
$$
You can prove $(*)$ directly in this case by choosing a function $f$ so that $f(t_j)w_j = |w_j|$ for $1 \le j \le n$, and so that $\|f\|=1$. Then
$$
     \sum_{j}|\omega_j|=\sum_{j}f(t_j)\omega_j=\varphi(f) \le \|\varphi\|\|f\|=\|\varphi\| \\
     \implies \sum_{j}|\omega_j| \le \|\varphi\|.
$$
And, as you noted, for a general $f\in C[0,1]$,
$$
       |\varphi(f)| = |\sum_{j}f(t_j)\omega_j| \le \sum_{j}|f(t_j)||\omega_j| \le \|f\|\sum_{j}|\omega_j| \\
    \implies \|\varphi\| \le \sum_{j}|\omega_j|.
$$
Hence, $\|\varphi\|=\sum_{j}|\omega_j|$.


text:
Q: ARKit, detect when tracking is available I'm looking for a way to detect when spacial tracking is "working/not working" in ARKit, i.e when ARKit has enough visual information to start the 3d spacial tracking.
In other apps i've tried, the user gets prompted to look around with the phone/camera to resume space tracking if ARKit doesn't get enough information from the camera. I have even seen apps with a progress bar showing how much more the user needs to move the device around to resume tracking.
Would a good way to detect if tracking is available to check how many rawFeaturePoints the ARSessions current frame has? E.g if the current frame has more than say 100 rawFeaturePoints, we can assume that spacial tracking is working.
Would this be a good approach, or is there built in functionality or better way in ARKit to detect if spacial tracking is working what i don't know about?

A: You could use feature points but I think that is probably overkill, as such something like this might be a good start:
Using the currentFrame of an ARSession you can get the current tracking state from like so:
//------------------------------------------------
//MARK: ARSession Extension To Log Tracking States
//------------------------------------------------

extension ARSession{

    /// Returns The Status Of The Current ARSession
    ///
    /// - Returns: String
    func sessionStatus() -> String? {

        //1. Get The Current Frame
        guard let frame = self.currentFrame else { return nil }

        var status = "Preparing Device.."

        //1. Return The Current Tracking State & Lighting Conditions
        switch frame.camera.trackingState {

        case .normal:                                                   status = ""
        case .notAvailable:                                             status = "Tracking Unavailable"
        case .limited(.excessiveMotion):                                status = "Please Slow Your Movement"
        case .limited(.insufficientFeatures):                           status = "Try To Point At A Flat Surface"
        case .limited(.initializing):                                   status = "Initializing"
        case .limited(.relocalizing):                                   status = "Relocalizing"

        }

        guard let lightEstimate = frame.lightEstimate?.ambientIntensity else { return nil }

        if lightEstimate < 100 { status = "Lighting Is Too Dark" }

        return status

    }

}

Which you would call something like this in the ARSCNViewDelegate callback:
 func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {

      DispatchQueue.main.async {

            //1. Update The Tracking Status
            print(self.augmentedRealitySession.sessionStatus())

      }
 }

There are also other delegate callbacks you can use as well e.g:
func session(_ session: ARSession, didFailWithError error: Error) {

    print("The ARSession Failed")
}

func sessionWasInterrupted(_ session: ARSession) {

    print("ARSession Was Interupted")
}

These ARKit Guidelines also provide some useful information as how to handle these states: Apple Guidelines
If you do actually want to track the number of featurePoints however you can do something like this:
func renderer(_ renderer: SCNSceneRenderer, updateAtTime time: TimeInterval) {

    guard let currentFrame = self.augmentedRealitySession.currentFrame,
    let featurePointCount = currentFrame.rawFeaturePoints?.points.count else { return }

    print("Number Of Feature Points In Current Session = \(featurePointCount)")

}

And if you want to see an example you can have a look here: Feature Points Example
Hope it helps...


text:
Q: how to find latitude and longitude of a user while GPS is on I have developed an android application in which gps of the is turn on any time. Now how i can find the latitude and longitude of the user. Please help me

A: To access current location information through location providers, we need to set permissions with android manifest file.
<manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
</manifest>

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app. But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of network provider.
Create LocationManager instance as reference to the location service
For any background Android Service, we need to get reference for using it. Similarly, location service reference will be created using getSystemService() method. This reference will be added with the newly created LocationManager instance as follows.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

Request current location from LocationManager
After creating the location service reference, location updates are requested using requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance and the LocationListener object over which the location to be updated.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

Receive location update from LocationListener on change of location
LocationListener will be notified based on the distance interval specified or the number seconds.
This example provides current location update using GPS provider. Entire Android app code is as follows,
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}

@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

XML files for layout and android manifest are as shown below
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity" >

        <TextView
            android:id="@+id/textview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="@string/hello_world" />

    </RelativeLayout>


text:
Q: Handling Multiple GridViews in ASP.Net and C# I Have a Table column Called Status which takes three Values 1, 2 or 3. Now, I  want to Display another column Name1 in either of the three GridViews depending on the Status. Also I have link buttons which Redirect to different web forms.
This is the output I'm Getting. The ID of this GridView is GridView1

This is the code I've used
Markup:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Admin.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html>

    <title></title>

    <form id="form1" runat="server">

    <asp:GridView ID="GridView" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
            AutoGenerateColumns="false" Height="225px" Width="368px"
            >
         <Columns>
                <asp:BoundField DataField="Name1" HeaderText="File Name" />
                <asp:BoundField DataField="Status" HeaderText="Status" />
                 <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application" OnClick="EditFile"
                            CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
     </asp:GridView>
      <asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
            AutoGenerateColumns="false" Height="225px" Width="368px"
            >
         <Columns>
                <asp:BoundField DataField="Name1" HeaderText="File Name" />
                <asp:BoundField DataField="Status" HeaderText="Status" />

                 <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application" OnClick="EditFile1"
                            CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
     </asp:GridView>
      <asp:GridView ID="GridView2" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
            AutoGenerateColumns="false" Height="225px" Width="368px"
            >
         <Columns>
                <asp:BoundField DataField="Name1" HeaderText="File Name" />
                <asp:BoundField DataField="Status" HeaderText="Status" />

                 <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkEdit" runat="server" HeaderText="Edit Status" Text="Edit Application"
                            CommandArgument='<%# Eval("Status") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
     </asp:GridView>

    </form>

C#
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;

using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    String statusVariable= string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
         //lb1.Text = "" + "WELLCOME ADMIN:: " + "" + "" + Session["name"] + "";
        if (!IsPostBack)
        {
            BindGrid();
        }
    }

    private void BindGrid()
    {
        DataTable dt;
        string constr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "Select Name1,Status from TBL_MST_ALL2";
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    {
                        while (reader.Read())
                        {
                            if (reader["Status"].ToString() == "3")
                            {
                                GridView.DataSource = reader;
                                GridView.DataBind();
                            }
                            else if (reader["Status"].ToString() == "2")
                            {
                                GridView1.DataSource = reader;
                                GridView1.DataBind();
                            }
                            else if (reader["Status"].ToString() == "1")
                            {
                                GridView1.DataSource = reader;
                                GridView1.DataBind();
                            }
                        }
                        con.Close();
                    }
                }
            }
        }
    }

    protected void EditFile(object sender, EventArgs e)
    {
        Response.Redirect("EditResume.aspx");
    }

    protected void EditFile1(object sender, EventArgs e)
    {
        Response.Redirect("EditResume1.aspx");
    }
}

However, all the data is being displayed in GridView1 regardless of the Status.


text:
Q: Does a PMML Debugger exist that could help find PMML syntax and/or logic errors? I have spent a lot of time during the last few weeks dealing with PMML files that have bad syntax or logic errors.  My current process involves looking at the PMML file and stepping through JPMML code until I can figure out what's wrong.
Common issues I have found,

*

*Variable in PMML not defined anywhere

*DerivedField If-Else statement falls through to a missing variable and does not use missingValueReplacement

*Attempted multiplication of string values

*invalidValueTreatment defined in MiningSchema of categorical variable that is not enumerated in the DataDictionary which means that the invalidValueTreatment would never be used.

What debugging tools are available for PMML?
Any tools to help with Syntax or Logic debugging would be helpful.

A: There are probably no such tools available yet. My logic goes that a debugger would be built on top of an evaluator. Since the JPMML-Evaluator library is the state-of-the-art evaluator, and it does not provide dedicated debugging tools, then it's hard to see how some other tool could beat it in this area.
When debugging PMML, you can have two types of issues. First, there are "static errors" that relate to the structure of the PMML document such as missing, invalid or misplaced XML elements and attributes. They can be discovered by performing XML validation against PMML XSD file, or using JPMML-Model Visitor APIs. Second, there are "dynamic errors" that relate to the evaluation path of some data record. For example, as you just pointed out, it may happen that a categorical field is assigned a value for which there is no handler.
The JPMML-Evaluator library should throw an exception whenever it detects an error condition. If you have SAX Locator information enabled, then the exception message provides the line number of the offending PMML content. Of course, the debugging work would be much easier if the JPMML-Evaluator library did proper logging.
You could also try analyzing the source code of your PMML producer application. Why is it doing so in the first place?


text:
Q: Broken linechart Windows Form, I want to add a broken line to my linechart. I am setting the YValue as double.NaN when there are no YValue to show.
It works fine except for the first point where it draws a vertical line as seen in the picture. How can I get rid of that one?

A: There is no code in the question, but it would automatically work with double.NaN if you used the DataBindXY method on the Points property of the chart series, so I assume you are adding the DataPoints manually.
In this case, the IsEmpty property of the DataPoint must be set to true. So, if you create the DatePoints from the x/y values (for example, from two arrays with the actual values), you can set the IsEmpty property accordingly by checking the y value with:
 double.IsNaN(yValue)

A simple self-contained example might look something like this:
private readonly int[] _xArr = new int[] { 1, 2, 3, 4, 5 ,6, 7 };
private readonly double[] _yArr = new double[] { double.NaN, 0.9, 1.2, double.NaN, 1.3, 1.1, 1.4 };

private IEnumerable<DataPoint> DataPoints()
{
    return _xArr.Select((x, i) => new DataPoint(x, _yArr[i]) { IsEmpty = double.IsNaN(_yArr[i])});
}

For completeness, here a simple chart setup for a quick test:
private void Form1_Load(object sender, EventArgs e)
{
    var series = chart1.Series[0];

    series.LegendText = "Some Chart";
    series.ChartType = SeriesChartType.Line;
    series.IsValueShownAsLabel = true;
    foreach(var dp in DataPoints())
    {
        series.Points.Add(dp);
    }
}

The example would then look something like this with the data from above:

As one can see, this displays missing start points and interruptions as desired.


text:
Q: Functor from $\textbf{Top}$ to $\mathcal{H}$ Let $\mathcal{H}$ be the homotopy category of spaces; i.e. $\mathcal{H}$ has as its objects the CW complexes and as its morphisms the homotopy classes of maps between them. I'm trying to understand the slogan that, by Whitehead's theorem, $\mathcal{H}$ is obtained by "formally inverting" the weak homotopy equivalences in $\mathbf{Top}$, but something is not entirely clear to me.
In particular, for any topological spaces $X$, we know there is a CW complex $X'$ and a canonical weak homotopy equivalence $\phi:X'\rightarrow X$, and that $X'$ is unique up to strong homotopy equivalence. The claim I've heard is that this means the object map $X\mapsto X'$ induces a functor $\mathbf{Top}\rightarrow \mathcal{H}$. Can someone enlighten me as to the details of this functor? In particular, I don't see what the map $X'\rightarrow Y'$ in $\mathcal{H}$ induced by an arbitrary map $f:X\rightarrow Y$ in $\mathbf{Top}$ should be; because weak homotopy equivalence is not a symmetric relation there doesn't seem to me to be canonical choice. Sorry if this is a stupid question or if I'm missing something obvious.

A: Given a map $f:X\to Y$, let $\phi_X:X'\to X$ and $\phi_Y:Y'\to Y$ be the canonical weak equivalences.  In particular, since $\phi_Y$ is a weak equivalence, it induces a bijection between homotopy classes of maps $K\to Y$ and homotopy classes of maps $K\to Y'$ for any CW-complex $K$.  In particular, taking $K=X'$ and considering the map $f\phi_X:X'\to Y$, this says there is a map $f':X'\to Y'$, unique up to homotopy, such that $\phi_Yf'$ is homotopic to $f\phi_X$.  This map $f'$ (or rather, its homotopy class) is where your functor sends $f$.  (The fact that this preserves composition follows from the uniqueness of $f'$: if $f:X\to Y$ and $g:Y\to Z$, then $g'f'$ satisfies $\phi_Zg'f'\simeq gf\phi_X$, and so $g'f'$ must be homotopic to $(gf)'$.)


text:
Q: code works in script editor, but not when run from command line I'm trying to pipe an expression result into a maya text object for use as a heads up display. My script works from the script editor, but not when called from the command line or from my display expression. How can I change this to make it work from the command line?
import maya.cmds as cmds

# convert a string to hex values, separated by a space

typeNode = cmds.ls( selection=True )
type3d = cmds.listConnections(t='type')
typeValue = cmds.getAttr( 'tower_CON.Spin' )

valueList=list(str('{:3.2f}'.format(typeValue)))

hexVersion=""

for x in valueList:
    hexValue=x.encode("hex")
    hexVersion=hexVersion + hexValue + " "

cmds.setAttr(str(type3d[0]) + ".textInput", hexVersion.rstrip(), type="string")

A: From the error in you're comments, it looks like you're trying to run the module as a function.
You probably need to save this in the file:
import maya.cmds as cmds

def text_to_hud():
    # convert a string to hex values, separated by a space

    typeNode = cmds.ls( selection=True )
    type3d = cmds.listConnections(t='type')
    typeValue = cmds.getAttr( 'tower_CON.Spin' )

    valueList=list(str('{:3.2f}'.format(typeValue)))

    hexVersion=""

    for x in valueList:
        hexValue=x.encode("hex")
        hexVersion=hexVersion + hexValue + " "

    cmds.setAttr(str(type3d[0]) + ".textInput", hexVersion.rstrip(), type="string")

and then in the command line you'd want
import textToolHUD as th; th.text_to_hud()

You could also keep the file as is and just do
import textToolHUD

which would run once, but it's bad practice to rely on code that runs on import.


text:
Q: how to assign id field in form_label CodeIgniter My question is in the title, how to assign id field in form_label CodeIgniter.
I have form label :
echo form_label('Titre', 'titre');

Because I need 'id' to delete this label with javascript.
Thanks,
Vincent.

A: Try like this
$attributes = array(
'class' => 'mycustomclass',
'style' => 'color: #000;',
'id'    => 'id',
);
echo form_label('What is your Name', 'username', $attributes);

A: codeGodie is right labels should not have id instead to text box or any other input field you can add id as
<?=form_input(array("name"=>"some","id"=>"some","value"=>set_value("some"),"placeholder"=>"some","class"=>"Some"))?>

plz read the documentation of https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html for further reference


text:
Q: Entity Framework: Creating single entity from related, cascading tables I am working with a database contains related tables for storing person address details. The following tables store the information – County, City Suburb, Address and Address Type.
The Address table holds street and house number information in addition to AddressTypeId (Associated to AddressType Table).  The Address table also has a SuburbId column for the association with the Suburb table. The associations of a person's address cascade down to the County table.
I want the Person data object to have an IList property. What would be my best approach to achieve this?

*

*Use a stored procedure to generate the Address entity on the Entity designer.

*Create a complex type and add this to the Person type as IList.

There might be some other recommended way than the above options. If there is a step-by-step example some one could point me to, that would be great.

A: As far your question you can write a stored procedure that gets all the address information. Have a select statement at the end of your stored procedure selecting all of the address information.
When you add this procedure entity framework(4.0 I assume)...you can create a function import and ef4 will create an complex type for return of your stored procedure. Here is a  tutorial.


text:
Q: java conversion from double to int for certain numbers import java.util.Scanner;
public class Test1C
{
    public static void main(String[] args)
    {
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter an integer between 1 and 50: ");

        double quo;
        int num = reader.nextInt();

        for(double a = 1; a <= num; a++)
        {
            quo = (num / a);
            System.out.println(quo);
        }
    }
}

This is the code I currently am making to evaluate the list of quotients based on what number was inputted. Now the only thing my brain keeps farting on about is how to convert the whole numbers that are currently decimals into integers. However, the doubles (ex: 1.333) that are printed by this code are fine as is. I just can't figure out how to convert the whole number decimals (ex: 12.0) into whole number integers. Can someone help me?

A: you can do like that .
Double d = new Double(1.25);
int i = d.intValue();
System.out.println("The integer value is :"+ i);

A: yes you can :
String s = "1.333";
double d = Double.parseDouble(s);
int i = (int) d;

or
String s="1.333";
int i= new Double(s).intValue();

A: There is no general way to detect whether a double is truly an integer and a comparison of double and double or int must, generally, be handled with much care, but for the range of numbers in your program (and the upper bound could be raised considerably), this will work as you want:
    for(double a = 1; a <= num; a++)      {
        double quo = num/a;
        int iquo  = (int)quo;
        if( iquo == quo ){
           System.out.println(iquo);
        } else {
           System.out.println(quo);
        }
    }


text:
Q: Facebook Like Box doesn't work I've been having a problem with a facebook like-box for a client, and me and a friend simply can't figure out what we're doing wrong, and it's been close to three days of staring at it. Here's the code we get from developers.facebook.com:

Nothing shows up. We did get this piece of code to work, but it doesn't quite work the way we want to:

<fb:like-box href="http://www.facebook.com/pages/mywebsite/1111111111" width="280" colorscheme="dark" show_faces="true" border_color="" stream="true" header="false"></fb:like-box>

You have to log in to facebook to see the feed, but the client want it to always show up.

A: You need to add http: in line 5 of the head script like this...
js.src = "http://connect.facebook.net/en_US/all.js#xfbml=1";

its a html5 thing.

A: Perhaps you should try the latest code; Facebook appear to have modified the Like box generator.


text:
Q: Message box in C in Linux I want to display a "SUCCESSFUL" pop-up message after executing my program in C in Linux.
It should run on both KDE and GNOME. How can I do this?

A: You are looking for desktop notifications.  I believe both KDE and GNOME support them.  Here is a (Gtk+-based) library you can use for your program's end.

A: Zenity (GNOME) and kdialog (KDE) are similar in a lot of respects.  Both will let you pop up a GUI notification.  If you just want to send something to the notification area in gnome notify-send does the trick.  I believe that kdialog will allow you to do something similar in KDE.  I don't know of a common tool between the two UIs.


text:
Q: Range based for-loop for priority_queue Defining my priority_queue like this,
priority_queue<int> parts(start, start+N, less<int>());

the following code won't compile
for(int t : parts){
    ...
}

Which leads me to question:
In C++11, are range based for loops allowed for std::priority_queue?
In general, which structures are allowed to be iterated trough using a range based for-loop?
I know I can do pretty much the same thing like this:
while(!parts.empty()){
    cout << "Next element: " << parts.top() << endl;
    parts.pop();
}

Is it possible to iterate trough the queue nevertheless?

A: No, std::priority_queue does not support the range-based for loop.
The range-based for loop works on arrays and on classes that have begin() and end() member functions. This includes all containers in the C++ standard library as well as std::string (and its basic_string cousins) but not stacks, queues, or priority queues which are container adaptors and do not expose iterators.


text:
Q: redirecting files with html extension to files without extension (in url) I have recently changed my website url using htaccess so that my urls will not show file extensions. Now my problem is as I have created a new xml sitemap so that my url will be extensionless!!! the Google webmaster tool is telling me about duplicate content issue!! ie. page and page.html have same title.... so my question is how do i redirect the urls with file extension html to urls with out extension!!!
this is an example of my website url with html extension
http://www.shenazhpeyk.co.uk/coding-machines.html
I want to redirect and change it to
http://www.shenazhpeyk.co.uk/coding-machines
so that will fix the issue with Google webmaster tools (Please provide me a code for use in htaccess file)
Many Thanks

A: Found this code as well.  Not sure if it will accomplish the same thing.  Seems to work for me as does the one above (for PHP).
RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ /$1 [R=301,L]

# Redirect external .php requests to extensionless url
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ /$1 [R=301,L]

# Resolve .php file for extensionless php urls
RewriteRule ^([^/.]+)$ $1.php [L]

I am wondering about the trailing slashes and whether those should be there or omitted?

A: Try adding the following to the .htaccess file in the root directory of your site redirect URLs with .html extension and remove it.
RewriteEngine on
RewriteBase /

#redirect to remove the .html extension
RewriteRule ^(.+)\.html$ $1 [L,NC,R=301]

A: Try this:
Options +FollowSymLinks -MultiViews
DirectorySlash Off

RewriteEngine On

RewriteCond %{SCRIPT_FILENAME}/ -d
RewriteCond %{SCRIPT_FILENAME}.html !-f
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^(.+)\.html$ /$1 [R=301,L]

RewriteCond %{SCRIPT_FILENAME}.html -f
RewriteRule [^/]$ %{REQUEST_URI}.html [QSA,L]


text:
Q: What are the practical uses for strings? I have been following some Fortran tutorials online and have recently come across strings. I was just wondering... what are the practical uses of them? It's probably just a beginner's oversight, but I just can't think of any projects you can do with strings. Please, enlighten me!

A: Strings are... everywhere, and in everything. Have a look at the string tag for >100,000 examples.
Strings are how you store text, like how integers and reals are how you store numbers. So anywhere you want to work with words you need strings.
Even in the simplest of programs, hello world, the "Hello, World!" is a string. And the ultimate test for computers, the Turing Test is dependent on strings to work.
If you want some practice projects, just do a web search for "string problems" or similar. You'll get hundreds of pages of example problems.


text:
Q: quarkus start fails with AppModel init exception I have been trying to integrate quarkus into my multi module gradle project. The project where I am importing it happens to be a module in this structure.
Root Project > Module A > Module B

Using Environment: Gradle 6.3,  GraalVM - JDK 8 and IDE -IntellijIdea 2020 .

The project does not give any web resource output but like a core java app.
So, I am running it with Quarkus.run(MyProblemSolver.class, args);
This throws an exception of

*

*Exception is:
  org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':moduleA:childModule:quarkusDev'.
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:205)
      at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:263)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:203)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:184)
      at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:114)
      at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
      at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:62)
      at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
      at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
      at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
      at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
      at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
      at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
      at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
      at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
      at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:41)
      at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:372)
      at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:359)
      at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:352)
      at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:338)
      at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.lambda$run$0(DefaultPlanExecutor.java:127)
      at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:191)
      at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:182)
      at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:124)
      at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
      at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
      at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
  Caused by: java.lang.NoSuchMethodError: io.quarkus.bootstrap.model.AppModel.(Lio/quarkus/bootstrap/model/AppArtifact;Ljava/util/List;Ljava/util/List;)V
      at io.quarkus.gradle.AppModelGradleResolver.resolveModel(AppModelGradleResolver.java:173)
      at io.quarkus.gradle.tasks.QuarkusDev.startDev(QuarkusDev.java:239)
      at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:104)
      at org.gradle.api.internal.project.taskfactory.StandardTaskAction.doExecute(StandardTaskAction.java:49)
      at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:42)
      at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:28)
      at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:727)
      at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:694)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$3.run(ExecuteActionsTaskExecuter.java:568)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
      at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
      at org.gradle.internal.operations.DelegatingBuildOperationExecutor.run(DelegatingBuildOperationExecutor.java:31)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:553)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:536)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.access$300(ExecuteActionsTaskExecuter.java:109)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.executeWithPreviousOutputFiles(ExecuteActionsTaskExecuter.java:276)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$TaskExecution.execute(ExecuteActionsTaskExecuter.java:265)
      at org.gradle.internal.execution.steps.ExecuteStep.lambda$execute$1(ExecuteStep.java:33)
      at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:33)
      at org.gradle.internal.execution.steps.ExecuteStep.execute(ExecuteStep.java:26)
      at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:67)
      at org.gradle.internal.execution.steps.CleanupOutputsStep.execute(CleanupOutputsStep.java:36)
      at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:49)
      at org.gradle.internal.execution.steps.ResolveInputChangesStep.execute(ResolveInputChangesStep.java:34)
      at org.gradle.internal.execution.steps.CancelExecutionStep.execute(CancelExecutionStep.java:43)
      at org.gradle.internal.execution.steps.TimeoutStep.executeWithoutTimeout(TimeoutStep.java:73)
      at org.gradle.internal.execution.steps.TimeoutStep.execute(TimeoutStep.java:54)
      at org.gradle.internal.execution.steps.CatchExceptionStep.execute(CatchExceptionStep.java:34)
      at org.gradle.internal.execution.steps.CreateOutputsStep.execute(CreateOutputsStep.java:44)
      at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:54)
      at org.gradle.internal.execution.steps.SnapshotOutputsStep.execute(SnapshotOutputsStep.java:38)
      at org.gradle.internal.execution.steps.BroadcastChangingOutputsStep.execute(BroadcastChangingOutputsStep.java:49)
      at org.gradle.internal.execution.steps.CacheStep.executeWithoutCache(CacheStep.java:159)
      at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:72)
      at org.gradle.internal.execution.steps.CacheStep.execute(CacheStep.java:43)
      at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:44)
      at org.gradle.internal.execution.steps.StoreExecutionStateStep.execute(StoreExecutionStateStep.java:33)
      at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:38)
      at org.gradle.internal.execution.steps.RecordOutputsStep.execute(RecordOutputsStep.java:24)
      at org.gradle.internal.execution.steps.SkipUpToDateStep.executeBecause(SkipUpToDateStep.java:92)
      at org.gradle.internal.execution.steps.SkipUpToDateStep.lambda$execute$0(SkipUpToDateStep.java:85)
      at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:55)
      at org.gradle.internal.execution.steps.SkipUpToDateStep.execute(SkipUpToDateStep.java:39)
      at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:76)
      at org.gradle.internal.execution.steps.ResolveChangesStep.execute(ResolveChangesStep.java:37)
      at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:36)
      at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsFinishedStep.execute(MarkSnapshottingInputsFinishedStep.java:26)
      at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:94)
      at org.gradle.internal.execution.steps.ResolveCachingStateStep.execute(ResolveCachingStateStep.java:49)
      at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:79)
      at org.gradle.internal.execution.steps.CaptureStateBeforeExecutionStep.execute(CaptureStateBeforeExecutionStep.java:53)
      at org.gradle.internal.execution.steps.ValidateStep.execute(ValidateStep.java:74)
      at org.gradle.internal.execution.steps.SkipEmptyWorkStep.lambda$execute$2(SkipEmptyWorkStep.java:78)
      at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:78)
      at org.gradle.internal.execution.steps.SkipEmptyWorkStep.execute(SkipEmptyWorkStep.java:34)
      at org.gradle.internal.execution.steps.legacy.MarkSnapshottingInputsStartedStep.execute(MarkSnapshottingInputsStartedStep.java:39)
      at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:40)
      at org.gradle.internal.execution.steps.LoadExecutionStateStep.execute(LoadExecutionStateStep.java:28)
      at org.gradle.internal.execution.impl.DefaultWorkExecutor.execute(DefaultWorkExecutor.java:33)
      at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:192)
      ... 30 more

I am not sure what am I  missing in my configuration. The other gradle commands of adding  ?extensinos and listing them work fine but not quarkusDev or buildNative.
Can someone point me what am I doing wrong since there are less talks about the same on internet yet.

A: I have fixed it though. The problem was with the version in settings.gradle for pluginVersion field , I was using an old one and the same correction in classpath of build.gradle . Atleast that fixed the model error . Have other errors but this question can be closed. The version being uses was

1.0.1

whereas

1.4.2.Final

had to be used.