text:
Q: Should software engineers also act as tech support? Should a software engineer also act as technical support? That is, should a company allow their engineers to wear both the software engineer and technical support hats. It seems that it would remove the ability to write software if much of an engineer's time is taken up by technical support.

A: It depends on the company.
My job is exactly like this. I'm a software developer, but since we're a fairly small company, each developer takes on an "unofficial" support role usually based around their own software. Some developers have to do more support than others, depending on a number of factors such as how many products they have developed/shipped, how buggy their products are, and how effective they are at support. If you can provide the customer with exactly what they need to solve the problem, they will keep coming back to you to get issues resolved as quickly as possible. Double edged sword? Yes. You suffer from reduced productivity, but the customer is happy, and more likely to remain a customer. This is important for smaller companies.
We do have a systems support team, but because of the nature of what we do, they mostly have to deal with hardware related issues. Personally, in a smaller company, this issue isn't as disruptive as one might imagine. Sure, you get calls while you're trying to work out some important feature, but at the same time, the customer service is much improved; they can have an authoritative voice that knows (in many cases) how to solve their problem instead of someone with second-hand information and a support script. If you can't solve the problem there and then, can reassure them personally that you will implement a fix for their bug, or consider their feature request for a future release. You can get real feedback straight from the users of your software, so your next version can be even better than you already think it is.
I like to think that happy customers create a more positive image of your company, which usually leads to more customers. And that's why, as a software engineer, I like tech support.

A: This is a classic issue in companies that have a software development component in their work, whether they are software companies or not. I struggle with this all the time.
Having Developers involved in Production Support
Pros

*

*Fights "Development in a vacuum" syndrome. It's valuable to gain exposure to how users use the app. Until I finally saw this as a young developer, I didn't realize what a crappy UI developer I was. All I cared about was coding and not design, analysis or the user's perspective.

*Developers that are not as good as they think they are can be humbled (although there's no guarantee you'll get this benefit; some devs are truly oblivious, selfish, and stubborn).

*Developers will gain domain knowledge. This is critical if your developers are to eventually become better at identifying and filling in the gaps the business analysis phase (assuming there is any) misses.

*Good support is a marketing point. If you do it well, clients will come to appreciate it. And a well-rounded developer with communication skills and domain knowledge is capable of doing this well. However, I would still prefer that applications be of high enough quality that they don't need support. Superior quality is its own form of customer support (and also a marketing point).

Cons

*

*Interruption factor. This is the number one fault of mixing project work and support work, bar none. Projects interfere with support, and support interferes with projects. Projects depend on estimates and milestone progress, support is unpredictable and can involve impromptu urgency. Projects are schedule-based, support is interruption-based. Not a happy combination, and very frustrating for developers to deal with.

*Not everyone is good at support. Someone that's less experienced with the app or business, or someone whose personality or communication skills are such that they are better shielded from user access might not work well in support.

*Inefficient use of resources. Frank Shearar noted in the comments that a developer doing trivial support can be more expensive than a level one support tech.

In my experience, most developers don't like support. Having served on both the project and support sides, I can sympathize. When having to do both at the same time, the mitigating factor is often overtime, usually unpaid, to deal with support emergencies and still make project deadlines. Project managers love unpaid overtime because it means making dates without costing more money, but for the devs, it's just a big bowl of suck.
However, I also believe that if developers did a better job creating reliable and intuitive systems, you'd have less support. So this creates a weird circular argument for mixing the two. What I think you should do if you have to do both is find ways to avoid making it simultaneous.

A: There is nothing more frustrating than computer tech support not willing to hook you up with someone who really understands what's going on.  I would hope that any large application company would have some programmers who would work tech support.

A: Developers should be the last line of support.
Only when the helpdesk and our QA department cannot help a customer will we be hassled. And even then it has to go through our prioritized bug tracking system.
If it's a really big problem we'll hear it.

A: I would only do this if it is a new developer or one who isn't familiar with the domain and customer base. Making it a permanent thing is not a good idea.

A: My last job was exactly this. We supported existing systems and also wrote new ones as needed. It was a total disaster. I would constantly be interrupted. My morale was so low because projects started would take forever to finish. Also, we had to carry around a pager for off hours support without extra pay (this was in the health care field). I think the solution (which I suggested to my manager at the time), would have been to have a front line of technical support, and if it's a software bug then forward it along to the developers. Needless to say I only lasted a year and a half until I finally left for a better all development job!

A: Emphatically, no.
We all know how difficult it can be to have to stop what you are doing to ask answer a question. I do answer phones for a help desk and I write some utility applications.
I cannot focus on solving a problem because every 5 minutes I'm having to pick up the phone. Neither job gets done as well as it can be because I constantly am thinking about what I can do to solve a problem, and I'm never working on the programming long enough to fully implement any solution I might have.
Again, I could not stress enough how important it is to be able to focus on one aspect or the other.

A: There are talents and skills you need to develop software, and talents and skills you need to be effective on first-line support.  I don't know that these talents have any correlation.
This means that either you have to hire developers based partly on their ability to do phone support, or you let your customers directly talk to people who aren't good at handling customers and don't want to be doing it in the first place.  This may or may not be better than having them talk to a guy with a thick Indian accent who reads from a polite script.
Also, when you make the job unpleasant (and I don't know any developers who actually enjoy first-line support), some of your developers will leave.  These are generally the ones who can get other jobs more easily:  i.e., the good ones.  As this process goes on, you wind up with a shop filled with less talented people, making it even less pleasant for the competent to stay past the first job offer from somebody else.
As far as getting serious development done, forget it if there's frequent interruptions.  My wife has complained a lot about being expected to do development and support users simultaneously.

A: I think that developers already wear two hats. Support is more like a filter used to shield development from trivial issues such not having the computer plugged in. However, there should be tight coupling between development and support. Some customers have legitimate issues that maybe the result of a bug. It should be the responsibility of development to help get these issues sorted out as soon as possible. So in a sense developers are already part of the support team...call it tier 2 support.

A: I would never put a developer as first line support.  The number of interruptions and the amount you will have to repeat yourself will drive most developers to shout RTFM and hang up on the next person who calls.  This is not something your clients need, nor is this something you want your developers to have to endure.
There is a certain rule in any customer service position.  To an irate caller, the first person who answers the phone is wrong.  Whether they have the president of the company, the person who developed the app, or the support manager, it doesn't matter.  Once the client gets the second person, who may or may not know what they are doing, the client will be able to calm down and explain the problem more clearly.
This is not an environment you want to retain good developers.  Is there value in having a developer interact with a client on a particularly difficult problem that goes beyond "why doesn't my cup holder work anymore"?  Absolutely.  But that's after the support request has been vetted through the first and second tier support lines.

A: Some of the time, definitely yes. Facing the customer often gives a perspective that most people, especially programmers, lack. How the user actually uses the product, or actually thinks is often far removed from how the builder (the engineer) thinks s/he does.
It should be for short periodic stints, so as not to interrupt the actual task of development.

A: I think a lot of it depends on the company.  Your typical BigCo firm can usually afford to have support people to insulate the developers.  On the other hand, a startup with three people total simply may not have the resources to provide separate support people.
I think the best general strategy (irrespective of company size or resources) is to use support teams to troubleshoot the low hanging fruit and the most common problems ("Have you tried turning it off and on?").  The engineers should work with the customers on the more tricky problems that require knowledge of how the system works along with more developer-oriented support (APIs, developer tools, etc.).  You could have the support person act as a "liaison", but I find that's usually more trouble than it's worth.

A: While I don't think it's appropriate to use devs as support all the time, I think there is something to be said for having a dev do the initial support of an application. This should specifically include the after hours support.  I also think in can be useful to have them be scheduled in to the after hours support for their apps on a regular basis.
There is nothing like multiple 3AM calls to make you realize what effect certain design decisions and/or shortcuts have on the ability for people to support and maintain your code.

A: Ideally no for the reasons sited above, but yes while the project is nascent, because developers can provide quick resolutions, often expected by business, which lends support to the continuing improvement of the software. I value developers that provide support smartly: those that lend their analytical skills by example to a more formal full-time support team, and those that answer the business in such a way to show a spirit of service and cooperation. Keys to this success though include management recognizing and formalizing first and second level support to quickly offload developers from what should only be their short-term role. Developers who show a knack for both development and support should be cultivated as third-level support, or support for the support folks. So should is time dependent, talent and desire dependent, and effectively managed.
My own interest has been to answer the tough support questions, and to take what I've learned from the experience to reduce the need for support overall, which benefits end-users and primary support alike.

A: Cons - assuming you have to deal directly with customers.
1) Spoiling Your Customers
If it is first/2nd/3rd line support (i really mean blurred line support) where developers deal directly with customers, then it is a big con. Developers have the skill set required to debug problems or develop solutions to solve problems. If customers have complete access to developers (blurred line) - there's no stopping customers from "abusing" this privilege - resulting in spoiled, demanding and privileged customers that are paying no more than any other customer.
2) Conditioning Your Developers to Lie and Make Up Stories.
Anyone who has dealt with customers know that it is a pre-requisite to be able to lie to them. There is a bug with a 1 line fix that can be done in 5 minutes. A customer support person would have been trained to manage customer's expectations - that it would take up to 3 days to get it resolved.
As a developer, if you have to deal directly with customers, you have to think of creative ways to appease or deceive customers when your primary job should be to solve technical problems and make sure the system is running smoothly.
3) Your Curriculum Vitae Suffers.
Unless you're making a switch from Software Engineer to Business Analyst / IT Consultant / Project Management, your CV is going to suffer from a technical aspect.
Paid support work that rotates among the team is a different story.
Pros
1) Stop Whiners from Whining
Developers who do what they hate will make them appreciate coding a whole lot more. Have a programmer who is constantly whinging? Put them on the hotline for a month.

