text:
Q: What is the correct way to implement server timer in intraweb usersession I have a simple intraweb project with the following structure
Usersession :
Have a timer to check the database and load the changes, do some data-formatting and put the results into a in memory table.
MainForm :
Have a IWTimer to check if the in memory table in Usersession changed and update its content if needed.
I do not use the IWTimer to check the database directly because I do not want some wait time in the browser which affect user experience.
The problem is that the usersession seems do not have a message queue and normal timer won't work.  So, I used JvThreadTimer in Jedi VCL instead.  I create it in UserSession.Create event and Stop and Free it in Destroy Event.  It do the work fine.
However, when I close the server application, it immediately pop up EidClosedSocket with message 'Disconnected'.  The exception fired before the Destroy Events in MainForm / Usersession / ServerControl Unit so I cannot find a way to stop the Timer before it trigger the exception.
So is there a proper way to set up a server side timer in usersession or are there other way of doing the periodical database checking which do not affect browser usage?
Thanks in advance for any help.

A: First. Don't use VCL stuff and window handle relying stuff within a non window application like a service/webserver.
The easiest way to fullfill that requierement is to use a Thread with an event object which is dispatched when the application starts.
It should look something like this:
type
  TTimerThread = class(TThread)
  private
    fSig : TSimpleEvent;
    procedure DoTimer;
  protected
    procedure Execute; override;
  public
    procedure SignalTerminate;

    constructor Create;
    destructor Destroy; override;
  end;

{ TSessionGarbageCollector }

constructor TTimerThread .Create;
begin
     fSig := TSimpleEvent.Create;

     inherited Create(False);
end;

destructor TTimerThread.Destroy;
begin
     fSig.Free;

     inherited;
end;

procedure TTimerThread.Execute;
begin
     try
        // e.g. every 10 seconds
        while fSig.WaitFor(10000) = wrTimeout do
        begin
             if Terminated then
                break;

             try
                // #################################################
                // #### Run the garbage collector from time to time
                DoTimer;
             except
                   on E : Exception do
                   begin
                        // your timer specific exception handling here
                   end;
             end;
        end;
     except
           on F : Exception do
           begin
                // your global exception handling here
           end;
     end;
end;

procedure TSessionGarbageCollector.DoTimer;
begin
     // whatever you like your timer to do
end;

procedure TSessionGarbageCollector.SignalTerminate;
begin
     Terminate;

     fSig.SetEvent;
end;

Also note that you should not dispatch the thread within the initialization clause if your module is a dll (like an isapi dll). Look for a place where you know that dllmain has already been processed.


text:
Q: Como fazer uma "compilação" do código em Python? Sabendo que Python é uma linguagem interpretada, existe alguma forma de compilar o programa em Python? Com isso quero dizer, como verificar os erro de sintaxe sem ter que esperar tal parte do programa ocorrer para a verificação.
Pois os erros só são mostrados em terminal ou IDE em tempo de execução.

A: Você pode só gerar o bytecode através dos módulos py_compile e compileall. Para usá-lo precisa usar a opção -m:
python -m py_compile arquivo.py

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get last log from all partition in ConsumerGroup I need to get last log from all partition in consumerGroup, in one consumerGroup may be partition from different topic.
I don't log to groupID so i couldn't use consumer.subscribe(sth topic)
@PostConstruct
public void connectionKafkaConsumer(){
    Properties props = new Properties();
    props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "xyz");
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");
    props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
    props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.IntegerDeserializer");
    props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
    consumer = new KafkaConsumer(props);
}

public void getLog(List<TopicPartition> topicPartitions) {
    consumer.assign(topicPartitions);

    for (TopicPartition topicPartition : topicPartitions) {
        long endPosition = consumer.position(topicPartition);
        long recentMessagesStartPosition = endPosition - 1;
        if (recentMessagesStartPosition < 0) {
            System.out.println("None message.");
            return;
        }

        consumer.seek(topicPartition, recentMessagesStartPosition);
        ConsumerRecords records;
        try {
            records = consumer.poll(2000);
        } catch (SerializationException e) {
            System.out.println(e.getMessage());
            return;
        }

        Iterator iter = records.iterator();

        while (iter.hasNext()) {
            ConsumerRecord consumerRecord = (ConsumerRecord) iter.next();
            System.out.println(consumerRecord.toString());
        }
    }
}

I expect the output of last log from all partition, but the actual output is
org.apache.kafka.common.errors.SerializationException:
Error deserializing key/value for partition my_partition at offset 16634750.
If needed, please seek past the record to continue consumption.

The line giving the exception is records = consumer.poll(2000);

A: I resolved my problem, KEY_DESERIALIZER_CLASS_CONFIG should be String in some my kafka topić/particion. I haven't notice this before that key is sometimes String.


text:
Q: Integration Tests with Microservices (NodeJS), Jenkins and Docker How would you typically configure Jenkins to build microservices (multiple NodeJS services, Rabbit, Mongo, etc), then test those services all together ?
Let's say I've the following services:

*

*RabbitMQ

*Mongo

*NodeJS Service 1

*NodeJS Service 2

Each of them has their own tests (unit and integration) and their Dockerfile.
I want to configure Jenkins in a way that it would enable me to clone all theses services, run them all at the same time in different containers with Rabbit and Mongo containers along them. It would then run the tests for each of those services (they do generate TAP and coverage reports). Then take those reports for the TAP/Coverage Jenkins plugins. If it works out, commit the image and push it to the docker registry.
I've been lying around Stack and Google and I don't really see an easy way to get there that would not imply tons of bash.
Maybe I see it in the wrong way, any input is more than welcome!

A: You can test using an "consumer driven contract" approach.
Like mentioned here:
https://medium.com/@sagansystems/integration-testing-our-microservices-for-fun-and-profit-b749ef42703b#.q7dyxgfrn
using this project:
https://github.com/realestate-com-au/pact


text:
Q: Filter signal through convolution I am a little bit unsure if I've set up the following problem correctly:
Consider the signal
$$f(t) = e^{-t}(\sin(5t) + \sin(3t) + \sin(t) + \sin(40t)) \quad 0 \leq t \leq \pi$$
Filter this signal with the filter:
$$h(t) = Ae^{- \alpha t} \quad t \geq 0$$
$$h(t) = 0 \quad t < 0$$
for $0 \leq t \leq \pi$.  Try various values of $A = \alpha$ (starting with $A = \alpha = 10)$.  Compare the filtered signal with the original signal.
Now, I have tried to set up this as follows (for $A = \alpha = 10$):
$$(f \ast h)(t) = \int_{0}^{\pi} 10 e^{-10(t - \tau) - \tau}(\sin(5 \tau) + \sin(3 \tau) + \sin(\tau) + \sin(40 \tau)) d \tau$$
$$= \int_{0}^{\pi} 10 e^{-10t + 9 \tau}(\sin(5 \tau) + \sin(3 \tau) + \sin(\tau) + \sin(40 \tau)) d \tau$$
Unfortunately I don't have MatLab available right now, so I tried running this through WolframAlpha, but was unable to get any computation made. To simplify it, I chose $t = 1$, and ran it through WolframAlpha again.  But this yielded the result $5.95 \cdot 10^7$ which seems way too high.
So my question is - have I set up this problem in the wrong way?  Any help will be greatly appreciated!

A: Check your assumptions for $f(t)$ and $h(t)$: the bounds on $t$ seem artificial, and in the case of $h$, arbitrary.
Note also that the convolution of two functions $f(t)$ and $h(t)$ in the context of an inverse Laplace transform of the product of their transforms $\hat{f}(s)$ and $\hat{h}(s)$, respectively, is
$$(f*h)(t) = \int_0^t d \tau \: f(\tau) h(t - \tau) $$
If I remove the bounds on $f(t)$ and $h(t)$, I get
$$ (f*h)(t) =  A \frac{e^{-a t}+e^{-t} ((a-1) \sin (t)-\cos (t))}{a^2-2 a+2}+A \frac{3 e^{-a
   t}+e^{-t} ((a-1) \sin (3 t)-3 \cos (3 t))}{a^2-2 a+10}+A \frac{5 e^{-a t}+e^{-t}
   ((a-1) \sin (5 t)-5 \cos (5 t))}{a^2-2 a+26}+A \frac{40 e^{-a t}+e^{-t} ((a-1)
   \sin (40 t)-40 \cos (40 t))}{a^2-2 a+1601} $$


text:
Q: Alternative unistd.h header file for Visual Studio 2010 I am compiling the code in Visual Studio 2010 which includes header file unistd.h. Since windows does not have any support for the   header file unistd.h , I am looking for the alternative header file or is there any way to customize it so that I can compile it in Visual Studio as well.

A: Your best bet, rather than trying to fit an inappropriate header file into Windows, is simply to remove the line:
#include <unistd.h>

