text:
Q: How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL? In PostgreSQL I have a table with a varchar column. The data is supposed to be integers and I need it in integer type in a query. Some values are empty strings.
The following:
SELECT myfield::integer FROM mytable

yields ERROR:  invalid input syntax for integer: ""
How can I query a cast and have 0 in case of error during the cast in postgres?

A: @Matthew's answer is good. But it can be simpler and faster. And the question asks to convert empty strings ('') to 0, but not other "invalid input syntax" or "out of range" input:
CREATE OR REPLACE FUNCTION convert_to_int(text)
  RETURNS int AS
$func$
BEGIN
   IF $1 = '' THEN  -- special case for empty string like requested
      RETURN 0;
   ELSE
      RETURN $1::int;
   END IF;

EXCEPTION WHEN OTHERS THEN
   RETURN NULL;  -- NULL for other invalid input

END
$func$  LANGUAGE plpgsql IMMUTABLE;

This returns 0 for an empty string and NULL for any other invalid input.
It can easily be adapted for any data type conversion.
Entering an exception block is substantially more expensive. If empty strings are common it makes sense to catch that case before raising an exception.
If empty strings are very rare, it pays to move the test to the exception clause.

A: SELECT CASE WHEN myfield="" THEN 0 ELSE myfield::integer END FROM mytable
I haven't ever worked with PostgreSQL but I checked the manual for the correct syntax of IF statements in SELECT queries.

A: I had the same sort of need and found this to work well for me (postgres 8.4):
CAST((COALESCE(myfield,'0')) AS INTEGER)

Some test cases to demonstrate:
db=> select CAST((COALESCE(NULL,'0')) AS INTEGER);
 int4
------
    0
(1 row)

db=> select CAST((COALESCE('','0')) AS INTEGER);
 int4
------
    0
(1 row)

db=> select CAST((COALESCE('4','0')) AS INTEGER);
 int4
------
    4
(1 row)

db=> select CAST((COALESCE('bad','0')) AS INTEGER);
ERROR:  invalid input syntax for integer: "bad"

If you need to handle the possibility of the field having non-numeric text (such as "100bad") you can use regexp_replace to strip non-numeric characters before the cast.
CAST(REGEXP_REPLACE(COALESCE(myfield,'0'), '[^0-9]+', '', 'g') AS INTEGER)

Then text/varchar values like "b3ad5" will also give numbers
db=> select CAST(REGEXP_REPLACE(COALESCE('b3ad5','0'), '[^0-9]+', '', 'g') AS INTEGER);
 regexp_replace
----------------
             35
(1 row)