A: Yes of cause they do. I lol'd when I read this question? I was like how is this even a question (not that I'm questioning your right to ask the question OP), but its quite rhetorical because almost every Dev I've ever met has had some type of technical support work implicit within his or her job function. You simply can't avoid it. In most cases your the most technically compitant person not just in your functional domain, but in terms of IT in general. It's very hard to avoid completely.

A: I got into this trap when I joined a company with good pay. During the interview I have been told that there will be 70% development and 30% support and I accepted the offer. May be it is the company or environment that I'm currently working on. But actually it 90% support and 10% development. Its been a couple of years now I lost the grip of development. I regret that I accepted this offer.
But I feel like I have lost the grip of coding more over there a lot of new technologies and  frameworks. Now I don't know where to start again. I keep on preparing but these helloworld examples are not enough to have some good practical experience and it is really getting difficult to update my knowledge and experience. I can't even leave my job to start over because of family commitments.
Unfortunately I'm in a deadlock.
Please don't accept roles if you dont like or not interested in.


text:
Q: Unity load files from outside of resources folder In unity is it possible to load a resource that is out side of the resources folder. I want the user to be able to set a textAsset variable from a file outside of the Assets directory entirely.

A: You can't load TextAsset from an external path(path not in the Unity game). In fact, you can't even load it from a path in the project itself which is not the Resources path which is then loaded with the Resources API.
One option you have is to use the AssetBundle. Add the TextAsset to the Assetbundle then you can load the Assetbundle from any path and extract the TextAsset from it.
If you just want to load any file outside the Unity path, you can do this without TextAsset. Just use any of the System.IO API such as File.ReadAllText an File.ReadAllBytes. This should be able to load your file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Grid Search Hyperparameters for Neural Network (Keras) I'm trying to optimize the hyperparameters of my neural network using both Keras and SKlearn, I am wrapping up my model with a KerasRegressor as this is a regression problem. I am trying to optimize various parameters:

*

*Number of Hidden Layers

*Number of Neurons per Hidden Layer

*Optimizer

*Number of Epochs and Batch_Size

*Activation Function

I can do this separately, but I wanted to try to run everything and all parameters at the same time :) to see if it would be possible to get an all out comparison but I keep getting the following error.
Error
PicklingError: Could not pickle the task to send it to the workers.

Here you can find my code below
def build_regressor(optimizer='adam', activation = 'relu', hidden_layers=1, neurons=1):
  # Initialize the constructor
    regressor = Sequential()
  # Add an input layer
    regressor.add(Dense(neurons, activation=activation, input_shape = (x_train.shape[1],)))

    for i in range(hidden_layers):
      # Add one hidden layer
        regressor.add(Dense(neurons, activation=activation))

  # Add an output layer
    regressor.add(Dense(1, activation=activation))
  #compile model
    regressor.compile(loss='mean_squared_error', optimizer= optimizer, metrics= ['mse','mae'],
                      epochs = epochs, batch_size = batch_size)
    return model

#Wrap Model
regressor = KerasRegressor(build_fn=build_regressor, verbose=1)

# define the grid search parameters
batch_size = [10, 20, 40, 60, 80, 100, 150]
epochs = [10, 50, 100, 150, 200]
neurons = [1, 32, 64, 128, 256, 512]
optimizer = ['SGD', 'adam']
#activation = ['relu', 'linear', 'softmax']

param_grid = dict(batch_size = batch_size, epochs = epochs, neurons = neurons, optimizer = optimizer)

#implement grid_search
grid = GridSearchCV(estimator=regressor, param_grid=param_grid, n_jobs=-1, cv=3, scoring = 'r2')
grid_result = grid.fit(x_train, y_train)

#Fit Model
results=regressor.fit(x_train,y_train)
y_pred= regressor.predict(x_valid)

# summarize results
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
    print("%f (%f) with: %r" % (mean, stdev, param))

Code


text:
Q: Pass Parameters in Link_to I would like to pass a parameter through a link_to method in Rails. I know there is a way to do it via the URL but I really don't want to do that. Is there any way to pass a param via a link without adding it to the link itself?
I know in PHP you can post and then retrieve that value by using the post variable. Is there something similar in Rails?

A: Here's how you can pass a parameter around via the link_to method in order to, say, create a new object with the passed parameter. This strategy would allow you to pass variables among actions in your controller and create objects with predefined attributes:
Say in your show view, you have a variable called @foo that you want to pass to your new controller action.  In which case, in your show view, you can have
<%= link_to "Link Text", new_widget_path(:foo => @foo) %>

which would store @foo in params[:foo], allowing you to use params[:foo] in your controller. Which controller action you get directed to depends upon *new_widget_path*. In this case, you get directed to the new action in WidgetController.
Clicking on Link Text will direct Rails to the new action of your WidgetController. You can have
def new
  @widget = Widget.new(:foo => params[:foo])
end

Then, in your new.html.erb view file, you can allow the user to create a new Widget object with this pre-defined foo attribute already filled out via a hidden form field:
 <%= form_for(@widget) do |f| %>
  <%= f.label :other_attribute %><br />
  <%= f.text_field :other_attribute %>
  <%= f.hidden_field :foo %>
  <%= f.submit %>
<% end %>

Allowing the user to create a new widget with the foo attribute already filled out!

A: Passing information through a web request can be done either by the URL: http://example.com/foo?bar=blah in a GET request which is what link_to does, or through a POST operation which usually requires a form.   The form could have hidden elements if you just want a submit button:
<form method="POST" action="http://example.com/foo">
  <input type="hidden" name="bar" value="blah">
  <input type="submit">
</form>

There are various rails helpers to help build the form if needed.
Lastly, if you really want a link, you could either CSS style that button, or you could use javascript to observe a link and then POST the info. (the method Simon Bagreev posted does this with javascript)

A: link_to signature looks as follows:
link_to(body, url_options = {}, html_options = {})

So, POST would look like (lets say you want to POST user's data):
link_to "Link text", some_path(:foo => "bar", :baz => "quux"), user: @user, :method => :post

User's data can be retrieved in the controller using params[:user]

A: What sort of parameter? If it's a key for a GET request, convention would dictate using the url (e.g. params[:id] or a an active record path variable). If you want to POST something, you should be using a form. Otherwise, you could write a helper method to set a session variable or something, but think about your architecture and what you're semantically trying to do, and I'm sure someone here can help you out.


text:
Q: React Hooks: Check if JSON object exists in useState and add if it doesn't make one and add it to it? I have a <Day/> component which is a child of a <Calendar/> component naturally;
<Day/> has a dayInfo prop. At this point I am trying to convert the event.target.computedName data I get from a click on the calendar and pass it to the day component like so: <Day dayInfo={event.target.computedName}/>
  event.target.computedName === 'April 9, 2020'

From there I'd like to convert it to an JSON object and then push it to state/array in the day component:
var [dayCollection, setDayInCollection] = useState([]);

So April 9, 2020 becomes:

dayCollection = [
  "April-9-2020" : {} // a JSON object awaits some data about the day!!!
]

So this is my Day component:
export default function Day({ dayInfo }) {
  var [dayCollection, setDayInCollection] = useState([]);

  useEffect(() => {
    console.log('dayInfo ', dayInfo);
    if (!dayInfo in dayCollection) {
      setDayInCollection(
        dayCollection.concat(
          JSON.parse(
            JSON.stringify(
              dayInfo
                .split(' ')
                .map((item) => {
                  if (item.indexOf(',')) return item.replace(/,/g, '');
                })
                .join('-')
            )
          )
        )
      );
    } else {
      console.log('do nothing');
    }
  }, [dayCollection]);

  console.log('dayCollection ', dayCollection);
  /* rest omited for brevity */
}

I believe I have the conversion of 'April 9, 2020' to "April-9-2020" as I've logged it, but the check of dayCollection/state continuously yields []
So how do I check if that JSON object exists in the state of the Day component, and add it if it doesn't make a JSON object and concat it to the state?
Thanks in advance!


text:
Q: What is difference between "Keras backend + Tensorflow" and "Keras from Tensorflow" using CPU(in Tensorflow 2.x) I want to limit CPU cores and threads.
So I found three ways to limit these.
1) "Keras backend + Tensorflow"
from keras import backend as K
import tensorflow as tf

config = tf.ConfigProto(intra_op_parallelism_threads=2, \
                        inter_op_parallelism_threads=4, \
                        allow_soft_placement=True, \
                        device_count = {'CPU': 1})