then try and compile your code.
You may find (if you're extremely lucky) that it uses no features of that at all.
However, more likely is that there are certain things that it will use from that header and any associated libraries, and you will need to either implement these or find a Windows equivalent.
If you wanted to keep the code as portable as possible, I would create a WindowsUniStd.h file  (and an associated source file) to implement the bare minimum needed by the program.

A: Try include io.h, it's equivalent of unistd.h in MSVC. if you want to maintain the compatibility, try this:
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif

A: If you need a minimal GNU environment for windows with some of the functionality of unistd.h, you would look to the MinGW project first. If you're lucky, you can get away without using their compiled libraries at all.
If that isn't enough, you are into porting a program, and you are porting onto the bad system. Windows is computational backwater, providing a full unistd.h is a Herculean task, and you're probably better of either rewriting the application to remove references to unistd.h or using Cygwin.


text:
Q: 400 Error with Javascript Rdio API Any thoughts on why I'm getting a "Failed to load resource: the server responded with a status of 400 (Bad Request)" in the Javascript on my client? (client-id obscured, I have one for an Oauth2.0 app via registration Rdio site)
index.html:
 <script src="https://www.rdio.com/api/api.js?client_id=12345678"></script>

response:
https://www.rdio.com/oauth2/authorize/auto?response_type=token&client_id=12345678&showSignup=true&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fhelper.html%3Fclient_id%3D12345678

Failed to load resource: the server responded with a status of 400 (Bad Request)

John

A: The response text from the https://www.rdio.com/oauth2/authorize/auto request should reveal the error. For example, making a request from the shell:
$ curl "https://www.rdio.com/oauth2/authorize/auto?response_type=token&client_id=12345678&showSignup=true&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Fhelper.html%3Fclient_id%3D1234567"

For a valid client ID, a possible response might be:

Invalid redirect_uri

If this is the error you're receiving, which seems likely, to resolve it, you need to add your redirect_uri's domain to the Redirect URIs in your Rdio application's settings.


text:
Q: How to use the API Name in Marketo integration? I have created a custom activity in Marketo with a field called Permalink and its API name is permalink.
Using the POST /rest/v1/activities/external.json endpoint, I am sending the following JSON to add a custom activity.
{
    "input": [
        {
            "activityDate": "2016-10-17T10:32:41+00:00",
            "activityTypeId": 100005,
            "attributes": [
                {
                    "apiName": "permalink",
                    "name": "Permalink",
                    "value": "https://facebook.com"
                }
            ],
            "leadId": "492",
            "primaryAttributeValue": "Test FB post"
        }
    ]
}

This call is successful and returns the following message:
{
    "requestId": "81d8#157d25cb121",
    "result": [
        {
            "id": 2287,
            "status": "added"
        }
    ],
    "success": true
}

But, when I don't send the apiName in the JSON (according to the documentation it is indeed optional), it works as expected as well.
I am curious to know where and how to use the apiName. What is the use for it and why is it optional? If there is any documentation, kindly point me to that since I couldn't find much information.


text:
Q: Cannot view bios/boot screen on Dell T7500 with Quadro 4000 card I have a Dell T7500 with a Quadro 4000 card.
I have just attached a new Phillips 328E1CA via display port. The new monitor only has display port and HDMI inputs. The monitor specs are here:
https://www.philips.co.uk/c-p/328E1CA_00/curved-lcd-monitor-with-ultra-wide-color
My OS is Ubuntu.
I do not see any of the boot/bios screens. My system has an encrypted hard drive, which requires password upon boot. I do not see that screen either. But if I type in my password and press enter, it takes me into the Ubuntu desktop and I can see things.
How can view the boot/bios screens via displayport?
Edit:
I see Amazon sells DVI to HDMI cables. If I use one of these to connect to the monitor, is it likely to let me see the boot screens?
Edit:
I haven't updated any drivers, but this morning I saw the password screen. I am not sure what is different. Perhaps the order in which I turned the computer/monitor on was different?

A: Go into the BIOS and change the Video > Primary Video to either Auto or to your graphics card.
You'll have to hook up a monitor to the integrated graphics port temporarily in order to access the BIOS.


text:
Q: Select 2 elements with linq I need to select 2 cities in a table with linq:
SOLUTION 1: just one query
            var CityQuery = db.Cities.Where(c => c.CityId == City1Id || c.CityId == City2Id).Take(2)
                foreach (var item in CityQuery)
            {
                if (item.CityId == City1Id)
                {
                    City1Name = item.CityName;
                }
                else
                {
                    City2Name = item.CityName;
                }
            }

or
SOLUTION 2: execute 2 queries
            var City1Query = db.Cities.Where(c => c.CityId == City1Id).FirsOrDefault();
            City1Name = City1Query.CityName;
            var City2Query = db.Cities.Where(c => c.CityId == City2Id).FirsOrDefault();
            City2Name = City2Query.CityName;

Which query is the most efficient ? What is the best practice ?

A: Generally speaking, your Solution 1 should be faster since it makes a single round-trip to the database. However, whether that difference is significant or not depends on your use case.
Here's an alternative solution that only brings back the city names from the database (vs bringing back all columns). At first look, this might look like an inefficient cartesian product but the db engine will most likely optimize this, especially if there exist an index on the CityId column.
var result = from city1 in CityQuery where city1.CityId == City1Id
             from city2 in CityQuery where city2.CityId == City2Id
             select new
             {
                 City1Name = c1.CityName,
                 City2Name = c2.CityName
             };

City1Name = result.City1Name;
City2Name = result.City2Name;


text:
Q: Putty FindwindowEx "Edit" Childwindows I am trying to use API FindwindowEx to input an IP address inside the Putty textbox. I know the textbox window is call "Edit", problem is there are three "Edit" Window in the Putty parent window.
Is there a way to separate the three "Edit" childwindows out so I am only sending text to one?

A: Don't think you can specify anything in FindWindowEx that will differentiate between the different Edit child windows. You could call GetWindowsRect with the handle of each of the child windows and find the one that is positioned in the top left of the form. You could also call GetWindowLength - that would remove the Port edit box easily enough (as it is shorter than the other two on the form).
The IP address edit box always appears first as I iterate through the child windows. Not sure you can guarantee that though.


text:
Q: Android up button isn't working I have a simple application. It consists of Activity A and Activity B.
When I start at Activity A (from the launcher icon) and then navigate to Activity B, and then hit the up button. I arrive at Activity A. Perfect.
Yet when I start activity B from the command line (simulating another app or a notification starting this activity) and I hit the up button, I just get taken to the home screen.
Here is my setup:
Activity A
public class ActivityA extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ActivityA.this, ActivityB.class);
                startActivity(intent);
            }
        });

    }

}

Activity B
public class ActivityB extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_b);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
}

My manifest. Note that the parent activity is defined and my app min api is 16 (so the parent activity declaration is valid for 16 and up).
   <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ActivityA"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".ActivityB"
            android:exported="true"
            android:label="@string/title_activity_b"
            android:parentActivityName=".ActivityA"
            android:theme="@style/AppTheme.NoActionBar" />
    </application>

To start ActivityB from cmd line I use: adb shell am start com.example.demo/com.example.demo.ActivityB
EDIT 1
According to docs here: https://developer.android.com/training/appbar/up-action.html

You do not need to catch the up action in the activity's
  onOptionsItemSelected() method. Instead, that method should call its
  superclass, as shown in Respond to Actions. The superclass method
  responds to the Up selection by navigating to the parent activity, as
  specified in the app manifest.

Edit 2:
Just for kicks, I tried the two code snippets here. One at a time to see if they would do the trick. But they don't. ActivityA doesn't open. ActivityB just closes.
https://developer.android.com/training/implementing-navigation/ancestral.html
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

and
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        Intent upIntent = NavUtils.getParentActivityIntent(this);
        if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
            // This activity is NOT part of this app's task, so create a new task
            // when navigating up, with a synthesized back stack.
            TaskStackBuilder.create(this)
                    // Add all of this activity's parents to the back stack
                    .addNextIntentWithParentStack(upIntent)
                    // Navigate up to the closest parent
                    .startActivities();
        } else {
            // This activity is part of this app's task, so simply
            // navigate up to the logical parent activity.
            NavUtils.navigateUpTo(this, upIntent);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
}

What's happening vs expected?
When I open ActivityB via the cmd line and hit up, I expect to go to ActivityA while ActivityB closes. What actually happens is that ActivityB just closes.

A: That is the default bahavior, the up navigation button works with the Activity Stack, if the ActivityA isn't in the stack, the Android will return to the previous screen , in this case the Home.


text:
Q: Allow download_url for lan addresses I'm hosting a wp site on my own server (at home) and I would like to use wp cli to import media from my own computer.
On my computer, I have a web server and I asks to wp-cli to import media from "http://192.168.0.2/wpTemp/media.txt".
It fails! After investigations, it is due to the ip address which is not recognized as "safe" by download_url() => wp_safe_remote_get().
Is there a way to configure wp to allow only 192.168.0.2 ? and keep the protection for everything else.
(I'll also need to know where to put the modification, I don't want to redo the modification after wp update).
Thank you for your time!
The code of the problem: https://developer.wordpress.org/reference/functions/wp_http_validate_url/ line 566 return false and marks the url as invalid.

A: to allow this IP as safe, use this filter
add_filter("http_request_host_is_external", function ($is, $host, $url) {

    if ("192.168.0.2" === $host) {
        $is = TRUE;
    }

    return $is;

}, 10, 3);


text:
Q: Where i have to place the .cfg.xml and .hbm.xml files with hibernate configurations? In a project with the tree below, where i have to place these files?
src
|_ com
   |_ app
      |_ java
      |  |_ controllers
      |  |_ models
      |_ webapp
         |_ WEB-INF

A: Inside src. Same level as com.


text:
Q: How to recover an user account with a specific email address in Ruby ( User Devise Gem use ) I'm here to ask how to recover an user account that happened to be deleted ( as a mistake ). The user's email address was 'sungpah+100@gmail.com' for instance and want to use this email address again as an account.
I tried to make a new user and insert the same email address but the console output is
User Exists (1.4ms)  SELECT  1 AS one FROM users WHERE users.email = BINARY 'sungpah+100@gmail.com' LIMIT 1
   (1.1ms)  ROLLBACK