To address Chris Cogdon's concern with the solution not giving 0 for all cases, including a case such as "bad" (no digit characters at all), I made this adjusted statement:
CAST((COALESCE(NULLIF(REGEXP_REPLACE(myfield, '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);

It works similar to the simpler solutions, except will give 0 when the value to convert is non-digit characters only, such as "bad":
db=> select CAST((COALESCE(NULLIF(REGEXP_REPLACE('no longer bad!', '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
     coalesce
----------
        0
(1 row)

A: (0 || myfield)::integer

Explanation (Tested on Postgres 8.4):
The above-mentioned expression yields NULL for NULL-values in myfield and 0 for empty strings (This exact behavior may or may not fit your use case).
SELECT id, (0 || values)::integer from test_table ORDER BY id

Test data:
CREATE TABLE test_table
(
  id integer NOT NULL,
  description character varying,
  "values" character varying,
  CONSTRAINT id PRIMARY KEY (id)
)

-- Insert Test Data
INSERT INTO test_table VALUES (1, 'null', NULL);
INSERT INTO test_table VALUES (2, 'empty string', '');
INSERT INTO test_table VALUES (3, 'one', '1');

The query will yield the following result:
 ---------------------
 |1|null        |NULL|
 |2|empty string|0   |
 |3|one         |1   |
 ---------------------

Whereas selecting only values::integer will result in an error message.

A: SUBSTRING may help for some cases, you can limit the size of the int.
SELECT CAST(SUBSTRING('X12312333333333', '([\d]{1,9})') AS integer);

A: I was just wrestling with a similar problem myself, but didn't want the overhead of a function. I came up with the following query:
SELECT myfield::integer FROM mytable WHERE myfield ~ E'^\\d+$';

Postgres shortcuts its conditionals, so you shouldn't get any non-integers hitting your ::integer cast. It also handles NULL values (they won't match the regexp).
If you want zeros instead of not selecting, then a CASE statement should work:
SELECT CASE WHEN myfield~E'^\\d+$' THEN myfield::integer ELSE 0 END FROM mytable;

A: You could also create your own conversion function, inside which you can use exception blocks:
CREATE OR REPLACE FUNCTION convert_to_integer(v_input text)
RETURNS INTEGER AS $$
DECLARE v_int_value INTEGER DEFAULT NULL;
BEGIN
    BEGIN
        v_int_value := v_input::INTEGER;
    EXCEPTION WHEN OTHERS THEN
        RAISE NOTICE 'Invalid integer value: "%".  Returning NULL.', v_input;
        RETURN NULL;
    END;
RETURN v_int_value;
END;
$$ LANGUAGE plpgsql;

Testing:
=# select convert_to_integer('1234');
 convert_to_integer
--------------------
               1234
(1 row)

=# select convert_to_integer('');
NOTICE:  Invalid integer value: "".  Returning NULL.
 convert_to_integer
--------------------

(1 row)

=# select convert_to_integer('chicken');
NOTICE:  Invalid integer value: "chicken".  Returning NULL.
 convert_to_integer
--------------------

(1 row)

A: CREATE OR REPLACE FUNCTION parse_int(s TEXT) RETURNS INT AS $$
BEGIN
  RETURN regexp_replace(('0' || s), '[^\d]', '', 'g')::INT;
END;
$$ LANGUAGE plpgsql;

This function will always return 0 if there are no digits in the input string.
SELECT parse_int('test12_3test');
will return 123

A: Finally I manage to ignore the invalid characters and get only the numbers to convert the text to numeric.
SELECT (NULLIF(regexp_replace(split_part(column1, '.', 1), '\D','','g'), '')
    || '.' || COALESCE(NULLIF(regexp_replace(split_part(column1, '.', 2), '\D','','g'),''),'00')) AS result,column1
FROM (VALUES
    ('ggg'),('3,0 kg'),('15 kg.'),('2x3,25'),('96+109'),('1.10'),('132123')
) strings;

A: The following function does

*

*use a default value (error_result) for not castable results e.g abc or 999999999999999999999999999999999999999999

*keeps null as null

*trims away spaces and other whitespace in input

*values casted as valid bigints are compared against lower_bound to e.g enforce positive values only

CREATE OR REPLACE FUNCTION cast_to_bigint(text)
RETURNS BIGINT AS $$
DECLARE big_int_value BIGINT DEFAULT NULL;
DECLARE error_result  BIGINT DEFAULT -1;
DECLARE lower_bound   BIGINT DEFAULT 0;
BEGIN
    BEGIN
        big_int_value := CASE WHEN $1 IS NOT NULL THEN GREATEST(TRIM($1)::BIGINT, lower_bound) END;
    EXCEPTION WHEN OTHERS THEN
        big_int_value := error_result;
    END;
RETURN big_int_value;
END;

A: This should also do the job but this is across SQL and not postgres specific.
select avg(cast(mynumber as numeric)) from my table

A: I also have the same need but that works with JPA 2.0 and Hibernate 5.0.2:
SELECT p FROM MatchProfile p WHERE CONCAT(p.id, '') = :keyword

Works wonders. I think it works with LIKE too.

A: If the data is supposed to be integers, and you only need those values as integers, why don't you go the whole mile and convert the column into an integer column?
Then you could do this conversion of illegal values into zeroes just once, at the point of the system where the data is inserted into the table.
With the above conversion you are forcing Postgres to convert those values again and again for each single row in each query for that table - this can seriously degrade performance if you do a lot of queries against this column in this table.

A: I found the following code easy and working. Original answer is here https://www.postgresql.org/message-id/371F1510.F86C876B@sferacarta.com
prova=> create table test(t text, i integer);
CREATE

prova=> insert into test values('123',123);
INSERT 64579 1

prova=> select cast(i as text),cast(t as int)from test;
text|int4
----+----
123| 123
(1 row)

hope it helps


text:
Q: jqGrid resize event and the event triggered when page is refreshed I have a jqGrid in my page and I want to know when does the resize event occur. Will it occur when I refresh the page? If not, what event occurs when the page containing the grid is refreshed. I would like to capture the event to alter it's width when the page is refreshed.

A: A page refresh causes a postback, so jQuery/jqGrid events aren't really going to detect a refresh so much as the page loading.
Depending on your goals, I would suggest either the jQuery .ready() method or the jqGrid gridComplete() method to handle grid resizing any time someone opens or refreshes the page.
Which one you use will likely depend on whether the actual data that the grid receives is going to influence how large you want to set the grid.
If the data doesn't matter and you just are concerned about the size of the browser window, I would use .ready() and pre-populate your grid configuration with the appropriate size.
If the data does matter, you'll probably want to use the gridComplete method on your jqGrid.
If you want to be able to adapt your grid size when the user resizes the browser, see this answer: Resize jqGrid when browser is resized?

redpajama_set_name: RedPajamaStackExchange


text:
Q: white list ip addresses i have the following function that checks a list of ip address if the ip address is not found in the list it will throw an error as follows
public Task TestIp<T>(dynamic body)
        {
            var httpContext = DependencyResolver.GetService<IHttpContextAccessor>()?.HttpContext;

            if (!_ips.Contains(httpContext.Connection.RemoteIpAddress)) //passes ::1
            throw new Exception("invalid");
}

one of my ips in list example is 127.0.0.1 which is a local host. but with the above code i get the following ip address passed as ::1
so this is what i tried
var remoteIp = httpContext.Connection.RemoteIpAddress;
            remoteIp = remoteIp.MapToIPv4()

            if (!_ips.Contains(remoteIp))
            throw new Exception("invalid");

but now the remoteIp = 0.0.0.1
so now the remoteIp doesnt match the ip adress stored 127.0.0.1 !=  0.0.0.1


text:
Q: Unique Particle Attribution Exception when i use  within  I need either apps element or other element defined in some other xsd (which I am importing through <xsd:any> ) or both. I have used choice but it is throwing Unique Particle Attribution Exception.
<xsd:sequence>
    <xsd:choice minOccurs="1" maxOccurs="unbounded">
        <xsd:element name="apps" />
        <xsd:any minOccurs="0" namespace="##local" />
    </xsd:choice>
</xsd:sequence>

A: This won't work because the XML processor does not know where your apps alement belongs to. xsd:element or xsd:any. It cannot do a look-ahead. Choose another namespace.

A: Unique Particle Attribution helps prevent ambiguity - where you have the apps element defined alongside the xsd:any, it is ambiguous whether the apps element is associated with the specific element declaration (xsd:element name="apps") or with the wildcard (xsd:any).
Your question doesn't give enough detail for a full answer - are the other non "apps" elements completely unspecified? E.g. is it literally any element, or is it "apps" and other well defined choices? If you have can defined the other elements then add those as specified choices, otherwise you may as well use xsd:any without the need to define the "apps" element.

A: Your schema is legal in XSD 1.1, which resolves the ambiguity by saying that a match against an explicit element declaration wins over a match against a wildcard. In XSD 1.0, however, you can't have a choice between a specific element and a wildcard if the namespaces allowed by the wildcard include the namespace of the specific element.


text:
Q: Can i set a custom uid in firebase anonymous auth with java? I am authenticating anonymously to access firebase but I would like the self-assigned UID to be according to a standard that I have defined, then I leave the anonymous authentication code I use:
auth.signInAnonymously()
        .addOnCompleteListener(task -> {
            if (task.isSuccessful()) {

                mUsername = idChat.substring(0, 10);
                id = task.getResult()
                        .getUser()
                        .getUid();
                isLoggedIn = true;
                mPhotoUrl = "";
                initAdapter();
            }
        })
        .addOnFailureListener(task -> displayError(task.getMessage()));

A: No, you cannot. You can use Firebase Anonymous Authentication to create and use temporary anonymous accounts to authenticate with Firebase. Note, that if an anonymous user decides to sign up to your app later, you can link their sign-in credentials to the anonymous account so that they can continue to work with their protected data in future sessions.
Users are identifiable by the same Firebase user ID regardless of the authentication provider they used to sign in (Anonymous Authentication, User/Password, Google account, Facebook account and so on).
So the custom id is generated by Firebase and there is no possibility to set a custom uid as in your terms.


text:
Q: Why does Android's parcel.readList work with ImmutableList? Why is it possible to use an ImmutableList with parcel.readList?
void someParcelFunction(Parcel parcel) {
    ImmutableList<String> myList = ImmutableList.of();

    parcel.readList(myList, ImmutableList.class.getClassLoader(), String.class);
}

When I look at the source code for parcel.readList I can see that the add method is called on the outVal (first argument) of the method:
private <T> void readListInternal(@NonNull List<? super T> outVal, int n,
            @Nullable ClassLoader loader, @Nullable Class<T> clazz) {
        while (n > 0) {
            T value = readValue(loader, clazz);
            //Log.d(TAG, "Unmarshalling value=" + value);
            outVal.add(value);
            n--;
        }
    }

But in Guava's documentation it looks like this method is deprecated and should throw an UnsupportedOperationException: https://guava.dev/releases/20.0/api/docs/com/google/common/collect/ImmutableList.html#add-int-E-. And this would make sense because not only should an Immutable list be immutable, but I am also initialising this list to empty and then it seems like it's actually being modified.
However, the code above runs and no exceptions are thrown. Why is that?

A: It doesn't. Possibly you are either not running the code you think you are running, or you're attempting to read in a 0-len list, which ends up never calling add, thus never causing any problem.
The fact that the method is deprecated is irrelevant - that is a compile-time (i.e. 'as you write it', not 'as you run it') only feature that means that invoking .add on an expression whose type is ImmutableList gets you a warning, but invoking it on an expression whose type is List (and an ImmutableList is a kind of list, so, that's possible, and in fact exactly what happens in readList's implementation) causes no issues, and @deprecated doesn't do anything else.
The fact that ImmutableList's add implementation straight up throws - that would, of course, do something at runtime. In fact, readList cannot possibly get around this. Hence, either you aren't running what you think you are running, or, you're reading a 0-len list, in which case that while loop is skipped immediately, and outVal.add is never invoked.


text:
Q: StyleFrame to_excel string attribute error I'm trying to use Pandas, but keeping the format of the template when I use "pd.read_excel".
I found out that "StyleFrame" could solve my problem, and it actually did after saving the model without any change.
Nevertheless after my code change the informations, I can't save the file properly...
I keep having this error: AttributeError: 'str' object has no attribute 'style'.
I read that the problem is that it tries to apply styles to the data my code wrote, but it doesn't need to. I only need to keep the format of the template I import...
The whole code works, the problem is when I try to save to excel.
Can someone help?
planilha.iloc[[16], [1]] = numero_remessa #String
planilha.iloc[[31], [1]] = peso #Float
planilha.iloc[[29], [1]] = info_materiais #String
planilha.iloc[[27], [1]] = sum(pallets) #Int
planilha.to_excel(f'C:/Users/usuario/Desktop/Python/PyCharm/Wanger/{str(numero_remessa).replace("/","-")[5:13]}.xlsx').save()
    #The error appears in this last line even if I save with a regular name.


text:
Q: How do you add command line args to airflow python operator? validation = PythonOperator(
    task_id="validation",
    python_callable=validation,
    op_args=[
            "--foo", foo,
            "--bar", "null",

    )
)

I'm trying to call a method from the airflow PythonOperator that requires command-line arguments which are accessed using argparse. How do I add these in to the PythonOperator?
I tried the above example but these arguments were invalid. The validation method takes no arguments.
I get this error:
ERROR - Failed to execute job 51 for task validation (main() takes 0 positional arguments but 4 were given; 10436)
[2023-02-17, 19:07:36 UTC] {{local_task_job.py:159}} INFO - Task exited with return code 1


text:
Q: How to inject CrudRepository and EntityManager from secondary DataSource? I want to initialize two DataSource in my app, as follows:
@Configuration
public class DataSourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties(prefix="spring.datasource")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties(prefix="spring.datasource2")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
}

Now I want to use the secondary datasource explicit as follows:
public class SecondaryDbService {
   @Autowired
   private EntityManager em;

   @Autowired
   private SecondaryCrudRepository dao;
}

interface SecondaryCrudRepository implements CrudRepository<SecondaryEntity, Long> {
}

If configured as above, the service would use the primary datasource.
Question: how can I tell the CrudRepository to rely on the "secondaryDataSource"? And likewise, how can I inject the EntityManager from the "secondaryDataSource"?

A: If you want to use multiple datasources, the key is to have the configurations for each Datasource in different packages. You will need to separate your entities between these packages according to which datasource they should access.
You will also have to implement both entity and transaction managers for each datasource in these packages.
To much theory ? in practical it would look something like this:
com.package1
- com.package1.entities
   - EntityClass1.java (annotated with @Entity)
- ConfigForDataSource1.java

com.package2
- com.package2.entities
   - EntityClass2.java (annotated with @Entity)
- ConfigForDataSource2.java

Here's how ConfigForDataSource1 would look like:
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerDataSource1",
    basePackages = "com.package1",
    transactionManagerRef = "TransactionManagerDataSource1")
public class MasterDBConfig {

   @Bean(name="DataSource1")
   @ConfigurationProperties(prefix = "datasource1.datasource")
   public DataSource dataSource() {
       return DataSourceBuilder.create().build();
   }

   @Bean(name="entityManagerDataSource1")
   public LocalContainerEntityManagerFactoryBean entityManagerDataSource1(EntityManagerFactoryBuilder builder,@Qualifier("DataSource1") DataSource dataSource) {
       return builder.dataSource(dataSource).packages("com.package1").persistenceUnit("DataSource1").build();
    }

   @Bean(name = "TransactionManagerDataSource1")
   public PlatformTransactionManager TransactionManagerDataSource1(@Qualifier("entityManagerDataSource1") EntityManagerFactory entityManagerFactory) {
       return new JpaTransactionManager(entityManagerFactory);
   }
}

Then do the same for package 2 and enjoy.
Good luck !


text:
Q: How to update Ruby On Rails app code aws ec2 instance Any AWS experts there?
I was wondering let say if we have rails app deployed on aws ec2 on 2 instances.
Now if I connect to app over the ssh and update code (ruby code on rails app, just minor changes in a code)

*

*1 -Do I need anything else there?

*2 -Do I need to do that on every app instance?

*3 -Do I need to do any reboot of instance?

Changes is so small it is not worth to redeploy app again which takes in our case 90 minutes.


text:
Q: Ruby on Rails: Issue sorting index based on average review rating So I am trying to order my Provider's (similar to a User) index by average rating, with the highest at the top. It works, but adds an extra row for each Review that a Provider has. E.g. If I have one Provider with 3 Reviews, the Provider will show up 3 times in the Providers index. Rating is a column on Reviews and is an integer between 1-5.
provider.rb
class Provider < ActiveRecord::Base
  belongs_to :user, foreign_key: 'user_id', autosave: true
  has_many :reviews, dependent: :destroy
end

review.rb
class Review < ActiveRecord::Base
  belongs_to :user, foreign_key: 'user_id'
  belongs_to :provider, foreign_key: 'provider_id'
end

providers_controller.rb
class ProvidersController < ApplicationController
  before_action :set_provider, only: [:show, :edit, :update, :destroy]

 def index
   @providers = Provider.all
                 .joins(:reviews)
                 .order("reviews.rating DESC")
   @reviews = Review.find_by(params[:provider_id])
 end

index.html.erb
 <% @providers.each do |provider| %>

    <%= link_to provider.name, provider_path(provider.id) %>
    <%= provider.industry %>
    <%= provider.experience %>
    <%= provider.description %>
    <%= provider.reviews.average(:rating) %>

<% end %>

Its probably something really silly as I am quite new to Ruby + Rails, but I cant seem to figure it out/find an relevant info. I've tried adding "AVG(reviews.rating) DESC" to the order method but that gives me an SQLite exception error.
Any help would be muchly appreciated!!! Happy to provide any more info if needed.

A: It gave you a sql error because your error has nothing to do with rails.
In SQL, if you are using an aggregate function such as avg(), then that column must appear in your select clause.
Provider.select("avg(reviews.rating) as avg_rating").joins(:reviews).order("avg_rating desc")

Edited due to comment below

A: I assume you are asking multiple results of the same provider, so I'm going to try and address that. When you join the provider and reviews table, you will get as many rows returned for each provider as that provider has reviews. This is because if we have a provider:
{:id => 1, :reviews => [...]}
and join that with these reviews:
[{:id => 1, :provider_id => 1, :content => "blah"}, {:id => 2, :provider_id => 1, :content => "bar"}, {:id => 3, :provider_id => 1, :content => "foo"}]
SQL will return a table that looks something like:
provider_id, review_id, content
1             1           blah
1             2           bar
1             3           foo

In your case I think an appropriate solution would just be to eliminate the joins clause completely. Doing so should eliminate the duplicates, and you can still access the reviews through the providers has_many relation.


text:
Q: Exception caught in System.Threading.Timers TimerCallback event handler and then re-thrown not sent back to main thread I need for exceptions thrown within a timed event to be bubbled up and handled outside of the event handler context. I had read that System.Threading.Timers would be able to do that, provided that, as outlined in the answer to this question, the exception is caught in the callback method and a mechanism is used to re-throw it. Using this example as a guide, I created an event handler which throws and a method which should catch and re-throw the exception using an IProgress object:
void ThrowerThreaded() {
    var progress = new Progress<Exception>((ex) => {
        throw ex;
    });
    Timer timer = new Timer(x => onTimerElapsedThrow2(progress), null, 10, -1);
    Thread.Sleep(1000);
}

void onTimerElapsedThrow2(IProgress<Exception> progress) {
    try {
        throw new Exception();
    } catch (Exception ex) {
        progress.Report(ex);
    }
}

I then wrote a unit test to see if the exception would bubble up:
[TestMethod]
public void TestThreadedTimerThrows() {
    Assert.ThrowsException<Exception>(ThrowerThreaded);
}

The test case fails indicating no exception was thrown. If I debug the test case, I can clearly see that the exception is caught and re-thrown in ThrowerThreaded() however the method still continues and exists normally. Why is the exception still being suppressed?

A: I'm guessing ThrowerThreaded is running on a background thread. That means it does not have a synchronizationContext, since these are intended to synchronize UI applications. This means the callback is called on the threadpool:

Any handler provided to the constructor or event handlers registered with the ProgressChanged event are invoked through a SynchronizationContext instance captured when the instance is constructed. If there is no current SynchronizationContext at the time of construction, the callbacks will be invoked on the ThreadPool.

Rethrowing the exception on a threadpool thread will probably kill that thread, and I'm somewhat surprised it did not kill the application, but it's possible that such behavior is overridden by the testing framework you are using.
To solve this you really need to handle the exception in the callback instead of re-throwing it. If you are not handling the exception, who should? there is a unhandledExceptionEvent, but that is intended for logging before you close your app.
You could handle the exception taking a callback in ThrowerThreaded that you delegate the exception handling to. Another alternative would be to create a TaskCompletionSource that allow you to return a task, and set the task to 'failed' by calling SetException on the source.
It is also poor practice to re-throw the same exception object, since you will lose the call stack, you should instead wrap the exception in a new exception that is thrown.


text:
Q: Filter a pandas df based on some rules in a yaml file I have a configuration yaml file that is supposed to be used by customers and be easy to edit. In the yaml file there are some rules:
variables:
  used_often: ['good','bad', 3]

rules:
  - dataframe_name: my_name
    variables:
      consequence: used_often
    query: 'column_a = 5 and column_b in ${consequence} and column_c != 1'
    output: {'column_d': 1}
  - more rules like this

As you can see here I want to filter 3 columns in the df my_name where column_a = 5 etc. and then in the result of this filter add/change column_d so that all rows that matched the query have column_d = 1.
My question is how could I make the query more easy to be filtered with pandas. As it stands, the query above should end up in pandas like this:
my_name[(my_name["column_a"] == 5) &
 (my_name["column_b"].isin(['good','bad', 3])) &
 (my_name["column_c"] != 1)]

So I have to do a lot of processing to interpret the query in yaml. Are there any tools that could help me or better ways to format the query (I have complete freedom in building the yaml file as long as it is reasonable easy for a client to write it)?
Thanks!

A: There is a pandas.query function that does all that https://pandas.pydata.org/pandas-docs/version/0.22/generated/pandas.DataFrame.query.html
So my query in yaml becomes:
query: 'column_a == 5 and column_b in @consequence and column_c !=1'

and then in python I can read the yaml and filter:
df.query(my_query)


text:
Q: Batch / bat file help - IE options and resizing I am attempting to figure out a way to execute commands using a batch file to complete a particular action - the action is opening up a IE window for a specific link using extra features such as status=no,toolbar=no,menubar=no + setting size of window.
This is the script that is run through browser, when it accomplishes the same thing I am trying to do. window.open('/xx/xx/xx.htm','newWin','status=no,toolbar=no,menubar=no,resizable=yes,scrollbars=no,height=640,width=640,center')
Using something simple like this, allows me to open a window fine but does not allow for extra options as mentioned above, or resizing of window
start iexplore http://x.x.x.com/x/x

I have seen being able to use -k as a flag to force IE into full screen mode without any toolbars etc but that is not what I am looking for. I would like to be able to specifically define what I do and don't want included, through a batch file.
My only issue with window resizing is that I cannot use autohotkey or similar, if possible only through batch would be best but if other solutions with javascript are avail I would like to hear of those as well.


text:
Q: Force React component naming with TypeScript There is React+TypeScript application, and all component classes should be upper-cased and have Component suffix, e.g:
export class FooBarComponent extends React.Component {...}

The application is ejected create-react-application application, i.e. is build with Webpack.
How can component naming be forced to be consistent with style guide, at least for component classes, with error being thrown on build when there are inconsistencies?
I believe this cannot be achieved with TSLint/ESLint alone. If different methods should be used for TypeScript and JavaScript, solutions for both languages would be helpful.

A: This is lot easier to do in eslint. The custom plugin is a lot less complex. So I created a plugin showcasing the same. To test the plugin I created the below file
import React from "react"

class ABCComponent extends React.Component {

}

class ABC2component extends React.Component {

}

class TestComponent {

}

class FooBarComponent extends React.Component {

}

class fooBazComponent extends React.Component {

}

class FooBazing extends React.Component {

}

And then ran the plugin on the same

I followed the below guides while writing the plugin
https://flexport.engineering/writing-custom-lint-rules-for-your-picky-developers-67732afa1803
https://www.kenneth-truyers.net/2016/05/27/writing-custom-eslint-rules/
https://eslint.org/docs/developer-guide/working-with-rules
The final code I come up with was below for the rules
/**
 * @fileoverview Check that proper naming convention is followed for React components
 * @author Tarun Lalwani
 */
"use strict";

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
var toPascalCase = require('to-pascal-case');

module.exports = {
    meta: {
        docs: {
            description: "Check that proper naming convention is followed for React components",
            category: "Fill me in",
            recommended: false
        },
        fixable: "code",  // or "code" or "whitespace"
        schema: [
            // fill in your schema
        ]
    },

    create: function(context) {

        // variables should be defined here

        //----------------------------------------------------------------------
        // Helpers
        //----------------------------------------------------------------------

        // any helper functions should go here or else delete this section

        //----------------------------------------------------------------------
        // Public
        //----------------------------------------------------------------------

        return {

            ClassDeclaration: function(node) {
                var isReactComponent = false;
                if (node.superClass && node.superClass && node.superClass)
                {
                    if (node.superClass.object && node.superClass.object.name == 'React' && node.superClass.property.name === 'Component')
                        {
                            isReactComponent = true;
                        }
                    else if (node.superClass && node.superClass.name === 'Component') {
                        // if you want to suppot extends Component instead of just React.Component
                        isReactComponent = true;
                    }
                }

                if (isReactComponent) {
                    var className = node.id.name;
                    if (className[0] !== className[0].toUpperCase() || !className.endsWith("Component"))
                         context.report({
                            node: node,
                            message: "Please use Proper case for the React Component class - {{identifier}}",
                            data: {
                                identifier: className
                            }, fix: (fixer) => {
                                var newClassName = className.toLowerCase().replace('component', '') + 'Component';
                                newClassName = toPascalCase(newClassName);
                                return fixer.replaceTextRange(node.id.range, newClassName)
                            }
                        });

                }
            }

        };
    }
};

The key is to understand the AST Tree, which I did using astexplorer. Rest code is quite self explanatory.
I have hosted the plugin on below repo in case you want to give it a short directly
https://github.com/tarunlalwani/eslint-plugin-react-class-naming
Install the plugin using below command
npm i tarunlalwani/eslint-plugin-react-class-naming#master

Then add it to your .eslintrc
{
    "plugins": [
       "react-class-naming"
    ]
}

Then add the rules in .eslintrc
"rules": {
   "react-class-naming/react-classnaming-convention": ["error"],
   ....
}

A: I can offer you only solution for typescript.

I believe this cannot be achieved with TSLint/ESLint alone.

There is a so-called rule class-name that can solve your issue partially but seems you need to write custom rule for such case.
So let's try writing such custom tslint rule. For that we need to use rulesDirectory option in tslint config to specify path to custom rules
"rulesDirectory": [
    "./tools/tslint-rules/"
],

Since I'm going to write custom rule in typescript I will be using one feature that was added in tslint@5.7.0

[enhancement] custom lint rules will be resolved using node's path
  resolution to allow for loaders like ts-node (#3108)

We need to install ts-node package
npm i -D ts-node

Then add fake rule in tslint.json
"ts-loader": true,

and create file tsLoaderRule.js in our rulesDirectory:
const path = require('path');
const Lint = require('tslint');

// Custom rule that registers all of the custom rules, written in TypeScript, with ts-node.
// This is necessary, because `tslint` and IDEs won't execute any rules that aren't in a .js file.
require('ts-node').register({
    project: path.join(__dirname, '../tsconfig.json')
});

// Add a noop rule so tslint doesn't complain.
exports.Rule = class Rule extends Lint.Rules.AbstractRule {
    apply() {}
};

This is basically approach which is widely used in angular packages like angular material, universal etc
Now we can create our custom rule(expanded version of class-name rule) that will be written in typescript.
myReactComponentRule.ts
import * as ts from 'typescript';
import * as Lint from 'tslint';

export class Rule extends Lint.Rules.AbstractRule {
  /* tslint:disable:object-literal-sort-keys */
  static metadata: Lint.IRuleMetadata = {
    ruleName: 'my-react-component',
    description: 'Enforces PascalCased React component class.',
    rationale: 'Makes it easy to differentiate classes from regular variables at a glance.',
    optionsDescription: 'Not configurable.',
    options: null,
    optionExamples: [true],
    type: 'style',
    typescriptOnly: false,
  };
  /* tslint:enable:object-literal-sort-keys */

  static FAILURE_STRING = (className: string) => `React component ${className} must be PascalCased and prefixed by Component`;

  static validate(name: string): boolean {
    return isUpperCase(name[0]) && !name.includes('_') && name.endsWith('Component');
  }

  apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
    return this.applyWithFunction(sourceFile, walk);
  }
}

function walk(ctx: Lint.WalkContext<void>) {
  return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
    if (isClassLikeDeclaration(node) && node.name !== undefined && isReactComponent(node)) {
      if (!Rule.validate(node.name!.text)) {
        ctx.addFailureAtNode(node.name!, Rule.FAILURE_STRING(node.name!.text));
      }
    }
    return ts.forEachChild(node, cb);
  });
}

function isClassLikeDeclaration(node: ts.Node): node is ts.ClassLikeDeclaration {
  return node.kind === ts.SyntaxKind.ClassDeclaration ||
    node.kind === ts.SyntaxKind.ClassExpression;
}

function isReactComponent(node: ts.Node): boolean {
  let result = false;
  const classDeclaration = <ts.ClassDeclaration> node;
  if (classDeclaration.heritageClauses) {
    classDeclaration.heritageClauses.forEach((hc) => {
      if (hc.token === ts.SyntaxKind.ExtendsKeyword && hc.types) {

        hc.types.forEach(type => {
          if (type.getText() === 'React.Component') {
            result = true;
          }
        });
      }
    });
  }

  return result;
}

function isUpperCase(str: string): boolean {
  return str === str.toUpperCase();
}

and finally we should put our new rule to tsling.json:
// Custom rules
"ts-loader": true,
"my-react-component": true

So such code as
App extends React.Component

will result in:

I also created ejected react-ts application where you can try it.
Update

I guess tracking class names in grandparents won't be a trivial task

Indeed we can handle inheritance. To do that we will need create rule extended from class Lint.Rules.TypedRule to have access to TypeChecker:
myReactComponentRule.ts
import * as ts from 'typescript';
import * as Lint from 'tslint';

export class Rule extends Lint.Rules.TypedRule {
  /* tslint:disable:object-literal-sort-keys */
  static metadata: Lint.IRuleMetadata = {
    ruleName: 'my-react-component',
    description: 'Enforces PascalCased React component class.',
    rationale: 'Makes it easy to differentiate classes from regular variables at a glance.',
    optionsDescription: 'Not configurable.',
    options: null,
    optionExamples: [true],
    type: 'style',
    typescriptOnly: false,
  };
  /* tslint:enable:object-literal-sort-keys */

  static FAILURE_STRING = (className: string) =>
    `React component ${className} must be PascalCased and prefixed by Component`;

  static validate(name: string): boolean {
    return isUpperCase(name[0]) && !name.includes('_') && name.endsWith('Component');
  }

  applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
    return this.applyWithFunction(sourceFile, walk, undefined, program.getTypeChecker());
  }
}

function walk(ctx: Lint.WalkContext<void>, tc: ts.TypeChecker) {
  return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
    if (
        isClassLikeDeclaration(node) && node.name !== undefined &&
        containsType(tc.getTypeAtLocation(node), isReactComponentType) &&
        !Rule.validate(node.name!.text)) {
      ctx.addFailureAtNode(node.name!, Rule.FAILURE_STRING(node.name!.text));
    }

    return ts.forEachChild(node, cb);
  });
}
/* tslint:disable:no-any */
function containsType(type: ts.Type, predicate: (symbol: any) => boolean): boolean {
  if (type.symbol !== undefined && predicate(type.symbol)) {
    return true;
  }

  const bases = type.getBaseTypes();
  return bases && bases.some((t) => containsType(t, predicate));
}

function isReactComponentType(symbol: any) {
  return symbol.name === 'Component' && symbol.parent && symbol.parent.name === 'React';
}
/* tslint:enable:no-any */

function isClassLikeDeclaration(node: ts.Node): node is ts.ClassLikeDeclaration {
  return node.kind === ts.SyntaxKind.ClassDeclaration ||
    node.kind === ts.SyntaxKind.ClassExpression;
}

function isUpperCase(str: string): boolean {
  return str === str.toUpperCase();
}

See also commit:

*

*https://github.com/alexzuza/react-ts-test/commit/98ea77fa5a1f4fc73c53a055deb6960a3e7f3afe


text:
Q: Matrix will not allow me to use sample() So the code:
 matrix(apply(hand, 1, sample(1:5,5,replace=TRUE)),byrow=TRUE, nrow=5)

Gives me the error message "Error in match.fun(FUN) :
  'sample(1:5, 5, replace = TRUE)' is not a function, character or symbol"
It seems counter-intuitive because sample() is a function??
Note: hand is itself a matrix of the same size of nrow=5, which I would like to fill by taking sample()


text:
Q: How to return the actual data from within a timeout instead of the timeout promise I'm trying to return data from a function but I need a timeout in order to wait for some data to be set before doing some actions. However I can't figure out the most vital piece.
How can I return 'A string' from myFunc instead of the $timeout promise?
function myFunc() {

  return $timeout(function() {

    return 'A string';
  });
}

A: You could access A string waiting for the promise to resolve
myFunc().then(function(data){
    console.log(data); // 'A string'
});


text:
Q: Vue particles doesn't work with my project? Hello everyone! I currently integrated vue particle into my vue project!
but for some reason something went wrong when I importing VueParticles inside Main.js file!This is snapshot from my terminal.

A: There's a problem with transform-runtime, a dependency of vue-particles. You can fix it running:
npm install babel-plugin-transform-runtime babel-preset-stage-2 --save-dev
There's an issue at vue-particles discussing about that. You can check it here.


text:
Q: Неправильное отображение оставшегося времни PHP Нужно, чтобы человек нажимая на кнопку получения бонуса смог ровно через сутки снова получить бонус.
Проблема в том, что когда человек нажимает на кнопку получения бонуса спустя час, то в ответ получает не "получение будет позможно через 23 часа", а наоборот, через 25 часов.
Код:
 if(DB::uCountColumns("SELECT * FROM `Bonus` WHERE `chat_id` = '$chatId' AND `date` >= NOW() -  INTERVAL '1' DAY")){
$hour = DB::uFetch("SELECT TIMESTAMPDIFF(HOUR , `date`, NOW() + INTERVAL '24' HOUR) AS hour FROM `Bonus` WHERE `chat_id` = '$chatId' AND `date` + INTERVAL '24' HOUR > NOW()")["hour"];
  $welcomeMsg = "Следующий бонус будет доступен через *{$hour}* часа";

Что тут не так?


text:
Q: Setting a variable based on TypeScript Generic Is it possible to set a variable based on a TypeScript Generic?
class Foo<T> {
  constructor() {
    // This doesn't actually work but it's essentially what I would like to do
    const myKey = (T extends number ? 'myNumber' : null);
  }
}

Here is a more complete example that will work in an external IDE. The objective here is to instantiate the Animal class with the appropriate generic (Dog | Cat) while also giving the constructor the ability to get a subset of the Object returned from getUpdate. In the below example, this is done with myKey. To reiterate on my original question, is there a way to perform all of this without having "Dog" appear 2 times when instantiating the class?
interface Dog {
  bark: string;
}

interface Cat {
  meow: string;
}

type AnimalType<T> =
  T extends Dog ? Dog :
    T extends Cat ? Cat : null;

const getUpdate = (): Record<string, Dog | Cat> => ({
  dog: { bark: 'woof' },
  cat: { meow: 'meow' },
});

class Animal<T> {
  public state!: AnimalType<T>;

  constructor(myKey: 'dog' | 'cat') {
    this.state = getUpdate()[myKey] as AnimalType<T>;
  }
}
// dogInstance is of type `Animal<Dog>` with a state of `{ bark: 'woof' }`
const dogInstance = new Animal<Dog>('dog');

A: What I see is that you are mixing value and type level. We need to understand the difference, you need to have real value for given type to assign it, you cannot just assign a type.
I believe this is what you are looking for:
class Foo<T> {
  constructor(key: T extends number ? 'myNumber' : null) {
    const myKey = key;
  }
}

const foo = new Foo<number>('myNumber'); // only possible option is 'myNumber'
const fooNull = new Foo<null>(null); // only possible option is null

As you can see I am constraining the real value of the argument and pass it to myKey.


text:
Q: Facebook javascript sdk and manual login/logout flow I am building a chrome kiosk with a manual facebook share flow. (I can also use the javascript sdk, but still run into the same issue).
In the perfect scenario, a user logs in and authenticates the app. On login/authentication complete, facebook will hit the redirect_uri with an access token.
var loginUrl = "https://graph.facebook.com/oauth/authorize?"
+"client_id=" + facebookId
+"&redirect_uri=" + loginRedirectURI
+"&response_type=token"

I can save that access token to logout the user manually:
var logoutUrl = "https://www.facebook.com/logout.php?"
+"client_id=" + facebookId
+"&next=" + redirectURILogout
+"&access_token="+accessToken;

Problem:
If the user logs in and then hits cancel or closes out of the window to the permissions/app authorization modal, facebook redirects to the redirect_uri with no access token. As far as I know, I only can logout a facebook user with an access token. Since this kiosk will be public, it's problematic if another user wants to share content and someone else's account is still logged in.
Has anyone used the facebook flow on a public computer and have any suggestions?


text:
Q: How to "fill" background image? I'm making a website where I need to have a notable difference between fill and center background images. My template is this:
Center: Uses native resolution to determine size.

Fill: Fits sides to fill screen without changing aspect ratio. Two sides exactly fit screen, while other two are cut off.

I managed to get centered with
.center {
    background-repeat: no-repeat;
    background-size: auto auto;
    background-position: center center;
}

But I can't figure out how I would do fill. Any insight?

A: I believe you want background-size: cover. Other background-size options.


text:
Q: Fabric, cluster, server Here is the marketing page for the Intel True Scale Fabric
http://www.intel.com/content/www/us/en/infiniband/truescale-infiniband.html

The Intel® True Scale Fabric Host Channel Adapters (HCA) along with
  its host stack, Performance Scaled Messaging (PSM), were specifically
  developed to provide an optimized, connectionless transport mechanism
  for each server. Together with the Intel® True Scale Fabric Switch
  12000 Series, a very high-performing fabric for HPC clusters and their
  Message Passing Interface (MPI) applications is created. Every member
  of the Intel True Scale Fabric Switch 12000 Series provides
  predictable, scalable performance, even under heavy traffic and
  extreme message rate load. All Intel True Scale Fabric products can be
  managed via the Intel True Scale Fabric Suite, providing an overall
  view into the health, status, and performance of a truly high
  performance computer cluster.

From there, i understand that a Fabric is the set of Host adapters, switches, interconnect and software tools to make a cluster.
I am not sure then how much fabric, cluster and servers are synonyms for the same thing? What are differences?

A: A good explanation is here.
Basically a cluster is made of servers, each one interconnected in a hierarchical topology. I'm not an expert on this field but basically you have server racks (i.e. computers) connected together with TOR (Top Of Rack) switch, each TOR switch is connected together with a cluster switch.
If needed more cluster can be connected together, again with an hierarchical topology .
A fabric is and alternative to aggregation of clusters and it is made of servers, each one interconnected with a uniform HPC topology. The base unit is a server pod, composed of server racks and fabric switches. Fabric switches are connected to spine switches that are connected by edge switches.
As I understand it, fabrics are a replacement of clusters of clusters.
I don't know what Intel brand names like Intel® True Scale Fabric Host Channel Adapters and Intel® True Scale Fabric Switch 12000 designates in term of hardware but my guess is that the HCA is an adapter used to connect a server rack with the Fabric Switch 12000 (that can be connected together through spine switched that can be connected... you got it) though a protocol like InfiniBand.

A: Starting from Ethernet shared bus. Limitation is that in the shared bus, collisions means loss of the frame. The CSMA/CD checks whether frame can be sent before sending. Nevertheless, performance is hindered.
Enter switches, to reduce the number of devices communicating over a given communication segment. Full-duplex.
Then switches investigated the ability to connect any device to any device. Again, collision occurs.
The crossbar switch, in silicon form, enables this any to any connection. It is possible to simulteaneously send frames over several segments, no collision !
more here http://etherealmind.com/what-is-the-definition-of-switch-fabric/


text:
Q: Transition to linux How does someone with major experience in other OS's make a transition to Linux if one's been using it for a while, on and off for two years.
By transition I mean everyday use without booting to something else. How does someone learn some advanced operation skills with shell for everyday use? Note that I'm not asking about the basic skills, I get stuck with other things that are deeply involved with the system itself and can only come with everyday use.
I know there are books and sites around that can help, but I guess I'm asking what the easiest way is to do it instantly.

A: The easiest way to make the transition to Linux, in my case, was setting up a dual boot system with Windows and Ubuntu where the Windows system simply didn't get to be booted anymore.
A friend of mine, who is a full-blown Linux geek, kept nagging me about giving Linux a try.
Back then my only experience with Linux was an awfully configured, unstable Linux Linpus that had come with my netbook as an OEM install.
Since the Linpus distro on my netbook was pretty much useless and had only caused me problems so far, I gave him leave to install some other flavour of Linux and show me how it all worked in the process.
That way he taught me some Linux basics, including stuff like how to use a terminal (my friend is an avid fan of the command line, and I guess so am I now, too), file systems, the OSI model, the Free Software movement, and so on.
The positive experience with Linux on my netbook eventually inspired me to have Linux running on my desktop computer, too.
This is how the dual-boot system came into being.
After the setup it so happened that I booted only Ubuntu for several days straight, and somehow, there didn't seem to be a real reason for me to go back to using Windows.
Ubuntu was very easy to use, almost hassle-free (at least much more than Windows had ever been), and I had started to like it.
So I just stuck with Linux, and Windows has since been converted to a gaming-only system :)
My friend is always at my disposal whenever I encounter a problem, and I also consult Linux-specific sites or forums on the Internet for that purpose frequently.
So, my transition to Linux happened more or less instantly and I am still by no means an expert, but I try to learn as much as I can.
It does take some time, though, and sometimes the best solution for a problem eludes me until after having gained more insight and knowledge somewhere else.
At the moment, I am trying out Linux from Scratch (LFS) because I feel that I still know too little about the inner workings of my Linux system.
LFS does not really count as a Linux distribution, but is rather a detailed step-by-step manual for building your own Linux system from scratch (hence the name) and learning which gears make which part of the system run.
Perhaps you might want to give this a shot, too?

A: You've already dipped your toes in the water for the last two years (which is an excellent and highly recommended preparatory step), so the best and easiest (and IMO the only) way to transition to using it full time is to just start using it full time.
With that much part-time use, you don't need more theory. You need more practice and you need to get into the habit of using it every day if that is your aim.
Dive in.  You'll learn soon enough whether it's going to work for you.

A: I would install a dual boot setup with Ubuntu or Mint, two of the friendly desktop Linux distros.  Then I would go through the excellent http://www.linuxfromscratch.org/ book online, where you build a Linux distribution from scratch, soup to nuts.  When you are finished with that, you will know Linux as well as anyone.

A: One approach I recommend that is a bit different to dual booting, and slightly more expensive, is to have 2 machines side-by-side, one with *nix, the other with Windows.
Part of the problem with dual-booting is you often have something going on one that you don't want to interrupt just to switch to another OS. While this may motivate you to find a solution in the OS you're currently in, it's still a nuisance.

Another possible approach is the VM solution (running one OS in a virtual machine). Pick whichever OS you want to become primary and set the other OS up as a VM inside that one. As long as you have the adequate resources to run a full VM, and you don't need the performance of a full machine, this works well.

If you're really up for a challenge, you can even set it up so you can run a partition on the disk as a VM, and dual-boot at the same time. So you could run the other OS as a VM, but also boot into it if necessary. It can be done (as I've done it), but it's not a trivial task.

For work, I will never be able to give up windows entirely. Unfortunately there are just some things that don't exist for *nix (such as the VMware vSphere client). I've used both the above solutions, but having 2 machines side by side is what I use every day. The windows machine mostly just sits off to the side running an Instant Messenger, but it's there if I need it.

A: If you want to learn the in and outs of the boot process and all the other Linux goodies, a distro like Gentoo or Slackware might be a good playground for you. Teaches you to build your own kernels and boot images and software as well.

A: Based on my own experience, I'd advice just plunging in to fully into *nix. Force yourself to learn and advance quickly. Just make sure you have a live internet connection you can use to ask questions and search for answers for problems others have had before. Doing this helps you improve really fast.
Try to challenge yourself to do some tasks that are easy with graphical interfaces with the command line. Continuous practice will soon make you a pro. You'll soon wonder how you ever used other operating systems when you learn just how simple most tasks are in linux and how, jusy like in programming, there are tons of ways to solve the same problem.
All the best!!


text:
Q: Getting the reference from $firebaseArray to make a new reference object Related to this question, I need to be able to get an element from a collection as a Firebase reference, ie given a $firebaseArray I need a $firebaseObject pointing to one of its elements. Unlike that example, I can't just hard-code a path the array and take a child from there because the location of the array will vary. And I can't use $firebaseArray.$getRecord() or the object provided by my ng-repeat followed by array.$save() because I may need to do a push() on this element.
So I settled on this reusable approach:
In a service:
function selectElement(array, element) {
  var obj = $firebaseObject(array.$ref().child(element.$id));
  return obj;
}

In the controller:
function onItemClicked(e) {
  vm.selected = dataservice.selectElement(vm.observations, e);
}

In the template:
<div class="list-item" ng-repeat="o in vm.observations" ng-click="vm.onItemClicked(o)">

The first line of selectElement produces an error: array.$ref(...).child is not a function at Object.selectElement
Here array has all the properties you'd expect, but logging array.$ref() shows this obfuscated object:
Y {k: Ji, path: P, n: Ce, pc: true}

That is what it looks like from the time the array is created. What's going on here and how do I use this reference? Is there another way to get a working Firebase object out of an array?


text:
Q: FileSystem API: Where are the files and folders located I'm currently developing a chrome app and need to access local files and directorys. My question is when I create a file or folder where are they located?
The extension is currently in my home directory and the created files aren't in the extension directory.

A: The file system API is "virtual" in that you cannot store the files entirely literally on the client's computer. You can only really access them via JavaScript.
Nevertheless, they are stored with different filenames in several directories (having non-intuitive names) in:
%appdata%\Local\Google\Chrome\User Data\Default\File System

Where %appdata% is e.g. C:\Users\xxx\AppData (on Vista).


text:
Q: Default save location when viewing a PDF from a web page via Internet Explorer When viewing a PDF from a web page via Internet Explorer, the default save location is the Desktop.
Where can I change the default save location?

A: Assuming you are using Adobe Reader, it appears there is no option to change the default location as it leaches off IE's default-save location (as its an add-on) or your last save location. Best you could do is change your IE default save location :(
http://blog.chron.com/helpline/2006/10/changing-the-default-save-location/
https://forums.adobe.com/thread/797451


text:
Q: WPF | Control Menu Checkbox (C#) I've created a controll menu in WPF. The button in that menu should activate the "Dark mode" that I've already created. Well that's just a simple Click event.
But I'd like to have a CheckBox not a simple Click event.
That's my code in XAML:
<DockPanel>
        <Menu DockPanel.Dock="Top">
            <MenuItem Header="_Settings">
                <MenuItem Header="_Darkmode" />
            </MenuItem>
        </Menu>
    </DockPanel>

The C# Code is inconsequential because that's just a sample.
Greetings from the US

A: Instead of using the Click event:
<Menu>
    <MenuItem Header="_Settings">
        <MenuItem Header="_Darkmode"
                  Click="OnDarkmodeClicked"/>
    </MenuItem>
</Menu>

You could use the Checked/Unchecked events after setting the IsCheckable property:
<Menu>
    <MenuItem Header="_Settings">
        <MenuItem Header="_Darkmode"
                  IsCheckable="True"
                  Checked="OnDarkmodeChecked"
                  Unchecked="OnDarkmodeUnchecked"/>
    </MenuItem>
</Menu>

Or you could bind IsChecked to a property in your model:
<Menu>
    <MenuItem Header="_Settings">
        <MenuItem Header="_Darkmode"
                  IsCheckable="True"
                  IsChecked="{Binding UseDarkmode}"/>
    </MenuItem>
</Menu>

A: This may not be the best solution, but you could store a boolean elsewhere, and have a menuitem that looks like this:
XAML code
<MenuItem Header="_Blur Background" IsCheckable="True" IsChecked="True" Click="BlurOnOff_Click" InputGestureText="Ctrl+B"></MenuItem>

Then C# code
private void BlurOnOff_Click(object sender, RoutedEventArgs e)
    {
        blurOn = blurOn ? false : true;
    }

The Blur On/Off is just an example. When the function is called, it updates the boolean to be the opposite of what it was before.


text:
Q: Trim strings of ServiceStack model Is there a way to "automatically" trim strings of a ServiceStack model based on [StringLength()] attribute before it insert/update them in the DB?
I'm getting an error because the strings I'm trying to import from an external service are too long and my model is pretty big and have different string lengths... it would be expensive in terms of time trimming each string type in it manually.

A: You can trim string properties using OrmLite's String Filter:
OrmLiteConfig.StringFilter = s => s.TrimEnd();

db.Insert(new Poco { Name = "Value with trailing   " });
db.Select<Poco>().First().Name // "Value with trailing"


text:
Q: Use a remote JMS queue with Spring and JBoss EAP 6.2 Is it possible (if yes, with what configuration?) to have a Spring application running on one JBoss instance connect to a JMS queue defined on a different JBoss instance? I read a few pages about how to do it programmatically, but is it possible to have the queue injected in the Spring app so the application is not aware of the remote location of the queue and not required to do an explicit lookup?
Ideally, to have the JNDI name of the queue being resolved to a remote queue by the "client JBoss". An acceptable option would be to have the client application define the queue as  remote in the <jms:listener> configuration.
Software: JBoss EAP 6.2, Spring 3.x

A: Yes you can use remoting NettyConnectionFactory
<bean name="liveTransportConfiguration" class="org.hornetq.api.core.TransportConfiguration">
        <constructor-arg value="org.hornetq.core.remoting.impl.netty.NettyConnectorFactory" />
        <constructor-arg>
            <map key-type="java.lang.String" value-type="java.lang.Object">
                <entry key="port" value="5445"></entry>
                <entry key="host" value="ip of server"></entry>
            </map>
        </constructor-arg>
</bean>

<bean name="connectionFactory" class="com.kp.KPHornetQJMSConnectionFactory"
        destroy-method="close">
        <constructor-arg name="ha" type="boolean" value="false" />
        <constructor-arg>
            <array>
                <ref bean="liveTransportConfiguration"></ref>
            </array>
        </constructor-arg>

        <property name="clientFailureCheckPeriod" value="5000" />
        <property name="retryInterval" value="1000" />
        <property name="retryIntervalMultiplier" value="1.0" />
        <property name="reconnectAttempts" value="-1" />
        <property name="confirmationWindowSize" value="-1" />
</bean>

<bean name="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"></property>
</bean>

<bean name="kpListener" class="Your jms MessageListener">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
</bean>

<jms:listener-container connection-factory="connectionFactory" concurrency="1">
        <jms:listener destination="myqueue" ref="kpListener" method="onMessage" />
</jms:listener-container>

KPHornetQJMSConnectionFactory.java class
public class KPHornetQJMSConnectionFactory extends HornetQJMSConnectionFactory {

    private static final long serialVersionUID = -712113311282964108L;

    public KPHornetQJMSConnectionFactory(final boolean ha,
            org.hornetq.api.core.TransportConfiguration transportConfiguration) {
        super(ha, transportConfiguration);
        super.setUseGlobalPools(false);
    }

}


text:
Q: Fearing rejection from others and hence hesitant about it Is there a term for the situation when we falter about making a suggestion or flinch from giving an answer or hesitating to take an action fearing ridicule of others or their rejection?
Is there a sort of a phobia for it, maybe?

A: This is a symptom of Kakarrhaphiophobia, the fear of being rejected.
This is a fantastic word...........perfect for a spelling bee!

A: Atychiphobia aka Kakarrhaphiophobia

A person afflicted with atychiphobia considers the possibility of failure so intense that they choose not to take the risk. Often this person will subconsciously undermine their own efforts so that they no longer have to continue to try.[4] Because effort is proportionate to the achievement of personal goals and fulfillment, this unwillingness to try that arises from the perceived inequality between the possibilities of success and failure holds the atychiphobic back from a life of meaning and the realization of potential.

A: I can also add:
Gelotophobia: Fear of being ridiculed/laughed at.

A: Do you mean "insecure?"

insecure: subject to fears, etc., not self-confident or assured.

A: How about:

*

*shy: being reserved or having or showing nervousness or timidity in the company of other people.

*hesitant: tentative, unsure, or slow in acting or speaking.

*apprehensive: anxious or fearful that something bad or unpleasant will happen.

A: Costive: 2. slow in action or in expressing ideas, opinions, etc.


text:
Q: How to Schedule Task using Marklogic These are following areas where Scheduling Task Using Marklogic can be used
1.Loading content. For example, periodically checking for new content from an   external data source, such as a web site, web service, etc.
2.Synchronizing content. For example, when MarkLogic is used as a metadata repository, you might want to periodically check for changed data.
3.Delivering batches of content: For example, initiate an RSS feed, hourly or daily.
4.Delivering aggregated alerts, either hourly or daily.
5.Delivering reports, either daily, weekly, or monthly.
6.Polling for the completion of an asynchronous process, such as the creation of a PDF file
My requirement is to schedule a task for bulk loading data from local file system to Marklogic DB using any data loading option available in Marklogic such as
1.MLCP
2.Xquery
3.Rest API
4.Java API
5.WebDAV.
So is there any option to execute this programatically. I prefer MLCP since I need to perform bulk load of data from local file system

A: Similar to your question at Execute MLCP Content Load Command as a schedule task in Marklogic , I would start with a tool like Apache Camel. There are other options - Mule, Spring Integration, and plenty of commercial/graphical ETL tools - but I've found Camel to be very easy to get started with, and you can utilize the mlcp Camel component at https://github.com/rjrudin/ml-camel-mlcp .


text:
Q: How to change coordinates in Google map API in Bootstrap template theme? I have tried, but without any luck.
Bootstrap provides this really awesome theme called Stylish Portfolio (http://startbootstrap.com/stylish-portfolio) which comes with a cool Google-map location.
This is a fairly standard thing nowadays. However, I need to change the location of the map to match Copenhagen in Denmark.
I've tried to look up other ressources/help/support from the template creators, bot cant seem to find anything on the map coordinates - which is why I'm here at SO now.
I've been looking through the html, and this seems to be the code for the map?

Clearly, it's not just a simple google-maps link/coordinates - can somebody help explaining to me, what I'm actually looking at here?
Thanks in advance

A: The solution to your problem is quite easy...
Follow these steps:

*

*Go to https://developers.google.com/maps/documentation/embed/start

*Search for business or place (where it says "Highlight a place or an address") then click "Looks Good!".

*Enter your API key, if you dont have an API key follow the istractions bellow and create one (API key), if you have an API key skip steps 3.1, 3.1.1, 3.1.2., 3.1.3., 3.1.4.,

3.1 Creating the API key
3.1.1. Visit the APIs Console at https://code.google.com/apis/console and log in with your Google Account.
3.1.2.Click the Services link from the left-hand menu.
3.1.3.Activate the Google Maps Embed API service.
3.1.4.Click the API Access link from the left-hand menu. Your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.
Your API key looks something like this: AIzaSyCwI3k7JC29_KzlX1S_bC8fARpocLX5bRY

*After you ender your API key click "DONE"

*Copy And Paste the code you'll get to your templates index.html and you're done.

*Change the height and width to 100% (where is says

That's all!


text:
Q: pandas cannot conver to datetime object I have a csv file where the a timestamp column is coming with values in the following format: 2022-05-12T07:09:33.727-07:00
When I try something like:
df['timestamp'] = pd.to_datetime(df['timestamp'])

It seems to fail silently as the dtype of that column is still object. I am wondering how I can parse such a value.
Also, what is the strategy so that it remains robust to a variety of input time formats?


text:
Q: Font y tamaño de letra en C# **Buenas, tengo una pregunta, ¿Cómo puedo ver el tamaño de la fuente en el diseño del formulario? Actualmente, uso esto para aumentar el tamaño:
        using (Font font = new Font("Arial", 15.0f))
        {
            label1.Font = font;
            label2.Font = font;
        }

Pero, esto solo funciona en tiempo de ejecución:

En el diseño no:

¿Alguno sabe como puedo hacer que se vea en diseño?

A: La fuente del formulario y de cualquier elemento dentro de el, la puedes cambiar en la ventana de propiedades como te muestro en la siguiente imagen.


text:
Q: Numpy mean for big array dataset using For loop Python I have big dataset in array form and its arranged like this:
Rainfal amount arranged in array form
Average or mean mean for each latitude and longitude at axis=0 is computed using this method declaration:
Lat=data[:,0]

Lon=data[:,1]

rain1=data[:,2]

rain2=data[:,3]

--

rain44=data[:,44]

rainT=[rain1,rain2,rain3,rain4,....rain44]

mean=np.mean(rainT)

The result was aweseome but requires time computation and I look forward to use For Loop to ease the calculation. As for the moment the script that I used is like this:
mean=[]

lat=data[:,0]

lon=data[:,1]

for x in range(2,46):

    rainT=data[:,x]

mean=np.mean(rainT,axis=0)

print mean

But weird result is appeared. Anyone?

A: First, you probably meant to make the for loop add the subarrays rather than keep replacing rainT with other slices of the subarray. Only the last assignment matters, so the code averages that one subarray rainT=data[:,45], also it doesn't have the correct number of original elements to divide by to compute an average. Both of these mistakes contribute to the weird result.
Second, numpy should be able to average elements faster than a Python for loop can do it since that's just the kind of thing that numpy is designed to do in optimized native code.
Third, your original code copies a bunch of subarrays into a Python List, then asks numpy to average that. You should get much faster results by asking numpy to sum the relevant subarray without making a copy, something like this:
rainT = data[:,2:] # this gets a view onto data[], not a copy
mean = np.mean(rainT)

That computes an average over all the rainfall values, like your original code.
If you want an average for each latitude or some such, you'll need to do it differently. You can average over an array axis, but latitude and longitude aren't axes in your data[].

A: Thanks friends, you are giving me such aspiration. Here is the working script ideas by @Jerry101 just now but I decided NOT to apply Python Loop. New declaration would be like this:
lat1=data[:,0]
lon1=data[:,1]
rainT=data[:,2:46] ---THIS IS THE STEP THAT I AM MISSING EARLIER
mean=np.mean(rainT,axis=1)*24 - MAKE AVERAGE DAILY RAINFALL BY EACH LAT AND LON
mean2=np.array([lat1,lon1,mean])
mean2=mean2.T
np.savetxt('average-daily-rainfall.dat2',mean2,fmt='%9.3f')
And finally the result is exactly same to program made in Fortran.


text:
Q: Rails, Heroku, Paperclip and the uploading of files to S3 I'm working on an app that will let users submit zip files that are about ~5mb in size I imagine. I will then take these files manually and work with them on my end.
I'm looking into using Paperclip as heroku suggests for this task - bypassing heroku entirely - and just uploading to Amazon S3.
However now that I'm messing with it it looks like a user model can have ONE attachment, rather than multiple. Is there a better alternative or perhaps a direct way to just upload to S3 knowing my bucket name and keys and such?
Or is there a way to configure paperclip such that a user can have many attachments? I'm a bit confused what I'm doing.

A: You can find many available tutorials to setup paperclip working with multiple attachments.

A: Paperclip supports an unlimited number of attachments.
Look into the S3 POST API, which will require some signature paramaters generated on your server, but will allow you to upload directly to S3. After a successful upload to S3, you have to make a separate request to notify your heroku server that there is a new attachment and of the attachment filename. Generally this requires hacking the [attachment]_file_name parameter in order to avoid paperclip unnecessarily uploading the file a second time.
Overall I find Paperclip to have some serious design flaws which means it requires unfortunate hacking in order to play nicely with files that are not uploaded through the plugin. I've had to pretty much hack the thing completely. For my next project I'll look for an alternative that more cleanly separates attachements from models and has a more modular storage mechanism.
That said, the solution I mentioned works nicely. The tricky part is to explicitly set the [attachment]_file_name field on the model so that Paperclip will think the file has original file has already been stored.

A: On popular alternative to  paperclip is CarrierWave. When I was looking into file attachments a few months ago it was highly recommended.

A: S3 Post API can be used but this is going to reveal your secret key in forms which is quite vulnerable from security perspective.
you should use direct uploaderm to s3 js library so your secret key remains secret.
Thanks


text:
Q: How to divide a list into more lists in a generated admin backend? I am pretty new in symfony. I am using symfony 1.4 and I already set up my backend for my project saving some articles.
However, In my article edit view, I have a list, with a many to many relationship to the article filters. I have an enumeration in the filters table, to give the filters 3 types. (there will be only 3, that's why I didnt created 3 Filters tables)
Here my doctrine schema, so you can imagine it.
    detect_relations: true
      Article:
        columns:
          article_no:          { type: string(50), notnull: true }
          producer:            { type: string(100) }
          name:                { type: string(255), notnull: true }
          description:         { type: string(2000) }
        attributes:
          export: all
          validate: true

    Filter:
      columns:
        name:  { type: string(255) }
        type:  { type: enum, values: ['Type1', 'Type2', 'Type3']}
      relations:
        Article:
          foreignAlias: Filters
          class: Article
          refClass: FilterArticle

    FilterArticle:
      columns:
        filter_id: { type: integer, primary: true }
        article_id: { type: integer, primary: true }
      relations:
        Filter: { foreignAlias: FilterArticle }
        Article: { foreignAlias: FilterArticle }

So in my Edit View, I have a big list with the filters.
But I want to divide this list into these 3 different types and display 3 lists.
Is this possible ? How can i realize that ? I suppose I need to overwrite the ArticleForm or FilterForm ?! Or can I do it only configuring the generator?
THank you all for the help, I can only say I love symfony :)
greetings

A: From what I can see here is, that you want to change the way the list view is rendered.
i assume that you have already created your admin auto-generated module.
if you go to your appropriate cache dir for your environment and go to templates, you should find a _list.php file, this partial holds the table display html/php and you should see the logic that iterates through the results, eg:
foreach ($pager->getResults()...

copy this _list.php to your auto generated module's templates dir..
here you can custom edit this file to override how the list view is rendered and add extra logic to distinguish how your 3 lists render...


text:
Q: Event Listener not working correctly Im trying to register a onClick event Listener to every dynamically created img element. When im trying to pass argument to the eventHandler function , the event gets fired or the handler function gets called when page loads and it does not work after that but it works fine when i don't pass argument to the event handler function
request.onreadystatechange = function() {
            try {
                if (this.response.contentlength != 0) {
                    var urlCreator = window.URL || window.webkitURL;
                    var imageUrl = urlCreator
                            .createObjectURL(this.response);
                    var elem = document.createElement("img");
                    elem.setAttribute("style","width:100%");
                    elem.setAttribute("src", imageUrl);
                    elem.addEventListener("click",on);
                // here elem.addEventListener("click",on(elem));
                    parent.appendChild(elem);
                }
            } catch (Exception) {
            }
        };
        request.send();
    }

    //for overlay effect
    //function on(ele){
    function on(){
        document.getElementById("overlay").style.display="block";
    }

A:

request.onreadystatechange = function() {
            try {
                if (this.response.contentlength != 0) {
                    var urlCreator = window.URL ||        window.webkitURL;
                    var imageUrl = urlCreator
                            .createObjectURL(this.response);
                    var elem = document.createElement("img");
                    elem.setAttribute("style","width:100%");
                    elem.setAttribute("src", imageUrl);
                    //
                    elem.addEventListener("click",on);
                // here elem.addEventListener("click",on(elem));
                    parent.appendChild(elem);
                }
            } catch (Exception) {
            }
        };
        request.send();
    }

    //for overlay effect
    //function on(ele){
    // the listener function always takes event as first parameter and event has the information about from which element this listener is called
    function on(evt){
        var targ = evt.target || evt.srcElement;
        document.getElementById("overlay").style.display="block";
    }

A: // Alternately, if you want to pass arguments.. please refer the below code

request.onreadystatechange = function() {
            try {
                if (this.response.contentlength != 0) {
                    var urlCreator = window.URL ||        window.webkitURL;
                    var imageUrl = urlCreator
                            .createObjectURL(this.response);
                    var elem = document.createElement("img");
                    elem.setAttribute("style","width:100%");
                    elem.setAttribute("src", imageUrl);
                    // here you should pass your arguments.. you cannot directly call the listener funciton. It always has to be wrapped with anonymous function.
                    var yourdata = "xxxx";

                    elem.addEventListener("click", function(){on(yourdata)});
                // here elem.addEventListener("click",on(elem));
                    parent.appendChild(elem);
                }
            } catch (Exception) {
            }
        };
        request.send();
    }

    //for overlay effect
    //function on(ele){
    // the listener function always takes event as first parameter and event has the information about from which element this listener is called
    function on(evt, data){
        var targ = evt.target || evt.srcElement;
        document.getElementById("overlay").style.display="block";
    }


text:
Q: AngularJS ChartJS - Multiline with diff no. of data points for each line I'm using angular-chart.js which is extension on chart.js in my page to create multiline chart.
In my multiline chart, each line may have different set of data points. For example, the chart has 2 lines A & B. Then x-axis labels would be of fixed # like months - Jan to March. The line A can have data points for month Jan & Feb and line B can have data points for Jan & March.  I'm not able to make it work using angularjs but according to this, it is possible using chartjs.
Example Code:
Plnkr Link
<body ng-app="DashboardApp">
<div ng-controller="MultiLineChartCtrl">
  <canvas class="chart chart-line" chart-data="data" chart-labels="labels" chart-series="series" chart-options="options" chart-dataset-override="datasetOverride" chart-click="onClick" height="250px"></canvas>
</div>

var dbapp = angular.module('DashboardApp', ['chart.js']);

dbapp.controller('MultiLineChartCtrl', ['$scope',
function($scope) {

$scope.labels = ["January", "February", "March", "April"];
$scope.series = ['Person A', 'Person B'];
$scope.data = [];
$scope.data.push({
  labels: ["January", "February", "March"],
  data: [4.43, 6.27, 6.74]
});
$scope.data.push({
  labels: ["January", "March", "April"],
  data: [6.43, 5.27, 7.74]
});

$scope.options = {
  limitLines: [{
    label: 'Target',
    value: 1,
    color: 'rgba(255, 0, 0, .9)'
  }],
  steppedLine: true,
  showLines: true,
  elements: {
    line: {
      fill: false,
    }
  },
  scales: {
    xAxes: [{
      display: true,
      scaleLabel: {
        show: true,
        labelString: 'Month'
      }
    }],
    yAxes: [{
      display: true,
      scaleLabel: {
        show: true,
        labelString: 'Value'
      },
      ticks: {
        suggestedMin: 0,
        beginAtZero: true
      }
    }]
  },
  legend: {
    display: true,
    position: 'top',
    fill: false
  }
};
$scope.$on('create', function(event, chart) {
  var legend = chart.generateLegend();
  console.log(legend);
});

 }
]);


text:
Q: Create always on top notification on Chrome on Android Is there a way to implement this (see picture) as a normal Human or is this a feature that can only be used by google/chrome?
Steps to reproduce:
When there is a running WM Game type "WM" in google and there is the option to pin a specific game. The Notification then stays on top until you delete it. Even out of chrome. And it updates when the game progresses.
Is there a way to implement this in a normal website?


text:
Q: How to prevent developers from committing into certain folders of git repository How to prevent developers from committing into certain folders of git repository which they don't own. Is there a way to prevent this using permissions on gitlab, since we want to enforce that certain folders (say folderA, folderB) are writable but folderC only is viewable.

A: This is possible on GitLab through the Code owners feature: https://docs.gitlab.com/ee/user/project/code_owners.html
Take into account that this is a premium feature.


text:
Q: Routing problem that load my view with only text and url does'nt change I'm fairly new to the Laravel. I implemented AUTH in laravel with 3 roles.
I've HomeController with index function where I'm checking for what is the  role of the logged in user and depending upon the role I want to load the view. I'm not able to get how do I change the route name from /home to /superadmin.
When I load view it only shows me text but the route is still /home. I know it must have been answered somewhere but nothing is working for me right now.
I've tried this
  Redirect::to('superadmin.page1')->with($data);
            return view('superadmin.page1')->with($data);
            return redirect()->route('superadmin');
            return view('superadmin.page1');

HomeController.php
//main code
try
        {
            if(count($data) < 0)
            {
                return view('user.page1')->with($data);
            }
            else
            {
                //super admin ko pehle check karo , then admin , then user
                $role_array = array();
                foreach ($data as $key => $value) {
                        $role = $value->role_name;
                        array_push($role_array , $role);
                }

           if (in_array("ROLE_SUPERADMIN", $role_array))
           {
            return view('superadmin.page1')->with($data);
           }
           else if (in_array("ROLE_ADMIN", $role_array))
           {
            return view('admin.page1')->with($data);
           }
           else
           {
            // undefined role found, therefore user
            return view('user.page1')->with($data);
           }
        }
    }

==========
My route
Auth::routes();

Route::get('/home', 'HomeController@index');

Route::get('/superadmin', 'SuperAdminController@index');

Route::get('/superadminPage1', 'SuperAdminController@page1');

I'm getting this as output
@extends('layouts.app') @section('content')
SuperAdmin Page1
@if (session('status'))
{{ session('status') }}
@endif This is SuperAdmin PAGE1. You must be privileged to be here !
@endsection


text:
Q: bind dig no answer for www I'm trying to set up a domain.  It works for vumila.com, but not with www.vumila.com.  Here are my files:
db.vumila.com:
$TTL    3h
@       IN      SOA     ns1.vumila.com. admin.vumila.com. (
                          3        ; Serial
                          3h       ; Refresh after 3 hours
                          1h       ; Retry after 1 hour
                          1w       ; Expire after 1 week
                          1h )     ; Negative caching TTL of 1 day
;
@       IN      NS      ns1.vumila.com.
@       IN      NS      ns2.vumila.com.

vumila.com.    IN      MX      10      mail.vumila.com.
vumila.com.    IN      A       216.172.176.81
ns1                     IN      A       216.172.176.82
ns2                     IN      A       216.172.176.81
www.vumila.com.                     IN      CNAME       vumila.com.
mail                    IN      A       216.172.176.82
ftp                     IN      CNAME   vumila.com.

db.216.172.176
;
; BIND reverse data file for 176.172.216.in-addr.arpa
;
$TTL    604800
176.172.216.in-addr.arpa.      IN      SOA     ns1.vumila.com. admin.vumila.com. (
                          3         ; Serial
                          3h       ; Refresh after 3 hours
                          1h       ; Retry after 1 hour
                          1w       ; Expire after 1 week
                          1h )     ; Negative caching TTL of 1 day
;
176.172.216.in-addr.arpa.       IN      NS      ns1.vumila.com.
176.172.216.in-addr.arpa.       IN      NS      ns2.vumila.com.

82.176.172.216.in-addr.arpa.   IN      PTR     vumila.com.

when i dig www.vumila.com i got this:
; <<>> DiG 9.9.5-3ubuntu0.1-Ubuntu <<>> www.vumila.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 8352
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;www.vumila.com.            IN  A

;; AUTHORITY SECTION:
vumila.com.     505 IN  SOA ns1.launchpad.com. anb.hotmail.com. 2014122502 7200 7200 172800 38400

;; Query time: 45 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Thu Jan 15 18:48:19 CST 2015
;; MSG SIZE  rcvd: 111

any help please

A: You have a problem with your serial number.
In your live DNS zone the serial number is 2014122502. But in your new zone it is 3. Serial numbers can only be incremented; a serial number lower than the previous one will be ignored, along with all the records in the zone.
Whenever you change one or more records in the zone, always change the serial number to a number larger than the previous one.
It is a common convention to use the date of the change along with some extra digits as the serial number, and this seems to be what was done previously:
2014 Year
12   Month
25   Day
02   The second of two changes made this day

By this convention, you can change the serial to 2015011601 and if you always follow it, the serial will always be larger than it was previously.


text:
Q: Spring Boot controller test with TestRestTemplate always fails with endpoints returning 404 I am trying to create a test of a Spring Boot controller using TestRestTemplate. It is a requirement that only what is absolutely required for the controller be included in the test context, so spinning up the entire application context for the test is not an option.
Currently the test fails due to the endpoint returning 404. The endpoint works correctly in production. It appears that the controller is not being registered with the web servlet.
The controller appears as follows:
@RestController
class MyController {
    @GetMapping("/endpoint")
    fun endpoint(): ResponseDto {
        return ResponseDto(data = "Some data")
    }
}

data class ResponseDto(val data: String)

The test is as follows:
@SpringBootTest(
    classes = [MyController::class, ServletWebServerFactoryAutoConfiguration::class],
    webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
internal class MyControllerTestRestTemplateTest(
    @Autowired private val restTemplate: TestRestTemplate
) {
    @Test
    fun `should work`() {
        val result = restTemplate.getForEntity("/endpoint", String::class.java)

        result.body.shouldMatchJson(
            """
                {
                    "data": "Some data"
                }
            """)
    }
}

How can I get this test setup to work?

A:
It is a requirement that only what is absolutely required for the controller be included in the test context,...

SpringBoot has a tooling for that already - see @WebMvcTest slice documentation or this SO answer.

A: As your requirement states:

It is a requirement that only what is absolutely required for the
  controller be included in the test context, so spinning up the entire
  application context for the test is not an option.

You should consider testing just the web layer using @WebMvcTest. With your current @SpringBootTest and the random port, you are booting the whole Spring Context and start also the embedded Tomcat. With @WebMvcTest you can inject a MockMvc instance and write assertions on the response body/header/status.
A Java example may look like this
@WebMvcTest(MyController.class)
class MyControllerTests {

    @Autowired
    private MockMvc mvc;

    @Test
    void testExample() throws Exception {
        this.mvc.perform(get("/endpoint")
                .accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string("YOUR_STRING_HERE"));
    }
}

And a working Kotlin example looks like the following
@WebMvcTest(MyController::class)
internal class MyControllerTests(@Autowired private val mockMvc: MockMvc) {

  @Test
  fun testExample() {
    this.mockMvc.perform(MockMvcRequestBuilders.get("/endpoint")
      .accept(MediaType.APPLICATION_JSON))
      .andExpect(status().isOk)
      .andExpect(content().json("""
        {
         "data": "Some data"
        }
      """.trimIndent()))
  }
}

A: The answers by rieckpil and Josef are both true and I agree that using @WebMvcTest is a better approach.
If you insist on keep using @SpringBootTest and TestRestTemplate: You are using webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT. This means your TestRestTemplate doesn't know what port to use. You need to include the entire url including the port the application is running on in the string url
By adding
@LocalServerPort
int randomServerPort = 0

And then providing the complete url
val result = restTemplate.getForEntity("http://localhost:${randomServerPort}/endpoint", String::class.java)


text:
Q: Shell Script Loop over files to exit when SQL query fails We have a shell script that runs to stop if one of any .pl files fails.  We want to do the same with the SQL files if they exist.  The difference is we don't always have an SQL file at that point in the loop.  So we do not always have a file_num.sql.  What we want to do is if it exist and fails, then exit the script below.  The way we have this structured is running this out of the do_updates files as such:
my $sqlFile = $updatesdir.'/releaseupdates_02.sql';
system("$drushcmd -r $drupalroot -u site.test.admin sql-query --file=$sqlFile") == 0 or die "$drushcmd failed: $?";

So below in our master loop, we want to exit the loop if a perl script containing an SQL command fails.  So let's say there is a perl script that calls a php file for 3 and 4 and if that errors out, this works, however, if an SQL file exists for 02 instead of a php file, this does not work.
# Declare a list of update script file numbers
FILE_NUMS="
  01
  02
  03
  04
"
# Run each update script
for file_num in $FILE_NUMS; do
  ${RELEASEDIR}/do_updates_$file_num.pl
  # Exit if an update script returns and exit status of anything other than zero
  if [ $? -ne 0 ]; then
    exit $?
  fi
done

A: Your exit $? doesn't get the same exit code as the previous line. You can simplify this as follows:
${RELEASEDIR}/do_updates_$file_num.pl || exit $?

Even better, write robust shell scripts by adding set -o errexit to exit the script at the first error (but beware caveats).