session = tf.Session(config=config)
K.set_session(session)

2) "Keras from Tensorflow"
import tensorflow as tf
from tensorflow import keras

tf.config.threading.set_intra_op_parallelism_threads(2)
tf.config.threading.set_inter_op_parallelism_threads(4)

3) "keras from Tensorflow"
import os

os.environ['TF_NUM_INTRAOP_THREADS'] = '2'
os.environ['TF_NUM_INTEROP_THREADS'] = '4'

These three ways are same affects?
Lastly I understood for the parameters like I wrote below

*

*intra_op_parallelism_threads("number of CPU cores")

*inter_op_parallelism_threads("number of threads")

is this right?
If I miss-understanding please let me know.
Thank you.

A: Not exactly, it's not as simple as that. As per official documentation -
intra_op_parallelism_threads - Certain operations like matrix multiplication and reductions can utilize parallel threads for speedups. A value of 0 means the system picks an appropriate number. Refer this
inter_op_parallelism_threads - Determines the number of parallel threads used by independent non-blocking operations. 0 means the system picks an appropriate number. Refer this
So technically you can not limit the number of CPUs but only the number of parallel threads, which, for the sake of limiting resource consumption, is sufficient.

Regarding the methods, you are using -
The third approach allows you to directly set the environment variables using os library.
import os

os.environ['TF_NUM_INTRAOP_THREADS'] = '2'
os.environ['TF_NUM_INTEROP_THREADS'] = '4'

The second approach is a method in tf2 that does exactly the same (sets environment variables), the difference being that Keras is packaged into tf2 now.
import tensorflow as tf
from tensorflow import keras

tf.config.threading.set_intra_op_parallelism_threads(2)
tf.config.threading.set_inter_op_parallelism_threads(4)

The first approach is for standalone Keras. This approach will work if keras is set to tensorflow backend. Again, it does the same thing which is set environment variables indirectly.
from keras import backend as K
import tensorflow as tf

config = tf.ConfigProto(intra_op_parallelism_threads=2, \
                        inter_op_parallelism_threads=4, \
                        allow_soft_placement=True, \
                        device_count = {'CPU': 1})
session = tf.Session(config=config)
K.set_session(session)

If you still have doubts, you can check what happens to the environment variables after running all 3 independently and then check the specific variable using os with -
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

For a better understanding of the topic, you can check this link that details it out quite well.

TLDR; You can use the second or third approach if you are working with tf2. Else use the first or third approach if you are using standalone Keras with tensorflow backend.

A: For completing Akshay Sehgal answer, I found these facts regarding choosing the right number of intra and inter parallelism threads in my case by trial and error:

*

*Almost all CPU logical cores (processors) correspond exactly to the number of intra parallelism threads (for example, if I reduce performance of a 8 logical processors CPU into 1 intra parallelism thread, then something around 1/8 of CPU performance will be exerted, however, the ratio is not exact). I also found that almost no role in changing CPU performance exists for inter parallelism threads after running my tensorflow model. However, I think it is best to specify number of inter parallelism threads as the rest of CPU's logical processors (for example, setting inter parallelism threads as 7 for a CPU with 8 logical processors when we already has chosen intra parallelism threads as 1) The reason is because I suspect inter parallelism threads might relate to the number of logical processors which runs other processes parellel to tensorflow model but I am not sure.

*There are no difference between changing intra and inter parallelism threads in both os.enviorn AND tf.config method but for sake of safe execution I considered applying both methods.

*Increasing threads more than number of your CPU's logical processors will keep its performance onto its maximum capacity for your process. for example, if your CPU has 8 logical cores, then defining 200 intra/inter parallelism threads is possible However the final performance still equals to 8 threads. Notice that in tensorflow calculations  CPU performance does not necessarily reach 100% if you assign maximum CPU performance for your model which is also true for any other CPU related process.

*Changing number of each threads into 0 will change back multi-thread parallelism settings into default again.


text:
Q: Group Comparisons for Predictions from GAMs Consider a continuous response y that varies with time x in groups A and B, and suppose the data are modeled using a GAM (generalized additive model) with separate trend for each group.  For example, consider the following data and GAM model:
set.seed(1)
n <- 100
sigma <- 0.1

x_A <- runif(n, -1, 12)
y_A <- 1 + sin(x_A)*exp(-x_A/4) + rnorm(n, 0, sigma)
x_B <- runif(n, -1, 12)
y_B <- (x_B/10)^(1/4) + rnorm(n, 0, sigma)
data <- data.frame(x = c(x_A, x_B), y = c(y_A, y_B), group = factor(rep(c("A", "B"), each = n)))
plot(data$x, data$y, col = rep(c("red", "blue"), each = n))

fit <- mgcv::gam(formula = y ~ group + s(x, by = group), data = data)

From this model, we would like to estimate the following:

*

*Mean response at times x = 0, 2, 4, and 6 in each group.

*Mean change from baseline (x = 0) at times x = 2, 4, and 6 in each group.

*Difference between groups in the mean change from baseline at times x = 2, 4, and 6.

For 1), we can obtain predicted values and their standard errors as below.  Is it appropriate to compute a normal confidence interval from these values?  Or is some other method recommended?
predict(fit, newdata = data.frame(x = rep(c(0, 2, 4, 6), 2), group = rep(c("A", "B"), each = 4)), se.fit = TRUE)
$fit
        1         2         3         4         5         6         7         8
0.9920607 1.5081197 0.7288036 0.9754705 0.3488343 0.6745791 0.7577260 0.9192016

$se.fit
         1          2          3          4          5          6          7          8
0.03190964 0.03046708 0.02543294 0.03505692 0.04524974 0.02557121 0.02315219 0.02880036

For 2), we could compute the difference in the estimated mean at each of x = 2, 4, 6 vs x = 0.  Supposing we compute a normal confidence interval for this quantity, how can the variance of the difference be estimated?  It does not seem like the estimates at, say, x = 0 and x = 2 would be independent, so I don't think we could just add the estimated variances, right?
For 3), supposing we have estimates of the mean change from baseline and its standard error in each group at the time points of interest (e.g. from 2), is it appropriate to assume independence and form a normal confidence interval for the difference?
Would inference for 2) or 3) be easier with a different model formulation?


text:
Q: 'If' statement with the 'or' operator in PHP I'm trying to build up a PHP if statement with or ("||") operators, but it doesn't seem to work.
   $country_code = "example_country_code";

   if ($country_code != 'example_country_code' || !clientIscrawler()) {
       echo 'the script can be executed';
   }
   else {
       echo 'skipping';
   }

With the given example, it should be echoed skipping, but it doesn't happen like that. What am I doing wrong?

A: Perhaps the double negatives are giving you problems. Let's rewrite it to:
!($country_code == 'example_country_code') || !clientIscrawler()

This can be turned into an equivalent condition with &&:
!($country_code == 'example_country_code' && clientIscrawler())

By reversing the if you would get this:
if ($country_code == 'example_country_code' && clientIscrawler()) {
    echo 'skipping';
} else {
    echo 'the script can be executed';
}

Therefore, in your code, it will only print skipping if clientIscrawler() is truthy.

A: If you have multiple conditions with the OR operator, in which case you don't want the if statement to evaluate as true, the syntax is:
if(!($something == "something" || $something == 'somethingelse')){
    do stuff...
}

Here is an example:
$apples = array (
 1 => "Pink Lady",
 2 => "Granny Smith",
 3 => "Macintosh",
 4 => "Breaburn"
);

foreach($apples as $apple){

    // You don't want to echo out if the apple name is "Pink Lady" or "Macintosh"

    if(!($apple == "Pink Lady" || $apple == "Macintosh")){

        echo $apple."<br />";

    }
}

// Output is:
Granny Smith
Breaburn

A: In your given code, it all depends on your function call
 !clientIscrawler()

You will be getting the script can be executed output only when your function call returns FALSE. I think it is returning TRUE right now, which is why you are not getting the desired output.

A: Try this way:
if ( ($country_code != 'example_country_code') || !clientIscrawler()) { ...

A: Maybe this can help you:
if ( ($country_code != 'example_country_code') || clientIscrawler() == false) {


text:
Q: Problems with multiline captions How can I get multiline captions on my banner slider (standard)?
I was able to get the Banner Slider working in my custom Foundation HTML site, but the captions only show up as a single line and cut off anything after that first line.  Any ideas how to get multiline captions working?
Thanks!

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

A: Add new line

Lorem ipsum dolor sit amet,
 consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.


text:
Q: How do I access my application's state (classes, properties, etc.) upon a callback from CFStream? I'm writing an iPhone app that involves handling network events from a server over a VoIP socket in the background. I've successfully set up the socket, the background service info in the .plist, and the appropriate streams, but I'm having trouble figuring out how to do anything useful in my callback. I don't know how to access the rest of my application's state from within the callback function. Here is where I set up the connections in the AppDelegate:
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    NSLog(@"AppDelegate: didFinishLaunchingWithOptions");
    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    [self.window addSubview:viewController.view];
    [self.window makeKeyAndVisible];

    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFHostRef host = CFHostCreateWithName(kCFAllocatorDefault, (CFStringRef)@"irc.freenode.net");
    CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, host, 6667, &readStream, &writeStream);
    CFReadStreamSetProperty(readStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);
    CFWriteStreamSetProperty(writeStream, kCFStreamNetworkServiceType, kCFStreamNetworkServiceTypeVoIP);

    CFStreamClientContext myContext = {
        0,
        viewController,
        (void *(*)(void *info))CFRetain,
        (void (*)(void *info))CFRelease,
        (CFStringRef (*)(void *info))CFCopyDescription
    };

    CFOptionFlags registeredEvents = kCFStreamEventHasBytesAvailable |
    kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered;

    if(CFReadStreamSetClient(readStream, registeredEvents, clientCB, &myContext)) {
        CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
    }

    if (!CFReadStreamOpen(readStream)) {
        NSLog(@"Read stream could not be opened");
    }
    else {
        NSLog(@"Successfully opened read stream");
    }
    return YES;
}