Can I make an account with 'sungpah+100@gmail.com' again?
When I tried to search the account with the command : User.find_by(:email => 'sungpah+1@gmail.com', the result is nil currently!
The id was 950 and now if I search with User.find(950), ActiveRecord::RecordNotFound: Couldn't find User with 'id'=950 [WHERE users.deleted_at IS NULL]
is the outcome!
Looking forward to seeing any response!
Best

A: It's difficult to be certain without more information, but from the deleted_at query in your question, you appear to be using a gem such as acts_as_paranoid which lets you hide and restore records without deleting them. So that's good!
Try user = User.unscoped.find(950).
You likely have a default scope applied to your User model provided by this acts_as_paranoid gem which filters out any record where deleted_as is present.  unscoped will remove that scope and let you find all records.
Once you've found the user, you can restore it by deleting the deleted_at field.
user.update_attributes(deleted_at: nil)


text:
Q: Why is addEventListener not working when creating a HTML element with createElement? So in my code im creating a simple div and adding an event listener
const new_card = document.createElement('div');
new_card.className = 'card';
new_card.style.left = e.pageX + "px"
new_card.style.top = e.pageY + "px"
new_card.addEventListener('onclick', handler);

Code for the handler:
const handler = (event) => {
    if ((event.target as HTMLElement).parentElement!.className == 'card') {
        get_selected_card((event.target as HTMLElement));
    }
};

and then the handler call this function:
function get_selected_card(elmnt: HTMLElement | null) {
    console.log(elmnt);
};

but the code isnt working, i got no response in my console


text:
Q: Выбрать строки в лог файле в зависимости от времени #!/bin/bash

dateminusten=$(date -d "10 minutes ago" +"%F %T")

declare -a arr=("2018-04-28 06:24:28,450 Log message 2wecewcewcewcewce" "2018-04-28 06:26:28,440 Log message 3wecewcewcew" "2018-04-28 06:28:28,640 log message 5c ewcwewc" "2018-04-28 06:30:28,220 log message 6" "2018-04-28 06:31:28,650 log message 4" "2018-04-28 06:32:28,634 log message 5" "2018-04-28 06:36:28,650 very long messageewcewcec" "2018-04-28 06:37:28,420 ewcewcewcewcwe wecewcwew" "2018-04-28 06:38:28,120 cwewwecewcewcwecwewecwe")
for i in "${arr[@]}"
do
   echo "$i"
done

Нужно выбрать строки, время в которых меньше в пределах 10 минут от текущего времени. Текущее время для этого примера 2018-04-28 06:40:28
Получаю это время так: dateminusten=$(date -d "10 minutes ago" +"%F %T")
и формируется строка вида 2018-04-28 06:30:28
Как выбрать строки время в которых находится между 2018-04-28 06:30:28 и 2018-04-28 06:40:28 ?
Разбивать строку по пробелам на подстроки, объединять первые две подстроки и потом как-то сравнивать дату. Вот что приходит на ум. Но тогда что делать с тысячными секунды?

A: Даты в квази-iso'шном формате да ещё когда они в начале строки удобны тем, что их можно сравнивать лексикографически без всякой подготовки. Например так:
$ cat file
2018-04-28 06:24:28,450 Log message 2wecewcewcewcewce
2018-04-28 06:26:28,440 Log message 3wecewcewcew
2018-04-28 06:28:28,640 log message 5c ewcwewc
2018-04-28 06:30:28,220 log message 6
2018-04-28 06:31:28,650 log message 4
2018-04-28 06:32:28,634 log message 5
2018-04-28 06:36:28,650 very long messageewcewcec
2018-04-28 06:37:28,420 ewcewcewcewcwe wecewcwew
2018-04-28 06:38:28,120 cwewwecewcewcwecwewecwe
$ datestart="$(date -d "2018-04-28 06:30:28" +"%F %T")"
$ dateend="$(date -d "2018-04-28 06:40:28" +"%F %T")"
$ awk "{if(\"$datestart\"<\$0 && \$0<\"$dateend\") print \$0}" file
2018-04-28 06:30:28,220 log message 6
2018-04-28 06:31:28,650 log message 4
2018-04-28 06:32:28,634 log message 5
2018-04-28 06:36:28,650 very long messageewcewcec
2018-04-28 06:37:28,420 ewcewcewcewcwe wecewcwew
2018-04-28 06:38:28,120 cwewwecewcewcwecwewecwe


text:
Q: Объясните значение Connect by, dual, level Объясните значение Connect by, dual, level в oracle.
Подсознательно понимаю что происходит, но хотелось бы увидеть четкое определение.
A: Например,
Иерархические запросы в Оракл.


text:
Q: Sum of diminishing series with constant addition I am not sure how to derive the formula for this example, although I suspect something from the annuity pension (not sure if that is the correct English word) formulas.
I have a start value of 1000. Each year the amount is reduced by a factor of 0.9. At the end of the year 90 are added to the reduced value. What is a formula to calculate the value at the end of 10 years.
So one way to solve this is to to it step by step:
$s(0) = 1000$
$s(n) = s(n-1)*0.9^n + 90$
Using a spreadsheet I calculated the final value.
$s(10) = 934.87$
How can I derive an analytical formula for this?

A: You have $s(n)=s(0)0.9^n+90\cdot 0.9^{n-1}+90\cdot 0.9^{n-2}+\dots 90$, where each term after the first comes from the decay of each added $90$.  This is a geometric series which we can sum, getting $$s(n)=s(0)0.9^n+90\frac {1-0.9^n}{1-0.9}$$


text:
Q: CruiseControl.NET send mail with fix list on build? I was wondering if it is possible if I could include a Fix List with my deployment build email notification,what I was expecting is I would add the latest changes to a text file stored in a directory and CruiseControl.NET would pick it from there and send along with the email.Anybody has any similar solutions, or how did you do it? Any samples or links?
Thanks in advance.

A: The first question is whether you do continuous integration (CI) builds or just periodical builds? In case it is CI, have you tried writing this fix list into the check-in comment of your version control system? CCNet shows this comment as part of the build report (and email notification).
UPDATE: the other option I see is to write your own CCNet plugin for this. It shouldn't be too hard. As a reference on writing CCNet plugins you can use my own BrekiLabeller plugin.


text:
Q: launch.json configuration for debugging client side javascript without using a web server The launch.json's Chrome configuration by default assumes that I am using a Web server. Its content are as follows:
{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:8080",
            "webRoot": "${workspaceFolder}"
        }
    ]
}

What if I want to debug a client side JavaScript but I am not using a Web server. My pages are simple HTML pages. Can I still use VS Code extension "Debugger for Chrome" to do this? Or something else may be?
Is it possible to use the file:/// protocol inside the url property of the launch.json to enable client side JavaScript debugging in Visual Studio without using a Web server.
I can't find any documentation that addresses this.

A: Use the below Json in launch.json
{
    "version": "0.1.0",
    "configurations": [
        {
            "name": "Launch localhost",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost/mypage.html",
            "webRoot": "${workspaceFolder}/wwwroot"
        },
        {
            "name": "Launch index.html",
            "type": "chrome",
            "request": "launch",
            "file": "${workspaceFolder}/index.html"
        },
    ]
}

You can find more explanation in the below mentioned URL
 VSCODE JS DEBUG


text:
Q: as3 load picture from xml file please can someone help me!? I am loading data from an xml file with FLASH, everything is working fine except for displaying a picture from a link in the xml file. The xml file has whitespaces. I've fixed the problem for text but the picture is still not showing because of the whitespaces in the xml file.
Please can anyone help me?/??`

A: Check out the ignoreWhitespace property. Why would you have whitespaces in an URL anyways??
Adobe help - ignoreWhitespace

Also some code and the xml would help


text:
Q: Pattern for a function that must be called in first, followed by client code, then a function that must be called last? Similar to the Builder pattern where a series of functions or code that must be called in a specific order can be called from one public function.
Is there a pattern for when the client must call a specific initializer function first, followed by zero or more client code calls, followed by a deinitializer function last?
I'd like to make it so the client doesn't have to worry about calling (or forgetting to call) the init and deinit functions and can just worry about their own code.

A: Depending on language used, you can try with NVI idiom or Proxy pattern. There are also some other idioms/patterns tackling with this problem indirectly.

A: My preference in this situation is to have the client call a single function (which we might call executeFn()), with the parameters f, which is a function that the client provides, and fp which is a way for the the client to provide arguments to f() via executeFn(). f() may also be required to accept arguments provided by executeFn(), which have been created in the initialisation step, and to return a value that is used by executeFn() in the de-initialisation step.
In Python, for instance:
def executeFn (f, fp):
    # do the initalisation here
    i = len(fp)
    f(fp,i)
    # do the de-initalisation here

def myFn (p,i):
    print (i)
    print (p)

executeFn(myFn,"message")

... which outputs:
7
message

A: Addition to Simon's answer, you can do delegation instead of hard-coding the operation inside, and depended on language, you can using delegation to be passed.
For example in C# for calling a webservice, which language is able to pass delegation:
public class Invoker{
    public ResultClass Invoke(Func<InvokeResultClass, ServiceClass> action){
        ResultClass result;
        using(ServiceClass svc = new ServiceClass()){ //create the service
            InvokeResultClass invokeResult = action(svc);
            // do something with InvokeResultClass and creating ResultClass
        } // dispose it
        return result;
    }
}

The consumer:
Invoker inv = new Invoker();
ResultClass result = inv.Invoke( svc => svc.CallWebServiceMethod(param1, param2, etc) );

A: You may need the Adapter Pattern where you have the client call methodA() on adapter which implementation is
class Adaptee
{
    methodA()
    {
        // some code
    }
}
class Adapter extends Adaptee
{
    methodA()
    {
        mustBeCalledFirst(); //methodB()
        super.methodA(); //from adaptee
        mustBeCalledLast(); //methodC()
    }
}
class Client
{
    Adapter adapter;
    methodA()
    {
        adapter.methodA();
    }
}

EDIT
If your methodB() and methodC() is in your client you may add a client interface
class Adaptee
{
    methodA()
    {
        // some code
    }
}
class Adapter extends Adaptee
{
    ClientInterface clientInterface;
    public Adapter( ClientInterface clientInterface)
    {
         this.clientInterface = clientInterface ;
    }
    methodA()
    {
        clientInterface.methodB()
        super.methodA(); //from adaptee
        clientInterface.methodC()
    }
}
class Client implements ClientInterface
{
    Adapter adapter;
    methodA()
    {
        adapter.methodA();
    }
    @override
    methodB(){}
    @override
    methodC(){}
}
Interface ClientInterface
{
     methodB();
     methodC();
}


text:
Q: IF Statement Incorrectly Evaluating to True when Using Optional Values in Swift I have set up my view controllers so that they send a notification once their -viewDidLoad method is about to return. For example:
class MyViewController: UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        //Do Stuff
        var notificationCenter = NSNotificationCenter.defaultCenter();
        notificationCenter.postNotificationName("AViewControllerDidLoadNotification", object: self);
    }
}

My AppDelegate class is listening for this notification and implementing the method shown in this picture.
In case the picture isn't loading, the method takes the notification sent by the view controllers as it's only argument and then tests whether the UIViewController's title property has a non-nil value. If the title property is non-nil it logs the title.
However, as you can see in the debugger panel, the title property of the view controller is nil and the if statement is still evaluating to true.
I am admittedly new to optional values. But I have recreated this situation in a swift playground and the if statement evaluates to false. Any ideas?

A: You've gotten yourself into rather an odd situation with your very peculiar use of the expression notification.object?.title, because notification.object is not, of itself, a UIViewController. It is an AnyObject.
Now, an AnyObject has no known properties, so it has no title and your expression, it would seem, should not even compile. But, by a special dispensation coming from certain oddities of Objective-C, you are in fact allowed to ask about an AnyObject's properties anyway. But when you do, the result is itself an Optional, because no such property might exist.
Thus, you are actually testing, not the value of a view controller's title property, but whether this unknown object has a title property in the first place; and if in fact it does have a title property at all, the value of that title property is double-wrapped inside that Optional.
To see this clearly, just test this (silly) code:
let n = NSNotification(name: "Howdy", object: "Hi")
let t = n.object?.title

Look at what type t is. It is not a String?; it is a String??. That's your double-wrapped Optional. This means that it would be an Optional-wrapping-a-String in case this object turns out to have a title property, but just in case, that value has itself been wrapped in an Optional.
Thus, your test doesn't do what you want it to do. To do what you want to do, just speak much more plainly and simply. You need to cast the object to a UIViewController first, and then examine its title. Like this:
func aViewControllerDidLoad(notification:NSNotification) {
    if let vc = notification.object as? UIViewController {
        if vc.title != nil {
            // ...
        }
    }
}


text:
Q: Resample only within the same day I have a dataframe containing an asset price (OHLC asset data) such that its index is a datetime. The data shoud be sample in minutes but my dataset have some missing minutes.

To fill the missing data, I just used the function
df.resample("1Min").asfreq()

It fills correctly the minutes within one day, but since my dataframe contains data for different days, it usually fills the minutes until midnight of each day. I would like that, if one specific day contains data from 13:05pm to 20:50pm, it fills minute only between those times, i.e., do not exceed those bounds.
I looked at the documentation for the resample function and couldn't find how it can be done. I appreciate your help!

A: I believe you need DataFrame.groupby by days and chain DataFrameGroupBy.resample with Resampler.first:
df = df.groupby(df.index.date).resample("1Min").first()


text:
Q: When UTF-8 encoded text is sent to database, special characters get corrupted I have a form that reads some data. And a php file that sends this data to the database. All of the html files and php file are UTF-8. When the form reads the data, I have a check with echo right before the INSERT statement. The echo displays the words correctly. But when it is sent to database, it arrives with broken characters.
For example:
I send the word "Būve". echo prints it exactly like that. But in the database I get "BÅ«ve".
I have both of these right after connection as well.
mysql_query("SET NAMES UTF8");
mysql_query("SET CHARACTER SET utf8");

PHP code:
echo $_POST[pasutitajs];

$sql = "INSERT into ligumitable (nrpk, ligums, pasutitajs, parkstisanasdatums, summa,)  VALUES ('$_POST[nrpk]', '$_POST[ligums]', '$_POST[pasutitajs]', '$_POST[parkstisanasdatums]', '$_POST[summa]')";

Tables in the database are utf8 as well, if I unput the data through phpmyadmin, using these characters, everything is fine. It's the INSERT that breaks it. What could be wrong?
EDIT:
This is funny. Thing is, i am not the only one working on the code. And now that I checked it, my buddy used "$conn->query($sql)" and not "mysql_query($sql)". No idea why. I changed it to a regular mysql_query and it works. Thanks everyone, sorry for bothering you with such a simple thing.

A: You can maybe fix it like this:

$sql = utf8_decode("INSERT into ligumitable (nrpk, ligums, pasutitajs, parkstisanasdatums, summa,)  VALUES ('$_POST[nrpk]', '$_POST[ligums]', '$_POST[pasutitajs]', '$_POST[parkstisanasdatums]', '$_POST[summa]')");

A: before inserting data into database write this two line:
  $str="set names UTF8";
  mysql_query($con,$str);

in $con write your connection codes.


text:
Q: Yii2: GridView's column is too wide I have index.php made by the Gii tool that created a CRUD. Also I use AdminLTE template.
It has the GridView that should show two columns: "Phrase" and "Author" but the column "Phrase" has some rows with long text (around 350 characters) so just a part of this column is shown. And the "Author" column is not shown at all.
There is no horizontal scroll bar (it should help me):

Or maybe the problem is the string data type:
public function rules()
{
    return [
        [['phrase'], 'required'],
        [['phrase'], 'string'],
        [['author'], 'string', 'max' => 50],
    ];
}

This is my index.php view:

    <?php Pjax::begin(); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'phrase',
            'author',
        ],
    ]); ?>
    <?php Pjax::end(); ?>

A: You can also use contentOptions :
[
   'attribute' => 'phrase',
   'contentOptions' => [
       'style' => [
           'max-width' => '600px',
           'white-space' => 'normal',
       ],
   ],
],

A: I added the table-responsive class to

    <?php Pjax::begin(); ?>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'frase',
            'autor',
            [
                'class' => 'yii\grid\ActionColumn',
                'template' => '{update} {delete}'
            ],
        ],
    ]); ?>
    <?php Pjax::end(); ?>

A: Try This:
[
    'attribute'=>'phrase',
    'value'=>function($data){
        return strlen($data->phrase) > 100 ? Html::encode(substr($data->phrase, 0, 100)) . ". . ." : $data->phrase;
    }
]

It will display the first 100 characters from  the string, if the string size is greater than 100.
Set The Value according to your desired width.


text:
Q: Give the names of employees who sell the products of more than 10 suppliers I am finding it difficult to write the query for the above question I have written the following query but it is returning all the rows
SELECT e.EmployeeID
FROM employees e
JOIN orders o ON e.EmployeeID = o.EmployeeID
JOIN order_details od ON o.OrderID = od.OrderID
JOIN Products p ON od.ProductID = p.ProductID
GROUP BY e.EmployeeID
HAVING COUNT(p.SupplierID) > 10

A: Your filtering condition is:
HAVING COUNT(p.SupplierID) > 10

COUNT() counts the number of non-NULL values.  Presumably, all products have a supplier and you are using inner joins.  So, all matching rows get counted.  It is equivalent to:
HAVING COUNT(*) > 10

And this counts the number of order lines for a given employee.
You want to count distinct suppliers, not order lines.  The simplest method is to use COUNT(DISTINCT):
HAVING COUNT(DISTINCT p.SupplierID) > 10

Because you are learning SQL, I would advise you to understand this version as well:
SELECT e.EmployeeID
FROM (SELECT e.EmployeeID, p.SupplierID, COUNT(*) as num_ordelines
      FROM employees e JOIN
           orders o
           ON e.EmployeeID = o.EmployeeID JOIN
           order_details od
           ON o.OrderID = od.OrderID JOIN
           Products p
           ON od.ProductID = p.ProductID
      GROUP BY e.EmployeeID, p.SupplierId
     ) es
GROUP BY EmployeeID
HAVING COUNT(SupplierID) > 10

This returns the same result set (assuming SupplierId is never NULL).  The subquery has one row per employee/supplier.  The outer query then counts these rows.


text:
Q: Groovy script for Jenkins: execute HTTP request without 3rd party libraries I need to create a Groovy post build script in Jenkins and I need to make a request without using any 3rd party libraries as those can't be referenced from Jenkins.
I tried something like this:
def connection = new URL( "https://query.yahooapis.com/v1/public/yql?q=" +
    URLEncoder.encode(
            "select wind from weather.forecast where woeid in " + "(select woeid from geo.places(1) where text='chicago, il')",
            'UTF-8' ) )
    .openConnection() as HttpURLConnection

// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )

// get the response code - automatically sends the request
println connection.responseCode + ": " + connection.inputStream.text

but I also need to pass a JSON in the POST request and I'm not sure how I can do that. Any suggestion appreciated.

A: Executing POST request is pretty similar to a GET one, for example:
import groovy.json.JsonSlurper

// POST example
try {
    def body = '{"id": 120}'
    def http = new URL("http://localhost:8080/your/target/url").openConnection() as HttpURLConnection
    http.setRequestMethod('POST')
    http.setDoOutput(true)
    http.setRequestProperty("Accept", 'application/json')
    http.setRequestProperty("Content-Type", 'application/json')

    http.outputStream.write(body.getBytes("UTF-8"))
    http.connect()

    def response = [:]

    if (http.responseCode == 200) {
        response = new JsonSlurper().parseText(http.inputStream.getText('UTF-8'))
    } else {
        response = new JsonSlurper().parseText(http.errorStream.getText('UTF-8'))
    }

    println "response: ${response}"

} catch (Exception e) {
    // handle exception, e.g. Host unreachable, timeout etc.
}

There are two main differences comparing to GET request example:

*

*You have to set HTTP method to POST
http.setRequestMethod('POST')

*You write your POST body to outputStream:
http.outputStream.write(body.getBytes("UTF-8"))

where body might be a JSON represented as string:
def body = '{"id": 120}'

Eventually it's good practice to check what HTTP status code returned: in case of e.g. HTTP 200 OK you will get your response from inputStream while in case of any error like 404, 500 etc. you will get your error response body from errorStream.


text:
Q: How to create a 'Close Tab' button in Google Sheets I have created an app using Google Sheets. I have created a hyperlink that opens a different Sheets file at the appropriate row to edit the relevant data, but now I want to create a clickable button that then closes that newly opened browser tab once the edit has been made, for it to return to the original sheet tab and continue with life.
Can someone provide me with easy to follow instructions on how to achieve this?  (I am aware of how to assign a script to a button, I just need help on the actual script required).

A: To close a generic page served from a web-app you can use the close() method of the Client-side API from a button with a code similar to this one:
<input type="button" value="Close" onclick="google.script.host.close()" />

Please, write back to me if this approach doesn't work in your scenario.


text:
Q: How to sort a Collection of Objects? I have a class Gym which contains the following fields:
private int id;

private String name;

private String street;

private String housenumber;

private String zipcode;

private String lat;

private String lng;

private String city;

All of the data is in a database. A user can filter gyms by some creteria: sports and distance. I have a function which gets all of the gyms out of the database and adds them to a layout.
The lat and lng fields also are in the database.
When a user requests all the gyms the distance between the user and the position is calculated using the following code:
double distance = Math.round(gpsHelper.calculateDistance(location.getLatitude(), Double.valueOf(gym.getLat()),
                location.getLongitude(), Double.valueOf(gym.getLng()), 0.0, 0.0));
 DecimalFormat df = new DecimalFormat("#.##");
String formattedDistance = "Afstand: " + String.valueOf(df.format(distance)) + " km";

What I would like to do is the following: I would like to sort all the gyms by their distance to the user. So sort them by df.format(distance).
Could anyone give me a push into the right direction? I think I've added al the relevant code.

A: Collections.sort
Collections.sort(List<T> list) sorts the specified list into ascending order, according to the natural ordering of its elements.
For example:
List<String> fruits = new ArrayList<String>();

fruits.add("Pineapple");
fruits.add("Apple");
fruits.add("Orange");
fruits.add("Banana");

Collections.sort(fruits);

int i=0;
for(String temp: fruits){
    System.out.println("fruits " + ++i + " : " + temp);
}

Will give as output:
fruits 1 : Apple
fruits 2 : Banana
fruits 3 : Orange
fruits 4 : Pineapple

See other examples at: Java object sorting example (Comparable and Comparator).
Comparator
Comparator is a comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.
Collections.sort(people, new Comparator<Person>() {

    @Override
    public int compare(Person o1, Person o2) {
        return o1.getLastName().compareTo(o2.getLastName());
    }
});

Lambda Expressions
Java 8 introduced Lambda Expressions and the Comparator's equivalent is:
Comparator<Person> people =
    (Person o1, Person o2)->o1.getLastName().compareTo(o2.getLastName());


text:
Q: Customizing my location button in airbnb/react-native-maps I have used airbnb/react-native-maps for designing a tracking based apps. I have designed a custom search box. But the problem is, the search box overlaps my location button. Is there any way to customize my location button and changing its alignment position? I have attached a photo for more specification.
Here is the sample code which I have used
 <MapView
    provider={PROVIDER_GOOGLE}
    style={styles.map}
    region={{
        latitude: this.props.initialPosition.latitude,
        longitude: this.props.initialPosition.longitude,
        latitudeDelta: Latitude_Delta,
        longitudeDelta: Longitude_Delta
    }}
    zoomEnabled={true}
    minZoomLevel={5}
    maxZoomLevel={20}
    showsMyLocationButton={true}
    showsUserLocation={true}
    ... ... ...
   >
   {... ... ... ...}
 </MapView>

A: A quick solution would be to add a padding to the top of your map with the height of your custom-search-box to push the myLocationButton below it.
I went through its Docs but could't find any way to customize its position or alignment.
There is a similar issue in the github regarding this raised more than 6 months ago which suggests the similar solution:

https://github.com/airbnb/react-native-maps/issues/1094


text:
Q: Exporting Y equation for Logistic Model with Categorical Variables I have built a logistic model in R.
As the system in which the data set is present – doesn't support integration of any other application, I have to export the Equation of this model and use that Y equation to predict the outcome.
The problem is that my data set has many categorical variables and when the model is built, R will provide the coefficients only for n-1 factors. (for example if the variable has 4 factors – Q1, Q2, Q3 & Q4, in the logistic model the coefficients will be available only for 3 factors Q2, Q3 & Q4). In this case, how can I deal will the missing Factors coefficients for the variable.


text:
Q: Is TEmbeddedWB worth investigating? I try to use Google map API from a Delphi Application. I got a good start from my other question Use Googlemap from my Delphi application ?.
Now I found TEmbeddedWB and I wonder if there are any advantages over the builtin TWebBrowser component. Both are interfaces to Internet Explorers DLL-files and seems to do similar things? I don't want to use more custom components than necessary.

A: The interface is much better than the twebbrowser one. there are also more events you can use. maybe important for you, you can modify the browsers security. this is necessary if javascript is disabled on the client machine. the twebbrowser is bound to the global ie settings.
i think using the tembeddedwb is an advantage.

A: I used TEmbeddedWB in one of my projects and found its impelentation worth using as it provides access to several events and methods which while not hard to implement yourself, are already present.

A: TEmbeddedWB has good concept behind it, but it is developed in a horrible manner. Everything works at 50%, there are plenty of bugs, it is not tested nor documented.
So good luck!


text:
Q: UITableView with Two Prototype Cells UPDATE- Thanks to Farhad for answering my initial post. At the bottom of this post is a new issue i've encountered regarding automatic dimensioning for dynamic cell height
I've tried searching for other posts but to no avail.
As the title suggests I want to have my table view show two cells with the second cell being custom.
The first cell will have 4 rows - O.D, Weight, I.D, Grade.
The second cell, the custom cell, will have 8 labels displaying the results from the inputs from the first cell.
I have a reuse identifier for both cells. The first cell i've called "capacitiesCell" and my second cell I've called "cell2"
For my second cell, I have created a new tableViewCell file named "CapacitiesTableViewCell" that has 4 of the 8 labels as outlets.
SIDE NOTE: For the name of the cells I've just put a generic "Section #, Row #" for now but will change the line of code to cell.textlabel?.text = capacityID when I've figured the issue out...assuming that's the correct way to go about this.
Here is my code thus far:
class CapacitiesTableViewController: UITableViewController {

let capacityParameters = ["O.D", "Weight", "I.D", "Grade"]

override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 2
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if section == 0 {
        return capacityParameters.count
    } else {
        return 1
    }

}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("capacitiesCell", forIndexPath: indexPath)

    //let capacityID = capacityParameters[indexPath.row]
    cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

    return cell

    let dimensionAndStrengthCell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath)
    // my code goes here
    return dimensionAndStrengthCell
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    if section == 0 {
        return "Casing Specification"
    } else {
        return "Dimension & Strength"
    }
}

This is my storyboard:

However when I run the app I get this:

CHANGING CELL HEIGHT FOR CELL2
So in my viewDidLoad I have the following:
override func viewDidLoad() {
    super.viewDidLoad()

    // Uncomment the following line to preserve selection between presentations
    // self.clearsSelectionOnViewWillAppear = false

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem()

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 200.0
}

I'm trying to have my view look like the screenshot below but the "Strength and Dimension" section cell height is stuck on the default height.

the new code I've added from Farhad's response is :
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    // init return type of cell
    var returnCell: UITableViewCell!

    if indexPath.section == 0 { // you can also check for section with section.index
        returnCell = tableView.dequeueReusableCellWithIdentifier("capacitiesCell", forIndexPath: indexPath)

        //let capacityID = capacityParameters[indexPath.row]
        returnCell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

    return returnCell

    } else {

        returnCell = tableView.dequeueReusableCellWithIdentifier("cell2", forIndexPath: indexPath)

        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedRowHeight = 200.0

        return returnCell

    }
}

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    if section == 0 {
        return "Casing Specification"
    } else {
        return "Dimension & Strength"
    }
}

A: In your cellForRowAtIndexPath you check at what position you need to enter a new row or section with if/else statement.
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        //Init the Return of Cell Type
        var returnCell: UITableViewCell!

        if index.row == 0 { // You can also check for section index.section
         returnCell = tableView.dequeueReusableCellWithIdentifier("capacitiesCell", forIndexPath: indexPath)

        //let capacityID = capacityParameters[indexPath.row]
        cell.textLabel?.text = "Section \(indexPath.section) Row \(indexPath.row)"

        return returnCell

        } else {

        returnCell = //Other cell at other rows or section
        return returnCell

        }

    }


text:
Q: TypeError: unbound method getInterfaceName() must be called with Interface instance as first argument (got nothing instead) class Unit:
    def init(self, _chassisId, _unitNo, _interface):
        self.chassisId = _chassisId
        self.unitNo = _unitNo
        self.interface = _interface
def getInterface(self):
    return self.interface

@staticmethod
def parse(elem):
    unitList = elem.find(UNIT+LIST)
    chassisList = []
    for unit in unitList.findall(UNIT):
        try:
            unitNumber = unit.find(UNIT_NUMBER).text
            interface = unit.find(INTERFACE)
            interface = ""
            chassisIdElem = unit.find(CHASSIS_ID)
            chassisId = ""
            if chassisIdElem is not None:
                chassisId = unit.find(CHASSIS_ID).text
            elif unit.find(BURNED_IN_MAC) is not None:
                chassisId = unit.find(BURNED_IN_MAC).text
            chassisId = chassisId.replace(".", "").replace(":", "").upper()
            chassis = Unit(chassisId, interface, unitNumber)
            chassisList.append(chassis)
        except Exception as e:
            print "Unit details not found", e
        return chassisList

def getChassisId(self):
    return self.chassisId

def __str__(self):
    str = "\n"
    str += "\nUnit Details:- "
    len = str.__len__();
    str += "\n"
    for i in range(1,len-1):
        str += "-"
    str += "\nUnit: " + self.unitNo
    str += "\nChassis Id: " + self.chassisId
    str += "\nInterfaces: " + self.interfaces
    return str

def __add__(self, other):
    return str(self) + other

def __radd__(self, other):
    return other + str(self)

class Interface:
    def init(self, _linkState, _interfaceName):
        self.linkState = _linkState
        self.interfaceName = _interfaceName
@staticmethod
def parse(elem):
    prefix = Device.getPrefix(elem.tag)
    interfaceList = elem.find(INTERFACE + LIST)
    interfaceNameTag = eval(prefix + "_INTERFACE_NAME")
    linkStateTag = eval(prefix + "_LINK_STATE")
    interfaces = []
    for interface in interfaceList.findall(INTERFACE):
        try:
            interfaceName = interface.find(interfaceNameTag).text
            linkStateElem = interface.find(LINK_STATE)
            linkState = ""
            if linkStateElem is not None:
                linkState = interface.find(LINK_STATE).text
            elif interface.find(LINE_PROTOCOL) is not None:
                linkState = interface.find(LINE_PROTOCOL).text
            interface = Interface(linkState, Name)
            interfaces.append(interface)
        except Exception as e:
            print "Interface details not found", e
            return interfaces

def getLinkState(self):
    return self.linkState

def getInterfaceName(self):
    return self.interfaceName

def __str__(self):
    str = "\n"
    str += "\nInterface  Details:- "
    len = str.__len__();
    str += "\n"
    for i in range(1,len-1):
        str += "-"
    str += "\nLink State: " + self.linkState
    str += "\nInterface Name: " + self.interfaceName
    return str

def __add__(self, other):
    return str(self) + other

def __radd__(self, other):
    return other + str(self)

A: You haven't shown us the call to getInterfaceName() that causes the error, which makes it harder to help you.
However, I'll guess that the call looks something like this:
something = Interface.getInterfaceName()

You can't do it that way.  You must create an instance of Interface, and then call its .getInterfaceName() method:
myInterface = Interface()
something = myInterface.getInterfaceName()


text:
Q: Construct a grading from a left group scheme action (from Vakil's FOAG) In Exercise 6.6.S(b) in Vakil's FOAG, it is stated that a $\mathbb{Z}$-valued grading on a ring $A$ is equivalent to a left $\mathbb{G}_m$-action on $\operatorname{Spec} A$. I think I see how one direction goes: if $A$ has a $\mathbb{Z}$-grading, then there is a canonical ring morphism $A \to A[x,x^{-1}]$ sending $a \in A$ to the polynomial $\sum_{n \in \mathbb{Z}} a_n x^n$, where each $a_n$ is homogeneous obtaining by decomposing $a$ into the sum of homogeneous elements. Using the fact that $A[x,x^{-1}] \cong \mathbb{Z}[x,x^{-1}] \otimes_\mathbb{Z} A$, we obtain a scheme morphism $\mathbb{G}_m \times \operatorname{Spec} A \to \operatorname{Spec} A$. What I am struggling in is the opposite direction.
Now suppose we have a left $\mathbb{G}_m$-action map $a: \mathbb{G}_m \times \operatorname{Spec} A \to \operatorname{Spec} A$. The equivalence of categories $\mathbf{CRing}^\mathrm{op} \simeq \mathbf{AffSch}$ turns commutative diagrams of a (left) group object action (stating the associtaivity an identity for the action) into the commutative diagrams in $\mathbf{CRing}$:

And I am not sure how to get a $\mathbb{Z}$-grading on $A$ from these two diagrams. The exercise also says there are two ways to define the grading, but at this stage I still don't see where the "splitting point" comes from.
I would like to see at least one of the ways to define the grading (of course both is better). And here is a further natural question. Suppose $A$ is a graded ring. Then the first paragraph gives a construction for a (possible) left $\mathbb{G}_m$-action of $\operatorname{Spec} A$. Then if we construct a grading on $A$ via the action, do we get original grading back (using either way? or only one of the ways? or not at all?) Just another question out of curiousity: how is this (or these) interpretation(s) of grading is (are) used in the literature?
Thanks for helping.


text:
Q: $k$-isogenies and $k$-subgroups of abelian varieties Let $k$ be a field of char0, with algebraic closure $\bar{k}$. Let $A$ be an abelian variety over $k$ of positive dimension and let $d\geq 1$ be an integer.
Let $S(A,k,d)$ be the set of abelian varieties $B$ over $k$ such that there exists a $k$-isogeny $A\to B$ of degree at most $d$.
Consider: (a) If $B\in S(A,k,d)$ then there exists a $k$-isogeny $\varphi_B:A\to B$ such that $\ker(\varphi_B)(\bar{k})$ is a subgroup of $A(\bar{k})$, defined over $k$, of order at most $d$.
(b) Furthermore, if $B,B'\in S(A,k,d)$ with $\ker(\varphi_B)(\bar{k})=\ker(\varphi_{B'})(\bar{k})$ as subgroups of $A(\bar{k})$ then $B$ is $k$-isomorphic to $B'$.
Note (a) holds always, and one can prove that (b) holds for $k=\bar{k}$.

*

*Does (b) hold for all $k$ as above?

*Moreover, can one use (a) and (b) to describe the set $S(A,k,d)$, up to $k$-isomorphisms, in terms of subgroups of $A(\bar{k})$, defined over $k$, of order at most $d$?


text:
Q: How do you test the 'Patch' action in Web API 2 controllers? I have a basic test case that puts together a Delta object to pass to my controller's 'PATCH' action which I am able to do successfully. My test code is as follows
[TestMethod]
    public async Task Patch_Product()
    {
        // Act
        var delta = new Delta<Product>(typeof(Product));
        delta.TrySetPropertyValue("Name", "PatchedProduct");
        delta.TrySetPropertyValue("Comment", "A test Product that has been patched");

        var result = await productController.Patch(1, delta);

        // Assert
        Assert.IsNotNull(result);
    }

The moment the code hits the first line in the Patch action which is as follows
Validate(patch.GetEntity());

It fails with the following exception: System.InvalidOperationException: ApiController.Configuration must not be null.
I verified that the ApiController.Configuration is in fact null for all of my other tests as well for GET, POST, DELETE etc. However none of these controller action call the 'Validate()' method which is where this exception is thrown. Has anyone encountered this before? Is there a way to get a test against PATCH  work by potentially mocking the context?
I tried passing in a blank configuration as well in my test as follows:
productController.Configuration = new HttpConfiguration();

But this does not seem to work either. I get this exception:
System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.

A: The following worked for me in an MVC5 WebApi2 project:
//----- Test the patch
XXXController controller = new XXXController();
HttpConfiguration configuration = new HttpConfiguration();
HttpRequestMessage request = new HttpRequestMessage();
controller.Request = request;
controller.Request.Properties["MS_HttpConfiguration"] = configuration;

Delta<Shipment> patch = new Delta<XXEntity>();
patch.TrySetPropertyValue("Id", xx.Id);
patch.TrySetPropertyValue("Notes", "Test Comment");

controller.Patch(xx.Id, patch);

This is based on information from prearrangedchaos in  https://aspnetwebstack.codeplex.com/discussions/358709 (which suggests that this is an MVC4 solution and that a better WebApi2 solution might exist).
In looking for my solution I also found a related question that might be useful if you have problems with Url (I didn't): Unit Test with route data not working on ASP.NET MVC 5 Web API


text:
Q: преобразование строки в список Имею данные на входе типа строки :
2020.12.03 04:45:53.399: Ask = 13277.5, Bid = 13275.0, Volume = 1, Last = 13275.0, Flag = 88, Volume Real = 1.0, Type = Sell, Spread = 25

2020.12.03 04:45:54.676: Ask = 13277.5, Bid = 13274.5, Volume = 1, Last = 13277.5, Flag = 56, Volume Real = 1.0, Type = Buy, Spread = 30

2020.12.03 04:45:55.922: Ask = 13277.0, Bid = 13274.5, Volume = 1, Last = 13277.0, Flag = 56, Volume Real = 1.0, Type = Buy, Spread = 25

2020.12.03 04:45:58.570: Ask = 13277.5, Bid = 13277.0, Volume = 1, Last = 13277.0, Flag = 88, Volume Real = 1.0, Type = Sell, Spread = 5

2020.12.03 04:45:59.73: Ask = 13277.5, Bid = 13277.0, Volume = 1, Last = 13277.5, Flag = 56, Volume Real = 1.0, Type = Buy, Spread = 5

2020.12.03 04:45:59.408: Ask = 13279.5, Bid = 13277.5, Volume = 1, Last = 13278.0, Flag = 120, Volume Real = 1.0, Type = N/A, Spread = 20

2020.12.03 04:46:00.840: Ask = 13279.0, Bid = 13277.5, Volume = 1, Last = 13277.5, Flag = 88, Volume Real = 1.0, Type = Sell, Spread = 15

Как привести входящие строки в список где 2020.12.03 04:45:59.408: это дата, а все остальное
Ask = 13279.5, Bid = 13277.5, Volume = 1, Last = 13278.0, Flag = 120, Volume Real = 1.0, Type = N/A, Spread = 20

расходится по значениям где до = название и после = содержание.
Также имеется код(спасибо сообществу)
text = "2020.12.02 10:47:28.819: Ask = 13332.0, Bid = 13331.5, Volume = 2, Last = 13331.5, Flag = 88, Volume Real = 2.0, Type = Sell, Spread = 5"

res = dict()

pos = text.rfind(':')
res['time'] = text[:pos]

for data in text[pos + 1:].split(","):
    obj = data.split("=")
    res[obj[0]] = obj[1]

print(res)

однако у res[obj[0]] = obj[1] выходит ошибка

A: Вы можете использовать регулярные выражения.
import re

lst = [
    '2020.12.03 04:45:53.399: Ask = 13277.5, Bid = 13275.0, Volume = 1, Last = 13275.0, Flag = 88, Volume Real = 1.0, Type = Sell, Spread = 25',
    '2020.12.03 04:45:54.676: Ask = 13277.5, Bid = 13274.5, Volume = 1, Last = 13277.5, Flag = 56, Volume Real = 1.0, Type = Buy, Spread = 30',
    '2020.12.03 04:45:55.922: Ask = 13277.0, Bid = 13274.5, Volume = 1, Last = 13277.0, Flag = 56, Volume Real = 1.0, Type = Buy, Spread = 25',
    '2020.12.03 04:45:58.570: Ask = 13277.5, Bid = 13277.0, Volume = 1, Last = 13277.0, Flag = 88, Volume Real = 1.0, Type = Sell, Spread = 5',
    '2020.12.03 04:45:59.73: Ask = 13277.5, Bid = 13277.0, Volume = 1, Last = 13277.5, Flag = 56, Volume Real = 1.0, Type = Buy, Spread = 5',
    '2020.12.03 04:45:59.408: Ask = 13279.5, Bid = 13277.5, Volume = 1, Last = 13278.0, Flag = 120, Volume Real = 1.0, Type = N/A, Spread = 20',
    '2020.12.03 04:46:00.840: Ask = 13279.0, Bid = 13277.5, Volume = 1, Last = 13277.5, Flag = 88, Volume Real = 1.0, Type = Sell, Spread = 15'
]

rex_time = re.compile(r'\d{4}\.\d{2}\.\d{2} \d{2}:\d{2}:\d{2}\.?\d*')
rex_value = re.compile(r'\b(\w+)\b = (\d+.?\d*)')

for item in lst:
    res = dict()
    res['time'] = rex_time.search(item).group(0)
    for k, v in rex_value.findall(item):
        res[k] = v

    print(res)

Результат:
{'time': '2020.12.03 04:45:53.399', 'Ask': '13277.5', 'Bid': '13275.0', 'Volume': '1,', 'Last': '13275.0', 'Flag': '88,', 'Real': '1.0', 'Spread': '25'}
{'time': '2020.12.03 04:45:54.676', 'Ask': '13277.5', 'Bid': '13274.5', 'Volume': '1,', 'Last': '13277.5', 'Flag': '56,', 'Real': '1.0', 'Spread': '30'}
{'time': '2020.12.03 04:45:55.922', 'Ask': '13277.0', 'Bid': '13274.5', 'Volume': '1,', 'Last': '13277.0', 'Flag': '56,', 'Real': '1.0', 'Spread': '25'}
{'time': '2020.12.03 04:45:58.570', 'Ask': '13277.5', 'Bid': '13277.0', 'Volume': '1,', 'Last': '13277.0', 'Flag': '88,', 'Real': '1.0', 'Spread': '5'}
{'time': '2020.12.03 04:45:59.73', 'Ask': '13277.5', 'Bid': '13277.0', 'Volume': '1,', 'Last': '13277.5', 'Flag': '56,', 'Real': '1.0', 'Spread': '5'}
{'time': '2020.12.03 04:45:59.408', 'Ask': '13279.5', 'Bid': '13277.5', 'Volume': '1,', 'Last': '13278.0', 'Flag': '120,', 'Real': '1.0', 'Spread': '20'}
{'time': '2020.12.03 04:46:00.840', 'Ask': '13279.0', 'Bid': '13277.5', 'Volume': '1,', 'Last': '13277.5', 'Flag': '88,', 'Real': '1.0', 'Spread': '15'}

A: Можно сделать без регулярок, чтобы получить словарь типа {время:[значения]}:
text = "2020.12.02 10:47:28.819: Ask = 13332.0, Bid = 13331.5, Volume = 2, Last = 13331.5, Flag = 88, Volume Real = 2.0, Type = Sell, Spread = 5"

res = {}

def parse(a: str) -> dict:
    key, vals = a.rsplit(":", 1)
    val = [x.strip() for x in vals.split(",")]
    res.update({key:val})

parse(text)

тогда res будет:
{'2020.12.02 10:47:28.819': ['Ask = 13332.0', 'Bid = 13331.5', 'Volume = 2', 'Last = 13331.5', 'Flag = 88', 'Volume Real = 2.0', 'Type = Sell', 'Spread = 5']}


text:
Q: Ping a user defined IP-Range with batch I'm working on a school project and I wanted to create a batch file that pings a user-defined IP-range and writes the successful pings to a txt file.
Now I'm stuck at the FOR loop:
@echo off
SET /p IPRange=Bitte IP-Range eingeben(xxx.xxx.xxx) :
SET /p AnfangsIP=Bitte AnfangsIP des Bereiches eingeben :
SET /p EndIP=Bitte EndIP des Bereiches eingeben :

FOR /L %IP% (%AnfangsIP%,1,%EndIP%) DO (
    ping -n 1 %IP-Range%.%IP% | find "TTL=" >nul
    if errorlevel 1 (
        echo %IP-Range%.%IP% not reachable
    ) else (
        echo %IP-Range%.%IP% reachable
    )
)

pause>nul

The batch file is executed with these parameters: IP range, start IP-address, end IP-address. My goal is to make a for loop that increments the variable %IP% every loop. From the start IP-address to the end IP-address.
I searched in the forum but there are just single pings not for a whole range of IPs.

A: Try this:
@echo off

SET /p IPRange=Bitte IP-Range eingeben(xxx.xxx.xxx) :
SET /p AnfangsIP=Bitte AnfangsIP des Bereiches eingeben :
SET /p EndIP=Bitte EndIP des Bereiches eingeben :

FOR /L %%I IN (%AnfangsIP%,1,%EndIP%) DO (
    ping -n 1 %IPRange%.%%I | find "TTL=" >nul
    if errorlevel 1 (
        echo %IPRange%.%%I not reachable
    ) else (
        echo %IPRange%.%%I reachable
    )
)

pause>nul

EDIT: Output example added
C:\> test.bat
Bitte IP-Range eingeben(xxx.xxx.xxx) :127.0.0
Bitte AnfangsIP des Bereiches eingeben :0
Bitte EndIP des Bereiches eingeben :7
127.0.0.0 not reachable
127.0.0.1 reachable
127.0.0.2 reachable
127.0.0.3 reachable
127.0.0.4 reachable
127.0.0.5 reachable
127.0.0.6 reachable
127.0.0.7 reachable

A: He Guys
Thanks a lot for the answers. Finally the script of Aacini works. In time i made a script without any for loop that isn't that beautiful...
Here's the Code:
@ECHO off
COLOR F0

:START
BREAK>PINGLOG.txt

CLS
SET /P range=Bitte IP-Range eingeben(xxx.xxx.xxx):
CLS
SET /P sIP=Bitte Start-IP eingeben(xxx):
CLS
SET /P eIP=Bitte End-IP eingeben(xxx):
CLS

SET /P JN1=START PING FROM %range%.%sIP% - %range%.%eIP%?(Y/N):

CLS
SET /A counter=%sIP%
SET /A endIP=%eIP%
SET /A endIP+=1
CLS

IF /I %JN1%==Y (
    GOTO PINGRANGE
) ELSE (
    GOTO ENDE2
)

:PINGRANGE
COLOR 7C
PING -n 1 %range%.%counter% | find "TTL=" >nul
IF NOT ERRORLEVEL 1 (
    ECHO ------------------------------------------------- >>PINGLOG.txt
    ECHO %range%.%counter% is reachable! >>PINGLOG.txt
    ECHO %range%.%counter% is reachable!
) ELSE (
    ECHO %range%.%counter% is not reachable!
)

SET /A counter+=1
GOTO CHECK
)

:CHECK
IF %counter%==%endIP% (
    GOTO ENDE1
) ELSE (
    GOTO PINGRANGE
)

:ENDE1
COLOR F0
ECHO -------------------------------------------------
SET /P JN2= FINISH! WOULD YOU SEE THE LOGFILE?(Y/N):
IF /I %JN2%==Y (
    START NOTEPAD "PINGLOG.txt"
) ELSE (
    EXIT cmd.exe
)

:ENDE2
COLOR F0
ECHO -------------------------------------------------
SET /P JN3= NEW IP-RANGE PING?(Y/N):
IF /I %JN3%==Y (
    GOTO START
) ELSE (
    EXIT cmd.exe
)

I now that this is not very beautiful :)
Have A Nice Day
Lukas


text:
Q: why javafx mediaplayer status sometimes returns unknown? First i am sorry for my poor english...
i made Media Player Application with Javafx.
this player can get mulit file media. and play files out of all limits.
it work well. but sometimes not work..
it is not media error. it is mediaplayer error.
error message is 'mediaPlayer Unknown, media Invalid..' why.??
i played same video file(1920 * 1080), sometimes work and sometimes not work..
and javafx is depend on OS ??
player works perfectly on windown7 computer
but player have this error on windown10 computer...
please give me advice..
MediaPlayer mediaPlayer = null;
Stage stage = new Stage();
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);

MediaView mediaView = new MediaView();
int mNextFileIndex = -1;
List<File> fileLists = new ArrayList<>();
Media media;

mediaplayer play Method
public void playNextMedia() {

    if (mediaPlayer != null) {
        mediaPlayer.dispose();
        mediaView.setMediaPlayer(null);
       }

   mNextFileIndex = (mNextFileIndex + 1) % fileLists.size();
   media =new Media(fileLists.get(mNextFileIndex).toURI().toString());

    media.setOnError(()-> {
        MainApp.makeLog("media error");
    });
    mediaPlayer = new MediaPlayer(media);

    mediaView.setMediaPlayer(mediaPlayer);

    mediaPlayer.setOnReady(() -> {
        mediaPlayer.play();
    });

    mediaPlayer.setOnEndOfMedia(() -> {
        playNextMedia();

    });

    mediaPlayer.setOnError(() -> {
      systom.out.println("mediaPlayer error");
      Systeom.out.println(mediaPlayer.getError().getMessage());
      playNextMedia();
    });

}

Button Method
@FXML
private void playMedia(ActionEvent event) {

    mNextFileIndex = -1;

        FileChooser fileChooser = new FileChooser();
        fileChooser.getExtensionFilters().addAll(new
        FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4"),
        new FileChooser.ExtensionFilter("All Files", "*.*"));

        List<File> list = fileChooser.showOpenMultipleDialog(null);

        if (list != null) {
           for (File file : list) {
              fileLists.add(file)
            }

        playNextMedia();

        pane.getChildren().add(mediaView);
        stage.setScene(scene);
        stage.show();
 }


text:
Q: Android: Using linear gradient as background looks banded I'm trying to apply a linear gradient to my ListView.
This is the content of my drawable xml:
 <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#3A3C39"
        android:endColor="#181818"
        android:angle="270"
     />
    <corners android:radius="0dp" />
</shape>

So I apply it to my ListView with:
android:background="@drawable/shape_background_grey"

It works but it looks very "banded" on emulator and on a real device too.
Is there any way to reduce this "behaviour"?

A: Put this in your Activity:
@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);
}

A: As Romain Guy suggests:
listView.getBackground().setDither(true);

solves my problem
If this is not enough especially for AMOLED and/or hdpi devices try this:
@Override
public void onAttachedToWindow() {
    super.onAttachedToWindow();
    Window window = getWindow();
    window.setFormat(PixelFormat.RGBA_8888);
}

A: If the dither and RGBA_888 setting don't help on some phones, the solution can be to set the element layerType to software, to disable the hardware acceleration
android:layerType="software"

This fixed my problem on a Samsung S5 phone.

A: You can simply enable dithering on your Drawable object.

A: For me on HTC Desire works like this
window.getDecorView().getBackground().setDither(true);

A: For me the banding disappeared when I set the android:useLevel="true" on the gradient:
gradient_dark.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#464646"
        android:endColor="#323232"
        android:angle="270"
        android:type="linear"
        android:useLevel="true"
         />
</shape>

But first I tried using a Layer-List with a "noise" drawable to remove the banding, it helps but there is still some banding.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@drawable/gradient_dark"/>
    <item>
        <bitmap
            android:gravity="center"
            android:src="@drawable/noise_repeater"
            android:tileMode="repeat" />
    </item>

</layer-list>

The "noise_repeater" drawable i created and used

A: The only thing that worked for me was to set a slightly-transparent alpha channel on both the startColor and endColor.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:startColor="#FE3A3C39"
        android:endColor="#FE181818"
        android:angle="270"
     />
</shape>

I got the idea to try this from this other SO question: android:dither="true" does not dither, what's wrong?


text:
Q: linking static library with shared object OS : AIX53
Language : C
I have a shared object
[a.so] which uses symbols in another static library [b.a]. The static library b.a is not supplied in the link line for creating a.so. Instead, it is supplied in the final executable binary which uses a.so.
When I run the executable, I am getting undefined symbol errors from a.so. These undefined symbols are those that are defined in b.a. Not sure what I am missing here.
Also, when I do an nm on both a.so and the executable, the symbols are not found. Should I be including b.a in the link line for a.so? I read it is not advisable to link static libraries compiled without fPIC into shared objects. Please advise.


text:
Q: How can I connect to NFS from finder? When I'm reading this guide it seems to be quite straightforward.
http://support.apple.com/kb/PH18705?viewlocale=en_US
But I was expecting to be typing the ip address. I don't understand what they mean by
nfs://DNSname/pathname

DNSname and pathname. Can someone elaborate?
(I'm trying to connect to my seagate business storage nas)

A: In order to mount an NFS share as a client, you need essentially two things:

*

*The name or IP address of the server, referred to as DNSName

*The share path

How do you find this stuff out?
This assumes you don't know what the share paths are.  If you already know, skip down to "Connecting"
Using my own personal Synology Diskstation as an example, I have shared two directories via NFS.  It's DNS name is diskstation.home.  Its IP address is 192.168.1.50 (not really, but it is for the sake of this example)
Launch the Terminal App.
At the prompt, type the following command:
showmount -e diskstation.home
(replace diskstation.home with your DNSname or IP Address)

In my example, the following is displayed:
$ showmount -e diskstation.home
Exports list on diskstation.home:
/volume1/netbackup                  *
/volume1/Network Share              *

Ok...so now I know what the two "share paths" are.  It's time to connect.
Connecting
Let's use finder:
Press CommandK to bring up the "Connect to Server" Dialog Box.
In the "Server Address" box, type enter the values in the format:
nfs://DNSName/path
or
nfs://IP/path

So, going back to my example, I would type:
nfs://diskstation.home/volume1/netbackup
or
nfs://192.168.1.50/volume1/netbackup

You should now be able to browse your network share.

A: After choosing 'Connect to Server...' in Finder with cmdK you may also use an IP-address instead of the DNS-name.
So if your NAS is at 192.168.1.10 (or mynas.example.home) and you've exported a share called 'Share', make sure the NAS provides you the entire pathname - sometimes they'll append /mnt/ (or /mount/ or /nfs/) to the path.
Instead of simple nfs://192.168.1.10/Share (or nfs://mynas.example.home/Share) you'd use nfs://192.168.1.10/mnt/Share (or nfs://mynas.example.home/mnt/Share) then.

A: They are telling you to use the "DNSname/pathname" because using DNS is preferred to using IP addresses in most cases (humans typically remember words better than numbers).
However, this is contingent upon you having DNS configured.
Using the device's IP address and path to the share will work just fine, it just isn't as friendly for remembering the address and telling other people how to access it.


text:
Q: Split Date.now() into parts in Javascript I am trying to split the current date into parts and this is what I am doing
        var today = new Date();

        var currDay = today.getDay();
        var currMonth = today.getMonth();
        var currYear = today.getYear();
        alert(currDay + "/" + currMonth + "/" + currYear)

but with this I get the following result
        0/7/115 (output)

where it should be
        09/07/2015

What can I do to get the required result?

A: Try
var currYear = today.getFullYear();

A: Based on the answer from https://stackoverflow.com/a/3605248/2649340:
var today = new Date();

var output   = ('0' + today.getDate()).slice(-2) + '/'
             + ('0' + (today.getMonth()+1)).slice(-2) + '/'
             + today.getFullYear();

A: Your "today.getDay()" should be "today.getDate()" since .getDay goes from 0-6 (days of the week)
var today = new Date();
var currDay = today.getDate();
var currMonth = today.getMonth();
var currYear = today.getFullYear();
alert(currDay + "/" + currMonth + "/" + currYear);

A: getDay() gives you the day's number (0-6 for sunday to monday), month starts with 0 for january. This is how to do:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();

if(day<10) {
    day='0'+day;
}

if(month<10) {
    month='0'+month;
}

today = month+'/'+day+'/'+year;
alert(today);

A: you can use moment.js. It has a lot of helpful functions for time and date in JavaScript


text:
Q: Rover 5 Robot Platform Motor Controller I am about to purchase a Rover 5 Robot Platform from Spark Fun and I would like to know what type of motor controller I should get, and is there a controlling device instead such as a remote control? Thanks.

A: Big question (and probably one that you'd be better asking SparkFun about - they seem to have a very helpful and knowledgeable staff).
Lots of things to look at:

*

*Stall current

*

*Seems to be 2.5A (manual)

*There's a comment on the site stating that it seems to be a total stall current (4 motors at ~500mA each)

*Comfort with electronics

*

*Will you be comfortable hooking it to an Arduino/RaspPi?

*Or are you keen for plug and play remote control with a standard out of the box transmitter/receiver?

Suggestions:

*

*All bells and whistles - feedback, lots of interface options, but rather expensive.

*Simpler alternative - if you are rather comfortable with electronics the L298 is a very nice H bridge chip, rather easy to use.

(no affiliation to pololu - just like their gear)


text:
Q: Appium Did not successfully proxy server command I have:
[test_instagram.rb]
require 'rubygems'
require 'appium_lib'
appium_txt = 'E:\\Instagram\\appium.txt'
caps = Appium.load_appium_txt file: appium_txt, verbose: false
Appium::Driver.new(caps).start_driver
driver_quit

[appium.txt]
[caps]
platformName = "android"
app = "E:\\Instagram\\instagram.apk"
deviceName = "emulator-5554"
automationName = "Selendroid"

I have started the server with this command: node . --no-reset --session-override
when i run ruby test_instagram.rb, the app starts in emulator (bluestack) and then the following error happens:
C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/response.rb:51:in `assert_ok': Did not successfully proxy server command (Selenium::WebDriver::Error::UnknownError)
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/response.rb:15:in `initialize'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/http/common.rb:59:in `new'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/http/common.rb:59:in `create_response'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/http/default.rb:66:in `request'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/http/default.rb:64:in `request'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/http/common.rb:40:in `call'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/bridge.rb:634:in `raw_execute'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/bridge.rb:99:in `create_session'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/remote/bridge.rb:68:in `initialize'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/common/driver.rb:33:in `new'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver/common/driver.rb:33:in `for'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/selenium-webdriver-2.42.0/lib/selenium/webdriver.rb:67:in `for'
        from C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/appium_lib-4.0.0/lib/appium_lib/driver.rb:436:in `start_driver'
        from test_instagram.rb:22:in `<main>'