And here is the callback function for CFStream events, where I'm having my issues:
void clientCB(CFReadStreamRef stream, CFStreamEventType event, void* myPtr) {
    switch(event) {
        case kCFStreamEventHasBytesAvailable:{
            UInt8 buf[32];
            CFIndex bytesRead = CFReadStreamRead(stream, buf, 32);
            if (bytesRead > 0) {
                NSLog(@"Readstream Not Empty %i", buf[0]);//dummy debug marker
            }
            //I WANT TO ACCESS CLASSES, PROPERTIES, FUNCTIONS, ETC. ABOUT THE REST OF MY PROGRAM HERE (E.G. GET A WORKING POINTER BACK TO THE MAIN APPDELEGATE).
        break;
    }
    case kCFStreamEventErrorOccurred:
    case kCFStreamEventEndEncountered:
    default:
        break;
}
}

These two functions are both defined in the same AppDelegate class. I've tried passing pointers via the CFStreamClientContext struct: VoIP_TestViewController* testViewController = context->info;, I've tried to access the main appDelegate via: [[UIApplication sharedApplication] delegate], and I've tried the usual Obj-C and C constructs ("this", "self", "super").
Any help would be greatly greatly appreciated!

A: *

*Make sure you import your main app delegate header file into the view where you need to call it.

*Use this to call it:
nameOfYourAppDelegate *appDelegate = (_nameOfYourAppDelegate *)[[UIApplication sharedApplication] delegate];
//than you can use appDelegate for whatever you want (ie. appDelegate.somView.someProperty )

A: Ah I'm an idiot. I forgot to import a class header for a member class (i.e. I forgot to import ClassB when I tried to access [ClassA.ClassB methodB]). Of course XCode only provided an unrecognized selector runtime error rather than a missing declaration compiler error, making debugging slightly harder than it should have been. Thanks for the catch!


text:
Q: suspendThread in windows Keeping my question short... i am writing simulation for a RTOS. As usual the main problem comes with context switch simulation. In case of interrupts it is really becoming hard not to deviate from 'Good' coding guidelines.
Say Task A is running and user application is calculating its harmless private stuff which will run for a long time. during this task A, an interrupt X is supposed to occur. (hint: task A has nothing to do with triggering this interrupt X)... now how do i perform context switch from Task A to interrupt X handler?
My current implementation is based on a context thread that waits till some context switch is requested; an interrupt controller thread that can generate interrupts if someone request interrupt triggering; and a main thread that is running Task A. Now i use interrupt controller thread to generate a new thread for interrupt X and then request context thread to do the context switch. Context thread Suspends Task A main thread and resumes interrupt X handler thread. At the end of interrupt X handler thread, Task A main thread is resumed..
[Edit] just to clarify, i already know suspending and terminating threads from outside is really bad. That is why i asked this question. Plus please don't recommend using event etc. for controlling Task A. it is user application code and i can't control it. He can even use while(1){} if he wants...

A: I suspect that you can't do what you want to do in that way.
You mentioned that suspending a thread from outside is really bad. The reason is that you have no idea what the thread is doing when you suspend it. It's impossible to know whether the thread currently owns a mutex; if it does then any other thread that tries to access the same mutex is going to deadlock.
You have the problem that the runtime being used by the threads that might be suspended is the same as the one being used by the supervisor. That means there are many potential such deadlocks between the supervisor and the other threads.
In a real environment (i.e. not a simulator), the operating system kernel can suspend threads because there are checks in place to ensure that these deadlocks can't happen. I don't know the details, but it probably involves masking interrupts at certain critical points, and probably not sharing the same mutexes between user-mode code and critical parts of the kernel scheduler. (In your case that would mean your scheduler could not use any of the same OS API functions, either directly or indirectly, as are allowed to be used by the user threads, in case they involve mutexes. This of course would be virtually impossible to achieve.)
The reason I asked in a comment whether you have any control over the user code compiler is that if you controlled the compiler then you could arrange for the user code to effectively mask interrupts for the duration of each instruction and only yield to another thread at well-defined points between instructions. This is how it is done in a control system that I work on.
The other aspect is platform dependence. In Linux and other unix-like operating systems, you have signals, which are like user-mode interrupts. You could potentially use signals to emulate context switching, although you would still have the same problem with mutexes. There is absolutely no equivalent on Windows (as far as I know) precisely because of the problem already stated. The nearest thing is an asynchronous procedure call, but this will run only when the thread has put itself into an alertable wait state (which means the thread is in a deterministic state and is now safe to interrupt).
I think you are going to have to re-think the whole concept so that your supervisory thread has the sort of privileged control above the user threads that the OS has in a non-emulated environment. That will probably involve replacing the compiler or the run-time libraries, or both, with something of your own making.


text:
Q: Why does using throw an exception when it's supposed to behave like try/catch/finally? As far as I understand, using works like a try/catch/finally, so I would expect that if an exception occurs in a using statement it would get caught (which is kinda odd, because that would also mean that the exception is silently eaten). The using statement should catch the exception and call the Dispose method, however, that is not happening. I've devised a simple test to demonstrate the issue.
Here is where I force an exception to occur inside the using statement:
using (TcpClient client = new TcpClient())
{
    // Why does this throw when the using statement is supposed to be a try/catch/finally?
    client.Connect(null);
}

An exception is throw by client.Connect() (meaning that it was not caught by the using statement or that it was re-thrown):
System.ArgumentNullException: Value cannot be null.
Parameter name: remoteEP
   at System.Net.Sockets.TcpClient.Connect(IPEndPoint remoteEP)
   at DotNETSandbox.Program.Main(String[] args) in C:\path\to\Sandbox\Program.cs:line 42

According to a Microsoft article on the topic, the using statement might throw if the Dispose method throws.
However, when I'm following the using pattern, it is evident that the Dispose method does not throw:
TcpClient c2 = new TcpClient();
try
{
    c2.Connect(null);
}
catch (Exception e)
{
    // We caught the null ref exception
    try
    {
        // Try to dispose: works fine, does not throw!
        ((IDisposable)c2).Dispose();
    }
    catch (Exception e2)
    {
        Console.WriteLine(e2.ToString());
    }
    Console.WriteLine(e.ToString());
}

I'm a little confused, since I was expecting using to behave like a try/catch. Could anybody explain why this is happening?

A: using is
try
{
}
finally
{
}

only !!!
there is no catch !
in .net you dont have to catch the exception..
its just a mechanism which calls DISPOSE method as soon as you leave the scope . thats all.
p.s. : " how will i know if my object can be used with using ?"
answer : don't worry - you will see error on compile time.

A: using is more of a try/finally without a catch.
Control can't leave the block without the object you're using being Disposed, that's it. Any exception thrown from inside the block will (after Disposing) be passed on as normal.
Edit: Picking nits on my own answer, in the special case of implementing an IEnumerable and yielding out of a using you could be said to leave the block without Dispose() being called, but when continuing the enumeration you'll end up right back inside again.

A: Because using doesn't behave like a try/catch/finally. It behaves like a try/finally.
Your first example, while it throws an Exception, will still properly Dispose the TcpClient.

A: Using statements behave like a try, finally block, not a try, catch, finally block.
Exceptions will still throw out of the using block.

A: As many people have said the using statement does not catch exceptions.  But I can see your confusion from this article.
It says that IF the Dispose() fails it can hide any errors that were thrown within the using block.
Because the Dispose() occurs inside a "finally" block, the ApplicationException is never seen outside the using block if the Dispose() fails


text:
Q: Is there a static URL that can be used to always view the details of the latest version of a package? I've published a package to nuget.org. I recently added icons to the package, so I updated it with a new version number. The version number is part of the URL to the details. I have a link to that page on my project site, but I don't want to have to update that link everytime a new version is released.
Is there a static URL that will always take me to the latest version of a given package?
In case you're wondering, my package is called Args, and the URL to the latest version of the detail page (at the time of writing) is http://nuget.org/Packages/Packages/Details/Args-1-0-1

A: You can as of now. We just updated nuget.org. More info here:
http://twitter.com/#!/anglicangeek/status/45386847362363392
So your new url would be:
http://nuget.org/List/Packages/Args