what is the problem and How to fix?


text:
Q: Sort map of maps i.e. nested maps in java Lets say I have data which has following structure.
//map1        //map2         //map3
Fruit-------->Apple--------->Green Apple------->4
                             Red Apple--------->5
                             Yellow Apple------>6
                             Total------------->15
              Cherry-------->Red Cherry-------->5
                             Green Cherry------>3
                             Total------------->8
Vegetable----->Capsicum----->Green Capsicum---->5
                             Red Capsicum------>7
                             Yellow Capsicum--->3
                             Total------------->15

In other words I have
Map<String, Map<String, Map<String, Long>>>

I want to sort the innermost map(map3) by values and the middle map(map2) by the value of entry "total" in map3.
I know that typically we can sort the map by value as follows.
import java.util.*;

public class MapUtil
{
 public static <K, V extends Comparable<? super V>> Map<K, V>
    sortByValue( Map<K, V> map )
 {
    List<Map.Entry<K, V>> list =
        new LinkedList<Map.Entry<K, V>>( map.entrySet() );
    Collections.sort( list, new Comparator<Map.Entry<K, V>>()
    {
        public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 )
        {
            return (o1.getValue()).compareTo( o2.getValue() );
        }
    } );

    Map<K, V> result = new LinkedHashMap<K, V>();
    for (Map.Entry<K, V> entry : list)
    {
        result.put( entry.getKey(), entry.getValue() );
    }
    return result;
  }
}