text:
Q: Why `commit` is needed before `git checkout`? I thought git add is enough to log the modifies made before checkout to another branch.
Therefore, why do the modifies should be logged to local repository by commit?

A: It's because you can patch diffs in and out of your staged content in both directions, from history or from your work tree, at any time. Commit says "yep, this whole set is worth revisiting later", but before then it's still actively being edited, by you.
git add doesn't have to be treated as provisional; for people unused to thinking of their vcs as a tool helping them iterate drafts of the history they're eventually going to publish it seems weird and unnecessary. Once you start thinking of your local history as a whole-tree, long-term extension of your editor's undo buffers it makes much more sense. Git helps you do the work as well as work out how best to present it.

A:
I thought git add is enough to log the modifies made before checkout to another branch.

This is not the case.
Git is, at its heart, all about commits.  A commit is a numbered entity—it has a unique hash ID, that random-looking string of letters and digits such as 30cc8d0f147546d4dd77bf497f4dec51e7265bd8.  Git uses the hash ID to find the commit in its "objects" database, which stores the commits and various supporting objects needed to make the commits actually work.  Each commit stores two things:

*

*a full snapshot of all of your source files (in a special, read-only, Git-only, compressed and de-duplicated format so that making hundreds of commits doesn't take much space at all—most of the files are de-duplicated), and

*some metadata: information about the commit itself, such as the name and email address of the author of the commit, and some date-and-time-stamps and so on.
Commits are mostly permanent—you can get rid of a commit by just making it so that you can't find it unless you've memorized its hash ID, and then Git will (after a lot of time) eventually discard the commit entirely—and completely read-only.  Being read-only, though, and in a format that only Git can read in the first place, you literally can't actually use a commit at all!  This means that for you to use a commit, Git has to extract a commit.
Most version control systems behave this way.  That is, you say "I'd like to work on commit XXXXX" (for some hash ID—in Git, you will normally use a branch name here, but that translates into a hash ID internally)—and the version control system says OK, let me go find and extract the archive that is stored under that ID.  In traditional version control systems, ten minutes later or so you have a version you can work on / with.  You do your work and then you run their "commit" verb and wait another half an hour for them to make a commit.
With Git, you say "extract the commit" and milliseconds (or maybe a few seconds) later you have the commit and can start work.  But you can't just run git commit when you're done working: instead, Git makes you run git add first, and then run git commit.1  The important question is not "do I have to do this", but rather rather "why do I have to do this?"  The answer lies in Git's index or staging area.  Git requires that you be aware of what the index is and does for you.

1In some cases, you can run git commit -a, but I don't recommend this because it skips right over the key reason you're using git add in the first place, and leaves you stranded when you hit one of the situations where git commit -a doesn't work (there are several of these; some depend on whether you use "pre-commit hooks" and how good someone was at writing a pre-commit hook, for instance).  It also means that you can't grasp why .gitignore sometimes doesn't work, what happens with git stash, and numerous other cases.

Git's index, aka staging area, aka cache
The thing that Git calls by three names—index, staging area, and (rarely these days) cache—has multiple purposes, but its most important one, the one you really have to know at all times, is this: the index or staging area holds your proposed next commit.
When you run git commit, Git builds a new commit in milliseconds or seconds, not the minutes or hours older version control systems tended to take.  The reason Git can do this is that the index always holds the proposed next commit.  When you run git commit, Git hardly has to do any work at all: it just takes all the files that are in the index right then and freezes them into a new commit.
What's in the index is hard to see, kind of on purpose.  There is a Git command that can list its content—git ls-files—but it's not one users will normally use; it's not very useful.  Here's a snippet of git ls-files --stage output, as run on the Git repository for Git:
[...]
100755 af5da45d2878e07ffe4586bfb8c1dc16134f9e95 0       Documentation/cmd-list.perl
[...]
100644 1fb1b2ea90c5953eb465d3b108c01f23fb442a32 0       commit.c
100644 21e4d25ce7878ab6463110b6b3104c7b99d159cb 0       commit.h
100644 c531372f3ff0f13839a2056568cbaa7fd37f98a8 0       common-main.c
100644 40dbfb170dabc5a43d1194bd2fb32fe1580ff980 0       compat/.gitattributes
100644 19fda3e877641c3c083618928c241351f1caaf91 0       compat/access.c
[...]
100644 8442bd436efeab81afc25db9d89da082638fcca4 0       xdiff/xtypes.h
100644 115b2b1640b4504d1b7eb1bc4dc1428b109f6380 0       xdiff/xutils.c
100644 fba7bae03c7855ca90aff3f238321581a91a6676 0       xdiff/xutils.h
100644 d594cba3fc9d82d94b9277e886f2bee265e552f6 0       zlib.c

For every file that would go into a new commit (if I made one right now), the index has one of the above entries.  This entry gives the file's mode—"executable" or "not executable", which for silly historical reasons is spelled 100755 or 100644—and the file's name and the (hash ID of the) de-duplicated, ready-to-commit file content, among other information.  The 0 in last column before the file's name is the staging number, which in normal use is always zero.
So, if I were to run git commit right now, Git would use the files in the index to make a new snapshot.  Well, actually, it would complain:
$ git commit
On branch master
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

because all the files in the index match all the files in the current commit!  (Git can tell this quite fast—just a few milliseconds—because the contents are all pre-de-duplicated, so the internal hash IDs all match.)
What running git add on a file does is update the index / staging-area.  That is, suppose I open up Makefile or xdiff/xutils.h in my editor and make changes to this file.  I write these changes out.  The changes I made go into the working tree, which holds the extracted files.  The working tree does not hold the committed files: those are in a special Git-only de-duplicated format and my editor and compiler can't even read them.  Nothing—not even Git itself—can change them.  But the working tree files are just ordinary everyday files, so everything can read and change those, including me and my editor.
If I do change them, though, I must prepare an updated, de-duplicated copy to be committed.  To do that, I must run git add.  The git add command reads the working tree copy and compresses it down and checks for duplicates:

*

*If there is a duplicate, git add makes a note of that while updating Git's index / staging-area.  The compressed copy git add made is no longer needed; it gets discarded.

*If there is no duplicate, git add makes a note of that while updating Git's index / staging-area.  The compressed copy git add made will be needed, but it's ready for committing now!
So in either case the index is once again ready for the next commit.  The git add command has merely updated the proposed next commit by updating the index aka staging area.
Running git commit saves what's in the index
If I now run git commit, Git will make a new commit, with the new (i.e., updated) snapshot I prepared by running git add.  This new snapshot will be saved forever—or rather, as long as the commit itself exists.  Git will add this new commit, with its new snapshot and metadata, to the database of "all Git objects".  (Any all-new files are now objects in the database as well, in their compressed format: they weren't duplicates.  If they had been duplicates, they wouldn't be all-new and git add would have re-used the old saved content.)
(The new commit then becomes the latest commit on the branch, in the usual fashion; we'll skip all the details here.)
This is why it takes at least two commands to make a new commit: git add prepares things, updating the proposed next commit, and git commit turns the proposed commit into an actual commit.  Until then, it's just a proposal.
Another way to look at this is that, at all times, there are three copies of each "active" file (assuming it's in the current commit):

*

*There's a frozen-for-all-time, unchangeable copy of some file in the current commit.

*For that particular file, there's a frozen-format (i.e., de-duplicated) copy in Git's index too.

*And, for that particular file, there's an ordinary, usable, read/write copy in your working tree.

What git add does is copy the working tree version into the index.
This explains how git status works as well
When you run git status, Git says things like:
On branch main
Your branch is up to date with 'origin/main'.

Changes staged for commit:

Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   file1

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   file2

What Git has done is to run two git diff operations:

*

*First, Git compared what is in the current commit to what is in Git's index / staging area.  Here, every file matched except for file1.  File file1 is different.  So Git calls that one out as "staged for commit".  If I were to run git commit right now, the new commit would have a different copy of file file1, than the copy that's in the current commit.

*Then Git compared what is in the index to what is in my working tree.  Here, every file matched except for file2.  File file2 is different.  So Git calls that one out as "not staged for commit".  Running git commit won't store the updated file2 unless I run git add on it.  Instead, it will store the unchanged file2 that's still there in Git's index.
Having listed these out, Git may go on to report untracked files.  An untracked file is simply any file in your working tree that is not in Git's index.  That's all there is to that, except for one extra feature.
.gitignore
Files that aren't in Git's index will, by definition, be omitted from the next commit.  That's clear now: we know that Git makes the new commit from what's in Git's index.  If the file isn't in the index, it won't be in the new commit.
Such a file is said to be untracked.  Running git status reports on this file.  But sometimes, an untracked file is untracked on purpose rather than by mistake.  For instance, if we use Python, Python builds *.pyc files and/or *.pyo files (Python3 puts them in folders named __pycache__, which keeps down the clutter a bit, while Python2 drops them all over the working tree).  We don't want to commit these files (it's a bad idea in general).  But we don't want git status to whine about them either.
To make git status shut up about untracked files, we can list the files' names or patterns in one or more .gitignore files.  These tell Git: When I run git status and these files are untracked, don't whine! This does not make the files untracked!  It is the fact that the files aren't in Git's index that makes the files untracked.  If a file is tracked, listing it in a .gitignore has no effect.  This fact only makes sense when you understand what the index is doing.
Besides making git status shut up, listing file patterns in .gitignore allows us to use a short-cut: we can run git add . or git add * or git add --all, and Git will not add these files if they are untracked.  That is, we can use en-masse "add everything", and it will only add untracked files as new files in the index if they would be complained-about.
What this means is that .gitignore is the wrong name for this file: it should be called .git-do-not-complain-about-these-files-when-they-are-untracked-and-when-they-are-untracked-and-I-use-an-en-masse-git-add-command-do-not-add-them-to-the-index-either, or something like that.  But do you really want to type in this file name?  (No, you don't.)  So .gitignore it is.


text:
Q: Bad Request model derivative autodesk api when translating dwg to obj format I want to use autodesk model derivative api to show DWG file in forge viewer. In
result = _client.Execute(objReq);
            if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
            {
            }

I get badrequest.
   public virtual ActionResult Index()
    {
        SetupViewer();
        if (_bucketFound)
        {
            //upload file
            RestRequest uploadReq = new RestRequest();
            uploadReq.Resource = "oss/v2/buckets/"+_bucketName+"/objects/"+_filepath;

            uploadReq.Method = Method.PUT;
            uploadReq.AddHeader("Content-Type", _fileContentType);
            uploadReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);

          var result=  _client.Execute(uploadReq);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                String responseString = result.Content;
                int len = responseString.Length;
                int objectKeyIndex = responseString.IndexOf("\"objectKey\" : \"");
                int index = responseString.IndexOf("urn:");
                responseString = responseString.Substring(index, objectKeyIndex - index-5).Replace("urn:", "").Trim();

                _fileUrn = "urn:"+responseString;
                //convert urn to base64
                string base64Urn = Base64Convertor.Base64Encode(_fileUrn);
                // Remove ending '=' signs
                // Use _ instead of /
                // Use - insteaqd of +
                base64Urn = base64Urn.Replace("=", "");
                //translate to SVF format
                //RestRequest svfReq = new RestRequest();
                //svfReq.Resource = "modelderivative/v2/designdata/job";

                //svfReq.Method = Method.POST;
                //svfReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
                //svfReq.AddParameter("Content-Type", "application/json;charset=utf-8", ParameterType.HttpHeader);
                //string body = "{\"input\":{\"urn\":\"" + base64Urn + "\",\"compressedUrn\":true,\"rootFilename\":\""+_filepath+ "\"},\"output\":{\"formats\":[{\"type\":\"svf\",\"views\":[\"2d\"]}]}}";
                //svfReq.AddParameter("application/json", body, ParameterType.RequestBody);

                // translate to OBJ format
                RestRequest objReq = new RestRequest();
                objReq.Resource = "modelderivative/v2/designdata/job";

                objReq.Method = Method.POST;
                objReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
                objReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
                string body = "{\"input\":{\"urn\":\"" + base64Urn + "\"},\"output\":{\"formats\":[{\"type\":\"obj\"}]}}";

                result = _client.Execute(objReq);
                if (result.StatusCode == System.Net.HttpStatusCode.OK || result.StatusCode==System.Net.HttpStatusCode.Created)
                {

                    //check the transition complete
                    RestRequest checkTransitionCompleteGetReq = new RestRequest();
                    checkTransitionCompleteGetReq.Resource = "modelderivative/v2/designdata/"+base64Urn+"/manifest";
                    checkTransitionCompleteGetReq.Method = Method.GET;
                    checkTransitionCompleteGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);

                 var result2   = _client.Execute(checkTransitionCompleteGetReq);
                    if (result2.StatusCode == System.Net.HttpStatusCode.OK)
                    {

                        ViewBag.BucketFound = result.Content;
                    }
                }

            }
        }
        return View();
    }

    void SetupViewer()
    {
        // Authentication
        bool authenticationDone = false;

        RestRequest authReq = new RestRequest();
        authReq.Resource = "authentication/v1/authenticate";
        authReq.Method = Method.POST;
        authReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
        authReq.AddParameter("client_id", ConfigurationManager.AppSettings["ClientId"]);
        authReq.AddParameter("client_secret", ConfigurationManager.AppSettings["ClientSecret"]);
        authReq.AddParameter("grant_type", "client_credentials");
        authReq.AddParameter("scope", "bucket:create bucket:read data:write data:read");

        IRestResponse result = _client.Execute(authReq);
        if (result.StatusCode == System.Net.HttpStatusCode.OK)
        {
            String responseString = result.Content;
            int len = responseString.Length;
            int index = responseString.IndexOf("\"access_token\":\"") + "\"access_token\":\"".Length;
            responseString = responseString.Substring(index, len - index - 1);
            int index2 = responseString.IndexOf("\"");
            _accessToken = responseString.Substring(0, index2);

            //Set the token.
            RestRequest setTokenReq = new RestRequest();
            setTokenReq.Resource = "utility/v1/settoken";
            setTokenReq.Method = Method.POST;
            setTokenReq.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            setTokenReq.AddParameter("access-token", _accessToken);

            IRestResponse resp = _client.Execute(setTokenReq);
            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                authenticationDone = true;
            }
        }

        if (!authenticationDone)
        {
            ViewData["Message"] = "View and Data client authentication failed !";
            _accessToken = String.Empty;
            return;
        }

        RestRequest bucketReq = new RestRequest();
        bucketReq.Resource = "oss/v2/buckets";
        bucketReq.Method = Method.POST;
        bucketReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
        bucketReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);

        //bucketname is the name of the bucket.
        string body = "{\"bucketKey\":\"" + _bucketName + "\",\"policyKey\":\"transient\"}";
        bucketReq.AddParameter("application/json", body, ParameterType.RequestBody);

        result = _client.Execute(bucketReq);

        if (result.StatusCode == System.Net.HttpStatusCode.Conflict ||
            result.StatusCode == System.Net.HttpStatusCode.OK)
        {
          //  _bucketFound = true;
            //Check bucket
            RestRequest bucketGetReq = new RestRequest();
            bucketGetReq.Resource = "oss/v2/buckets";
            bucketGetReq.Method = Method.GET;
            bucketGetReq.AddParameter("Authorization", "Bearer " + _accessToken, ParameterType.HttpHeader);
            bucketGetReq.AddParameter("Content-Type", "application/json", ParameterType.HttpHeader);
            result = _client.Execute(bucketGetReq);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                _bucketFound = true;
                ViewBag.BucketFound = "Found";

            }
            else
                ViewBag.BucketFound = "NotFound";

        }
        else
        {
            ViewData["Message"] = "View and Data bucket could not be accessed !";
            _bucketFound = false;
            return;
        }
    }

A: Could you try this again, we had some down time from our side during that time, but everything should be back up and running for you. In case does not work I will take a look at your request.


text:
Q: convert array of objects to nested array of arrays for building chart I have the following array
const data = [
      {
        date: "2018-01-01",
        label: "MH",
        qt: 10
      },
      {
        date: "2018-04-01",
        label: "MH",
        qt: 30
      },
      {
        date: "2018-02-01",
        label: "GJ",
        qt: 30
      },
      {
        date: "2018-03-01",
        label: "KL",
        qt: 30
      },
      {
        date: "2018-02-01",
        label: "KL",
        qt: 40
      }
    ]

and i want my output to be
[
  [date,MH,GJ,KL],
  ['Jan 2018',10,null,null],
  ['Feb 2018',null,30,40],
  ['Mar 2018',null,null,30],
  ['Apr 2018',30,null,null]
]

How can i achieve that in an optimize way?
And the date should be sorted in order to.
I tried doing
data.sort(function compare(a, b) {
      var dateA = new Date(a.date);
      var dateB = new Date(b.date);
      return dateA - dateB;
    });
    let labelArr = data.map(l => l.label);
    let dateArr = data.map(l => l.date);
    labelArr = _.uniq(labelArr);
    dateArr = _.uniq(dateArr);
    console.log(labelArr, dateArr);

    const outputArr = [];
    dateArr.forEach(d => {
      labelArr.forEach(l => {
        const tempObj = data.filter(r => {
          if (d == r.date && l == r.label) {
            return r;
          }
          else {
            return { date: d, label: l, qt: null }
          }
        })
        outputArr.push(tempObj);
      });
    });

but i'm stuck here. What I was thinking is first i'll create the objects for date and label which are not present and add thier qt to null. After that i'll group by date and then insert only the qt to the result

A: You could take an object for keeping the array for each date and one for keeping track of the indices of the columns.
At the end set all elements to null for not set items.

var data = [{ date: "2018-01-01", label: "MH", qt: 10 }, { date: "2018-04-01", label: "MH", qt: 30 }, { date: "2018-02-01", label: "GJ", qt: 30 }, { date: "2018-03-01", label: "KL", qt: 30 }, { date: "2018-02-01", label: "KL", qt: 40 }],
    cols = {},
    rows = {},
    result = data
        .sort(({ date: a }, { date: b }) => a > b || -(a < b))
        .reduce((r, { date, label, qt }) => {
            date = date.slice(0, 7);
            if (!rows[date]) r.push(rows[date] = [date]);
            if (!cols[label]) cols[label] = r[0].push(label) - 1;
            rows[date][cols[label]] = (rows[date][cols[label]] || 0) + qt;
            return r;
        }, [['date']])
        .map((a, _, [{ length }]) => Array.from({ length }, (_, i) => a[i] || null));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: I don't know if it's the best solution, but it's a working solution:

const data = [{
    date: "2018-01-01",
    label: "MH",
    qt: 10
  },
  {
    date: "2018-04-01",
    label: "MH",
    qt: 30
  },
  {
    date: "2018-02-01",
    label: "GJ",
    qt: 30
  },
  {
    date: "2018-03-01",
    label: "KL",
    qt: 30
  },
  {
    date: "2018-02-01",
    label: "KL",
    qt: 40
  }
]

function formatData(data) {
  const labels = {};
  const map = {};

  data
    .sort((a, b) => a.date < b.date ? -1 : 1)
    .forEach(item => {
      const date = moment(item.date).format('MMM YYYY');
      labels[item.label] = true;
      if (map[date]) {
        map[date][item.label] = item.qt;
      } else {
        map[date] = { [item.label]: item.qt };
      }
    });

  const labelsArr = Object.keys(labels);
  const formattedData = Object.keys(map).map(date => {
    const values = labelsArr.map(label => map[date][label] || null);
    return [date, ...values];
  });

  return [['date', ...labelsArr], ...formattedData];
}

const result = formatData(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://momentjs.com/downloads/moment.min.js"></script>

A: I tried doing this:
    data.sort(function compare(a, b) {
      var dateA = new Date(a.date);
      var dateB = new Date(b.date);
      return dateA - dateB;
    });
    let labelArr = data.map(l => l.label);
    let dateArr = data.map(l => l.date);
    labelArr = _.uniq(labelArr);
    dateArr = _.uniq(dateArr);

    const outputArr = [['Date', ...labelArr]];
    dateArr.forEach(d => {
      const o1 = data.filter(e => e.date == d)
      const o2 = o1.reduce((s, a) => {
        s[a.label] = a.qt;
        return s;
      }, {})
      const b1 = []
      labelArr.forEach(l => {
        b1.push(o2[l])
      });
      outputArr.push([moment(d).format('MMM YYYY'), ...b1]);
    });

Hope it helps someone.


text:
Q: logarithmic differentiation of fraction Can some one help me with this problem: using logarithmic differentiation find the derivative of
$$\frac {e^{2x} (x^3-2)^4}{x(3e^{5x} +1)}.$$
I got stumped its a fraction, has e in it, and I'm supposed to use logarithmic differentiation.

A: Take natural logarithm from both sides of the given function:
$$y=\frac {e^{2x} (x^3-2)^4}{x(3e^{5x} +1)} \Rightarrow \\
\begin{align}\ln y&=\ln \frac {e^{2x} (x^3-2)^4}{x(3e^{5x} +1)}=\\
&=\ln (e^{2x} (x^3-2)^4)-\ln (x(3e^{5x} +1))=\\
&=2x+4\ln (x^3-2)-\ln x-\ln (3e^{5x}+1).\end{align}$$
Now take derivative (implicitly) from both sides:
$$\frac1y\cdot y'=2+\frac{12x^2}{x^3-2}-\frac1x-\frac{15e^{5x}}{3e^{5x}+1}$$
And the final answer is ...

A: Don't worry: logarithmic differentiation of a fraction
$$
F(x)=\frac{f(x)}{g(x)}
$$
consists in writing, formally, $\log F(x)=\log f(x)-\log g(x)$ and so
$$
\frac{F'(x)}{F(x)}=\frac{f'(x)}{f(x)}-\frac{g'(x)}{g(x)}
$$
If you have more terms, it's no different. In your case $f(x)=f_1(x)f_2(x)$ and $g(x)=g_1(x)g_2(x)$ (write down the definitions for these functions), so $\log F(x)=\log f_1(x)+\log f_2(x)-\log g_1(x)-\log g_2(x)$ and
$$
\frac{F'(x)}{F(x)}=\frac{f_1'(x)}{f_1(x)}+\frac{f_2'(x)}{f_2(x)}
-\frac{g_1'(x)}{g_1(x)}-\frac{g_2'(x)}{g_2(x)}
$$
Now just compute the derivatives and simplify.


text:
Q: Transform to anonymous function I want to convert this example code to a function. I want to do this because I have 2 input fields on the same page which have to make use of this autocomplete. I could do this the old way like I am used to, but I want to learn something about this type of programming. This is what I have now:
var Lookup = {
    init: function(field) {
        this.field = field;
        this.autocomplete = null;
        this.autocomplete = new google.maps.places.Autocomplete((document.getElementById(this.field)), {
            types: ['geocode']
        });
        this.autocomplete.addListener('place_changed', this.fillInAddress());
    },
    geolocate: function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var geolocation = {
                    lat: position.coords.latitude,
                    lng: position.coords.longitude
                };
                var circle = new google.maps.Circle({
                    center: geolocation,
                    radius: position.coords.accuracy
                });
                this.autocomplete.setBounds(circle.getBounds());
            });
        }
    },
    fillInAddress: function() {
        var place = this.autocomplete.getPlace();
        console.log(place);
    }
}

I execute this with:
$(document).ready(function () {
    Lookup.init('location_from');
    Lookup.init('location_to');
});

Everything works, the two fields have an autocomplete function. But when I select an address I get this error:

Uncaught TypeError: Cannot read property 'apply' of undefined

This is happening in the fillInAddress function. The AJAX call gets made (request extra details of the place), but then it stops. Can anyone tell me why this is?

A: I think you want to create a jQuery plugin for this task:
$.fn.extend({
    geocode: function () {
        return this.each(function () {
            var ac = new google.maps.places.Autocomplete(this), {
                types: ['geocode']
            });
            ac.addListener('place_changed', function () {
                var place = ac.getPlace();
                console.log(place);
                // ... etc ...
            });
        });
    }
});

and
$('#location_from, #location_to').geocode();


text:
Q: Signal: SIGABRT (Aborted) @ realloc i'm trying to add an extension to a c-string, but i just get Signal: SIGABRT (Aborted), can anyone tell me what's the reason for this? This is what i've done so far, the error comes @ realloc in function "prepareFileName":
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define OUT_OF_MEMORY 3
#define FILE_EXTENSION ".txt"

typedef enum _Bool_ // enum _Bool_ is a non-typedef'ed enum
{
  FALSE = 0, // Enum element
  TRUE = 1 // Enum element
} Bool; // Bool is the typedef'ed enum

Bool cStringEndsWith(const char *sourceString, const char *suffix) {
  if (!sourceString || !suffix)  // Check for not null pointer
  {
    return FALSE;
  }
  size_t length_of_c_string = strlen(sourceString);
  size_t length_of_suffix = strlen(suffix);
  if (length_of_suffix > length_of_c_string) {
    return FALSE;
  }
  int compare_result = strncmp(sourceString + length_of_c_string - length_of_suffix, suffix, length_of_suffix);
  if (compare_result == 0) {
    return TRUE;
  } else {
    return FALSE;
  }
}

int prepareFileName(char **ptr_file_name){
  int ends_with_file_extension = cStringEndsWith(*ptr_file_name, FILE_EXTENSION);
  if(!ends_with_file_extension)
  {
    char *new_ptr_file_name = realloc(*ptr_file_name, strlen(*ptr_file_name) + strlen(FILE_EXTENSION) + 1);
    if(!new_ptr_file_name)
      return OUT_OF_MEMORY;
    *ptr_file_name = new_ptr_file_name;
    strcat(*ptr_file_name, FILE_EXTENSION);
  }
}

int main()
{
  char *file_name = "testFileName";
  printf("Filename unprepared: \"%s\"", file_name);
  prepareFileName(&file_name);
  printf("Filename prepared: \"%s\"", file_name);
  return 0;
}

A: file_name is in the text segment (read only) of your program. Use malloc() + strcpy() to allocate the space on the heap.
See man realloc

Unless ptr is NULL, it must have been returned by an earlier call to
  malloc(), calloc() or realloc().


text:
Q: iphone: strange leak Can anybody help me out why this piece of code is leaking and how can we handle it?
sqlite3 *database;
if (pickerList) {
    self.pickerList=nil;
    [pickerList release];

}
self.pickerList=[[NSMutableArray alloc] init];

NSString *dbPath = [self applicationDocumentsDirectory];

dbPath=[dbPath stringByAppendingPathComponent:@"database"];
dbPath=[dbPath stringByAppendingPathComponent:@"OFFENDERSDB.sqlite"];