But here the value is a long and not map. I am working on this problem and I think this can be a good way to learn more about maps. Any idea or suggestion about how this can be achieved?


text:
Q: Paypal integration with Magento 2.1 I am trying to integrate Paypal with Magento 2.1. However, I get the following error message:

Error Processing Payment
Error Message" This transaction can't be processed. Please pay with
  another card.

I have set up Paypal as a payment method: Store -> Configuration -> Sales -> Payment Methods
The "Merchant Country" is "United Kingdom".
I have set up an "API Signature".
Still the same error. Anyone have any ideas?

A: It seems the payment was declined due to the credit card issue. Please try with a new credit card or paypal account to test your payment.
To get the details on the previous card decline, please contact PayPal customer service


text:
Q: Script to switch columns according to their positive/negative increment The situation: I have 5 columns. Columns 2 and 3 are min and max ranges and column 4 is a value to indicate positive or negative increment (1 or -1). Columns 1 and 5 are ignored.
However, columns 2 and 3 are currently min (lowest number) to max (highest number), and if column 4 is -1 I want them to be switched. Which script in Linux can do this?
The text files looks like this (first 2 rows out of 400):
44110,2100,2600,1,1
44200,3400,4500,-1,2
Therefore, in the output the second row would contain the switch and the first row would stay the same, as follows:
44110,2100,2600,1,1
44200,4500,3400,-1,2
Thank you in advance for your answers!