if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {

    if (isAlertForViolationPicker) {

        const char *sqlStatement = "SELECT * FROM VIOLATIONS_TBL";

        sqlite3_stmt *compiledStatement;

        if (sqlite3_prepare(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

            while (sqlite3_step(compiledStatement) == SQLITE_ROW) {

                NSString *recSTR=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

                [self.pickerList addObject:recSTR];
                [recSTR release];
                recSTR=nil;

            }
        }
        //[tempRowArray release];
        sqlite3_finalize(compiledStatement);
        //sqlite3_reset(compiledStatement);
        sqlite3_close(database);

    }
    else {

        const char *sqlStatement = "SELECT * FROM PLAN_TBL";
        sqlite3_stmt *compiledStatement;

        if (sqlite3_prepare(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

            while (sqlite3_step(compiledStatement) == SQLITE_ROW) {

                NSString *recSTR=[[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];

                [self.pickerList addObject:recSTR];
                [recSTR release];
                recSTR=nil;

            }
        }
        sqlite3_finalize(compiledStatement);
        sqlite3_close(database);

    }

}

sqlite3_reset(compiledStatement);

recSTR is leaking in this case and I have tried all the below mentioned solutions but none worked (updated the code)
Thanx in advance

A: It looks as though you may be leaking pickerList. You have a pointer to pickerList which you then set to nil. Then you send a release message to this point (which is in effect a no-op). If you use:
if (pickerList)
{
     [pickerList release];
     self.pickerList=nil;
}

instead of your current code, do you fare any better? Without seeing more code it's hard to say, but you definitely want to release before you set the ivar to nil. (This said if you you've done @property (retain) UIPickerList *pickerList then self.pickerList = nil will release pickerList. If you've done this then your [pickerList release] call is redundant.)
You may well get a report of a recSTR leaking from instruments. But that doesn't mean that the issue isn't with pickerList. Looking at the code, it would not unlikely that recSTR is owned by an instance of pickerList that is hanging around because you've discarded the pointer to it and then sent a release message to nil. So you'll end up with a leak of recSTR and pickerList.


text:
Q: select command in mysql returns an empty row even though the entry exist in table When I run the below query in phpmyadmin it returs 0 rows even the entry exists on the table
SELECT * FROM `default_companyshare` WHERE `comp_symbol` = "ACEDBL"

A: Try this in case you have some space-padding in your database:
SELECT * FROM `default_companyshare` WHERE `comp_symbol` like "%ACEDBL%"

You can also try trimming your result:
SELECT * FROM `default_companyshare` WHERE trim(`comp_symbol`) = "ACEDBL"

A: You clearly have some issue with the string comparison.  Start with:
SELECT *
FROM `default_companyshare`
WHERE upper(`comp_symbol`) like '%ACEDBL%';

This will show you all the symbols that contain that string.  Then figure out if the problem is leading/trailing spaces, collation conflicts, hidden characters, or something else.


text:
Q: Match number not ending with 0 I'm matching whole and fractional numbers with the following pattern:

(0|[1-9][0-9]*)(.[0-9]+)?

It matches for example the numbers:
0
1
12
12.1
12.12

But it also matches:
0.0
0.00
1.00
1.10

My question is how to modify the pattern above to disallow the match of numbers with ending zero after the decimal point.

A: Your pattern (0|[1-9][0-9]*)(.[0-9]+)? matches all examples because the second part (.[0-9]+)? does not take into account that the last match should be 1-9. Note that you have to escape the dot \. to match it literally.
You could update the second part of your pattern to match 0+ times [0-9]* and make sure that the match ends with [1-9]:
^(0|[1-9][0-9]*)(\.[0-9]*[1-9])?$

Regex demo
The pattern matches:

*

*^ Start of string

*(0|[1-9][0-9]*) Capture group, match either 0 or 1 followed by 0+ times 0-9

*( Optional capturing group to match

*

*\.[0-9]*[1-9] Match ., then 0+ times 0-9 followed by 1-9

*)?  Close group

*$ End of string

If you are for example not referring to the capturing groups for further processing you might make them non capturing (?: instead.

A: You can use the following regex:
^(0|[1-9][0-9]*)(.(?:[0-9]+[1-9]|[1-9]))?$

demo: https://regex101.com/r/ZtRg49/5
This will not match at all the following elements:
0.0
0.00
1.00
1.10

If you want to allow partial matches (not take into account the ending 0), you can use:
^(0|[1-9][0-9]*)(.(?:[0-9]+[1-9]|[1-9]))?

demo https://regex101.com/r/ZtRg49/4/
Explanations:

*

*I have added the constraint that after the . there is one digit [1-9] or several digits that can contain 0 followed by a non zero digit [1-9].

*By removing the ending anchor $ you enable partial matches

A: My suggestion to this Problem:
^\d+$|[0-9.]*?[1-9]$

Requirements to be fulfilled:

*

*Match whole numbers

*Match floating point numbers not ending on 0


text:
Q: How does one specify a row when trying to programatically create DeveloperMetadata for just a row I'm using this script to create some DeveloperMetadata for some rows. But I have to admit I don't know how to specify a complete row or column using the Sheet.getRange(row,cols,numrows,numcols) method and I keep getting the error show below.
function setupMetaData() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  for(var r=2;r<sh.getLastRow();r++) {
    let rg=sh.getRange(r,1,1,sh.getMaxColumns());//tried sh.getLastColumn()
    let lbl=Utilities.formatString('omer%s',r);//creating a label for later use
    rg.addDeveloperMetadata(lbl,SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);//get error here
  }
}

This is the error
Exception: Adding developer metadata to arbitrary ranges is not currently supported. Developer metadata may only be added to the top-level spreadsheet, an individual sheet, or an entire row or column.
I also tried to create DeveloperMetadata for the Active Row and the Active Column using these scripts and just selecting an entire row or column and that doesn't seem to get me anywhere either.
function createMetadataForActiveRow() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getActiveRange();
  let lbl=Utilities.formatString('omer%s',rg.getRow());
  rg.addDeveloperMetadata(lbl,SpreadsheetApp.DeveloperMetadataVisibility.PROJECT);
}

function createMetadataForActiveCol() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const rg=sh.getActiveRange();
  let lbl=Utilities.formatString('omec%s',rg.getColumn());
  rg.addDeveloperMetadata(lbl,SpreadsheetApp.DeveloperMetadataVisibility.PROJECT);
}

The above functions seem to run okay I not getting any errors in view logs or from the console.log
I been trying to use the following function to get the sheet  DeveloperMetadata but dmd is always returned with zero length,
function getSheetMetaData() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const dmd=sh.getDeveloperMetadata();
  var html='Developer Metadata';
  dmd.forEach((d,i)=>{html+=Utilities.formatString('
Item: %s key: %s row: %s column: %s',i+1,d.getKey(),d.getLocation().getRow(),d.getLocation().getColumn())});//always comes back with zero length
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Metadata');
}

So this may be working because I'm not actually creating any metadata but I'm not understanding why.  I must be missing something important.
In the youtube video 'Totally UnScripted' about DeveloperMetadata the speaker had access to a library and with that library he was able to create the DMD object himself by hand.  It would be nice to know if that library is available.
I just realized that library is written by Bruce McPherson so probably that library is on his website.
With Tanaike's help I'm finding the developer metadata now and the two functions that create rows and columns using the active range are working okay.
function getMetadataUsingFinder() {
  const ss=SpreadsheetApp.getActive()
  const sh=ss.getSheetByName("Sheet1");
  const f=sh.createDeveloperMetadataFinder().find();
  let html='';
  f.forEach(d=>{html+=Utilities.formatString('
key: %s row: %s',d.getKey(), d.getLocation().getLocationType())});
  SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'MetaData');
}

Here's the final script for setting up my working example for learning about how to use Developer Metadata:
function setupMetaData() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const lr=sh.getLastRow();
  for(let r=2;r<=lr;r++) {
    let rg=sh.getRange(`${r}:${r}`);
    let lbl=Utilities.formatString('omer%s',r);
    rg.addDeveloperMetadata(lbl,SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);
  }
  const lc=sh.getLastColumn();
  const colA=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
  for(let c=1;c<lc;c++) {
    let rg=sh.getRange(`${colA[c]}:${colA[c]}`);
    let lbl=Utilities.formatString('omec%s',c);
    rg.addDeveloperMetadata(lbl,SpreadsheetApp.DeveloperMetadataVisibility.DOCUMENT);
  }
  getMetadataUsingFinder();
}

A: In your 1st script, as a method, how about the following modification using A1Notation?
From:
let rg=sh.getRange(r,1,1,sh.getMaxColumns());

To:
let rg=sh.getRange(`${r}:${r}`);

*

*For example, the A1Notation of 2:2 is used, the row 2 is retrieved.

Note:

*

*In this case, when you want to retrieve the developer metadata, you can also use the following sample script. This is from this thread.
  var s = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var v = s.getRange(1, 1, s.getMaxRows(), s.getMaxColumns()).createDeveloperMetadataFinder().onIntersectingLocations().find();
  var res = v.map(function(e) {
    var loc = e.getLocation();
    var obj = loc.getLocationType() === SpreadsheetApp.DeveloperMetadataLocationType.COLUMN ? {range: loc.getColumn().getA1Notation()} :
      loc.getLocationType() === SpreadsheetApp.DeveloperMetadataLocationType.ROW ? {range: loc.getRow().getA1Notation()} : {};
    obj[e.getKey()] = e.getValue();
    return obj;
  });
  Logger.log(res)

Reference:

*

*getRange(a1Notation)