A: $ awk 'BEGIN{FS=OFS=","} $4<0{t=$3;$3=$2;$2=t} 1' file
44110,2100,2600,1,1
44200,4500,3400,-1,2


text:
Q: how to stop a function in laravel controller I'm new to LARAVEL. I want to send an AJAX request to a function of controller that this function will run very big loop (takes about 2 minutes). I want to have a button that when click on it, it send a request with AJAX to the controller that stops the function that is running big loop. any idea?

A: After second click (to stop function) you can send to database information about it. In one of 10 loops function can check database and if function get message "stop" then will stopped.


text:
Q: Iterating over tf.Tensor is not allowed: AutoGraph is disabled in this function I am using tensorflow 2.1 along with python 3.7
The following snippet of code is being used to build a tensorflow graph. The code runs without errors when executed as a standalone python script. (Probably tensorflow is running in eager mode? I am not sure.)
import tensorflow as tf
patches = tf.random.uniform(shape=(1, 10, 50, 300), dtype=tf.dtypes.float32)
s = tf.shape(patches)
patches = [patches[0][x][y] - tf.reduce_mean(patches[0][x][y]) for y in tf.range(s[2]) for x in tf.range(s[1])]

However, the code fails when this is part of a tensorflow graph. I receive the following error:
tensorflow.

python.framework.errors_impl.OperatorNotAllowedInGraphError: iterating
  over tf.Tensor is not allowed: AutoGraph is disabled in this function. Try decorating it directly with @tf.function.

I also added the decorator @tf.function to the method which wraps the above lines of code. It didn't help. I am not sure if I fully understand the meaning of decorating with @tf.function. I also checked that this could be a problem with using python list comprehension inside the tensorflow graph. I am not sure how to use tf.map_fn or tf.while_loop for my case, since I have nested loops.
Thanks in advance!

A: List comprehensions are not yet supported in autograph. The error that's raised needs to be improved, too. Piling up on https://github.com/tensorflow/tensorflow/issues/32546 should help resolve it sooner.
Until comprehensions are supported, you have to use map_fn, which in this case would look something like this:
def outer_comp(x):
  def inner_comp(y):
    return patches[0][x][y] - tf.reduce_mean(patches[0][x][y])
  return tf.map_fn(inner_comp, tf.range(s[2]), dtype=tf.float32)
patches = tf.map_fn(outer_comp, tf.range(s[1]), dtype=tf.float32)

That said, I believe you can just use reduce_mean directly:
patches = patches - tf.expand_dims(tf.reduce_mean(patches, axis=3), -1)

A: This naturally works in tf version: 2.5.0. Now you can use the nested comprehensions directly.


text:
Q: Unlocking account from powershell ISE pre made script I was busy making a script where a variable is declared containing the information of the user that you can enter in a prompt.
I thought of this way when I saw that unlock account can't be done with an e-mail address (Logon name after 2000).
But I can't figure out what I am doing wrong.
This is the code i am running right now.
Import-Module ActiveDirectory
[void][System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$name = [Microsoft.VisualBasic.Interaction]::InputBox("Enter your name", "Name", "$env:username")
$Test = Get-ADUser -Filter { EmailAddress -eq $name } | Select SamAccountName
Unlock-ADAccount -Identity $Test

The error i'm getting is
Unlock-ADAccount : Object reference not set to an instance of an object.
At C:\Users\Admcbl\Documents\Powershell.ps1:5 char:1
+ Unlock-ADAccount -Identity $Test
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (Microsoft.Activ...ement.ADAccount:ADAccount) [Unlock-ADAccount], NullReferenceException
    + FullyQualifiedErrorId : Object reference not set to an instance of an object.,Microsoft.ActiveDirectory.Management.Commands.UnlockADAccount

A: You should refer to the SamAccountName property of $Test:
Unlock-ADAccount -Identity $Test.SamAccountName

But why not just pipe the account to the Unlock-ADAccount? Like this:
Get-ADUser -Filter { EmailAddress -eq $name } | Unlock-ADAccount

A: Here might be a simpler solution for you. Notice I switched the filter so @domain.com isn't needed
Import-Module ActiveDirectory

$name = Read-Host -Prompt "Enter Username "

Get-ADUser -Filter {SamAccountName -eq $name} |
    Unlock-ADAccount


text:
Q: How to name assets for different screen resolutions? My app has over 100 images. And how to I specify resources for other resolutions? I see both methods.
One by naming the folders scale-100 and other by naming each file with a suffix of scale 100. My app is developed in C#. And how do I test which image is taken?
For now my folder structure is
Assets -> Images-> scale-100 -> tab_icon_notes_clicked_1366.png

And in the code when I need to reference the image, I reference it like this.
("ms-appx:/Assets/Images/tab_icon_notes_clicked_1366.png");

So without using scale-100 in the image path, it is retrieving an image. I have another folder named as scale-140 in which the higher resolution of the same image is placed. But I cant figure out which image it is taking.. scale-100 or scale-140 ?

A: You can identify the System Display Scale Information by the Code below
var scaleInfo= DisplayProperties.ResolutionScale;

The system will take care of loading the correct Scale Images from the respective Scale Folders [100,140,180].