text:
Q: When new app instance launched, how to pass data to already running app instance My app architecture includes splash screen as launcher activity. Splash screen is destroyed after app is started. So, to prevent restarting app (because of launcher activity destroyed), I have added this in onCreate method for splash screen:
if (!isTaskRoot())
{
  finish();
  return;
}

So, new instance finishes itself if already running instance is there and running instance is shown. Good so far.
However, new app instance not always starts from launcher. I have set Firebase Messaging to receive push messages from my server. Push message contains some additional data, it can be accesed this way:
String messageId = getIntent().getStringExtra("id_message");

when new app instance is launched after click on push message notification. In case when app is already running, I need to show it after push notification click (it works) and then process message_id with already running app instance (new instance should finish itself). But I don't know how to pass message_id to already running instance to be able to process it and show message details without restarting entire app.
Do you have any idea?

A: You can use an intermediate Activity to choose which Activity to launch.
First, create the LaunchActivity:
public class LaunchActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.empty);

     BaseApp application = (BaseApp) this.getApplication();

    // determine where to go
    if(application.isHasGoToMain()) {
      Intent intent = new Intent(this, MainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      finish();
      startActivity(intent);
    } else {
      Intent intent = new Intent(this, SplashScreenActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      finish();
      startActivity(intent);
    }
  }
}

with the empty layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone">

</LinearLayout>

Second, create an Application to save if the main activity is already launched:
public class BaseApp extends Application {
  private boolean hasGoToMain = false;

  public boolean isHasGoToMain() {
    return hasGoToMain;
  }

  public void setHasGoToMain(boolean hasGoToMain) {
    this.hasGoToMain = hasGoToMain;
  }
}

you need to set the flag in the splash screen activity.
Third, set the LaunchActivity as the launcher in the AndroidManifest.xml and set it as hidden and singleTask:
<activity
    android:name=".LaunchActivity"
    android:screenOrientation="portrait"
    android:configChanges="orientation"
    android:launchMode="singleTask"
    android:theme="@android:style/Theme.NoDisplay"
    android:windowSoftInputMode="stateHidden">
  <intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
  </intent-filter>
</activity>

Fourth, you need to create your splash screen and main activity as singleTask too:
<activity
    android:name=".SplashScreenActivity"
    android:launchMode="singleTask"
    android:configChanges="screenSize|orientation|screenLayout">

</activity>

<activity
    android:name=".MainActivity"
    android:launchMode="singleTask"
    android:label="@string/app_name"
    android:theme="@style/AppThemeMain.NoActionBar">

Last, you need to set the flag after splash activity is launched with:
public class SplashScreenActivity extends AppCompatActivity {
  ...
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    ...

    BaseApp baseApp = (BaseApp) this.getApplication();
    baseApp.setHasGoToMain(true);
  }
}

Now you can send the intent and handle it within the onNewIntent() of the main activity.

A: First add launch mode in that activity tag in manifest file like
<activity
android:name="your_activity_name"
android:launchMode="singleTop" />

When you click on notification and you are starting any activity
if your activity is not there then a fresh activity will start.
And if that activity is already opened then its onNewIntent(Intent intent) gets called and you will receive the data you sent in this intent parameter.

A: When the push is received in the app from firebase it will be handled by MyFirebaseMessagingService. Over there you need to create a pending intent ie,the activity that needs to be opened when the user taps on the notification.
Intent resultIntent = new Intent(context, ActivityToOpen.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addNextIntentWithParentStack(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
  PendingIntent.FLAG_UPDATE_CURRENT);

Once the user clicks on the notification they will be diverted to the activity ActivityToOpen.In that activity you can put the following code
 Intent upIntent =
 NavUtils.getParentActivityIntent(ActivityToOpenOnBackPress.this);
        if (NavUtils.shouldUpRecreateTask(CurrentActivityName.this,
  upIntent))
       {

            TaskStackBuilder.create(CurrentActivityName.this)
                    .addNextIntentWithParentStack(upIntent)
                    .startActivities();
        } else {
            NavUtils.navigateUpTo(CurrentActivityName.this, upIntent);
        }

Put this code in the onBackPressed function or inside the toolbar navigation click listener.So when the user presses the back button an artificial stack is created and android handles the rest.
In the androidmanifest.xml assign a parent activity for each activity by adding the following code
android:parentActivityName=".ParentActivityName"

A: I had almost the same problem. My app starts from launcher or from intent. After adding a splashscreen activity the intent startet a second instance from the app if the app was in background.
I added android:launchMode="singleTask" to both activities in the manifest and now it works like before. Only one app instance at a time.
Doesn't make any sense to me, but as long as it works I don't care...


text:
Q: Create index on json field in PostgreSQL 9.2 I have a few tables with json columns and would like to build an index on these columns. However, I get a default operator class (http://www.postgresql.org/docs/9.2/static/sql-createopclass.html). Has someone already done that or give me an alternative?
To reproduce the problem, try:
>> create table foo (json json, id int);
CREATE TABLE
>> create index on foo (id);
CREATE INDEX
>> create index on foo (json);
ERROR:  data type json has no default operator class for access method "btree"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.

The same applies for gist or gil indexes.
Interestingly, I don't get the error when I try the following:
>> create type "nested" as (json json, extra text);
CREATE TYPE
>> create table bar (id int, json nested);
CREATE TABLE
>> create index on bar (json);
CREATE INDEX

Is that because no index is created for the components?
Okay, the main issue is the default operator. Any help or shared experience with that is appreciated.
Thanks.

A: There is a workaround for this if you feel like installing the PLV8 JavaScript language:
http://people.planetpostgresql.org/andrew/index.php?/archives/249-Using-PLV8-to-index-JSON.html

A: The solution that works best for my case is the following:
I simply treat json as text and create an index on the text.
>> create index on foo ((json::text));

A query would then have to be transformed so that it uses the index.
Explain reveals whether the index is used or not.
>> explain select * from foo where json::text = 'foo';

A: there are no internal index type for JSON or XML type. This fields can hold a values, bat it cannot be indexes - you need to auxiliary columns with hstore columns or similar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'const string& getName() const{}' vs 'string getName() const{}'? Now, this is highly conceptual. I don't know if I understand this correctly, so please help me understand the difference.
Let's assume that name is a private std::string data member that is accessed by the getName() accessor function:
const string& getName() const {
       return name;
}

Now then, this returns a reference, which is just another word for alias, to name. So, an alias is being returned, i.e. the name data member is being returned. Is this allowed or will it defeat the whole purpose of data hiding?
In other words, how exactly is the above method different to the conventional:
string getName() const {
     return name;
}

???
And finally, is it really worth implementing the former instead of the latter?

A: First of all, the reference would be problematic indeed if the underlying value could change, particularly in the context of multi-threaded execution. So it's almost a basic assumption that the value of the data member doesn't change during the lifetime of the object. That it's effectively a constant.
Now, a main problem with the reference is that it exposes an implementation detail so that it gets difficult to change the implementation.
A more academic problem is that it can break code, if there earlier was a by-value return, or just because it's unusual. E.g.
const string s& = foo().name();

With foo() returning an object by value, and name() returning a string by reference, this gives you a dangling reference instead of the naïvely expected prolonged lifetime. I call it academic because I can't imagine anyone writing that. Still, Murphy's law and all that.
It will probably not be (significantly) more efficient than a value return, precisely because it's unlikely that it's used just to initialize a reference.
So:

*

*probably not significantly more efficient,

*prevents changing implementation easily,

*also has an academic problem, yielding dangling references.
In sum, just don't.
This is premature optimization and complication.

A: The first allows callers some-what direct access to your internal name variable. Granted it's constant, so they can only call const methods on it. But still do you want external callers operating on your hidden, internal data? Even worse, what if some bozo decides to const_cast the internal data buffer of the string and hack on it?
The second returns a copy of your internal name variable. Perfectly safe for any callers to use.
I usually steer away from the first type, except for trivial, low level types. But then trivial low level types don't have much overhead for copying anyways. So that means I never write stuff like that.

A: The const reference return is better since it does not make a copy of the string. The reason I say this is because the interface is more flexible this way - you can always copy the const reference into another string if needed or you can use it as a reference - up to the caller. Returning a member byvalue and you are always stuck with making a copy. If name is big or used often, then it will impact performance and I assume performance is one of the reasons you use C++ in the first place.
Now, the other answers raise some negative points about returning a const reference, which I do not think are valid.
The concern that you can cast away the const, is valid, but casting away const is just one of the tools in the C++ developer's toolbox. Why take it away? If someone really wants to mess with your object, they can always do so in c++ by addressing memory directly so designing your code to save your callers from themselves is pointless. Casting the const away shows intent to do so and in my opinion is perfectly OK. It means that the caller has some very specific reasons to do so and knows that the const being cast away is for a non-const object and therefore - safe.
The academic example in the other answer is just silly:
const string s& = foo().name();

Again, designing your code to attempt to save the caller from themselves is limiting you from the power of C++. If one would really want to do the above, the proper way would be
string s = foo().name();

So that point is moot too.
The only valid point is that it exposes the implementation somewhat. The efficiency gains, however, outweigh this concern in my opinion.
What you really should ask yourself is this - what is the usual case of using name()?
By answering this question, you will answer which flavour you should use.
To me, the fact that it is called name implies that it will mostly be used for printing/logging and comparison. Therefore, the const reference is the clear winner here.
Also, look at the style guides out there. Most of them will have you pass by const reference and return members by const reference. There are very good reasons to do so as outlined above.


text:
Q: Equation solving using bisection method using python I wrote a python code to find root of 2*x-4 using bisection method

def func(x):
    return 2*x-4

def bisection(a,b):

    if (func(a) * func(b) >= 0):
        print("You have not assumed right a and b\n")
        return

    c = a
    while ((b-a) >= 0.01):

        c = (a+b)/2

        if (func(c) == 0.0):
            break

        if (func(c)*func(a) < 0):
            b = c
        else:
            a = c

    print("The value of root is : ","%.0f"%c)

a =-2
b = 4
bisection(a, b)

Now i want that the function input should be given by the user in the form of mx+n where m and n are integers. Can anyone help how can i do that ?

A: m, n = list(map(int, input("Please enter the value of [m] [n] for f(x) = mx +n: ").split()))

def Input():
    a, b = list(map(int, input("Enter values of [a] [b]: ").split()))
    if f(a)*f(b)<0:
        Bisection(a, b)
    else:
        print("Oops! The root of function doesn't belong to the above domain\nPlease try to again:")
        Input()

def f(x):
    return m*x + n

def Bisection(a, b):
    c = (a+b)/2
    if f(c)*f(b)<0:
        Bisection(c, b)
    elif f(c)*f(a)<0:
        Bisection(c, a)
    elif f(c)==0:
        print(c)

Input()

See we know that Bisection, Newton-Raphson, or most of all Numerical methods are the iteration processes so better we use function inside of function: f(f(f(f.....) Of course! by checking the conditions.
Here, I have used elif f(c)==0 this is something which we can't use for quadratic/cubic or higher-order polynomials because getting the exact root will not be possible for all the types of equations say like f(x) = mx^2 - n where m, n > 0 However, we can define the iterations to be performed.
By asking like Please enter the number of iterations to be performed:


text:
Q: java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null I used the following function in my code:
private fun sharedPreferences() = context.getSharedPreferences(
        "sunny_weather",
        Context.MODE_PRIVATE
    )

fun getSavedPlace(): Place {
        val placeJson = sharedPreferences().getString("place","")
        return Gson().fromJson(placeJson, Place::class.java)
    }

but the following error appear
java.lang.NullPointerException: Gson().fromJson(placeJson, Place::class.java) must not be null

i had found a similar question and according to asker's meaning, although his code isn`t similar to mine, he also write the getString function but set the second parameter to null. so his program went wrong, and after changing, his program ran well. but i had set the parameter to "", not null, but it's wrong.

A: Use "{}" for the default value:

fun getSavedPlace(): Place {
    val placeJson = sharedPreferences().getString("place","{}")
    return Gson().fromJson(placeJson, Place::class.java)
}


text:
Q: ClassLoader's getResource() method always return null in Android this method works fine in eclipse,but when i use androidStudio,it return null all the time,even i pass "" to the argument,did anyone got this problem before?
Android-Studio version is 1.5
here is the test code Log.e("itag",PropertiesConfig.class.getResource("")+"");
output is null
any advise is appreciated;

A: You can create a folder in your shared test module called resources like in the image
Usually useful to put .json file inside
Then in tests you can do:
this.javaClass.classLoader!!.getResource("test_data.json").openStream()

to get an InputStream of the file content to provide to a JSON parser

A: Why you use ClassLoader?You cann't load a .class file in android.If you had to ,you should transform .class file to .dex file ,and use DexClassLoader instead.


text:
Q: Create an iPhone app for personal use without using Xcode or going through the App Store I want to make a little app just for me. I don't want to distribute it, and don't want to make any money from it, I just need to have this app with me.
I don't have a Mac capable of running Xcode, and I don't want to waste any money on the developer license.
Is there a way I can make an app for only my personal iPhone 4s, without going through the App Store or using Xcode? My iPhone is jailbroken.

A: A web app might be a better solution.

A: The short answer is no. You would need a Mac/Xcode to compile/build the application for you. As @Thalecress suggested you might be better off building a web app.

A: Also check PhoneGap, with it you can deploy your web app in several platforms (including iOS, Android and WP7). Phonegap also offers a build service that you can use to wrap the final web app as a native app to run it on a device (PhoneGap:Buld).


text:
Q: Is there any way to run macros in background? Is there a way by which VBA can be running in the background i.e. even when the workbook is not active but the machine is on?

A: You could disable screen updating and minimize the excel file to allow a macro to "run in the background" but the excel file must be open.


text:
Q: In Python Pandas: How to reshape rows to columns without aggregation? I have some trouble reshaping my DataFrame.
Just in case someone would like to reproduce the DataFrame:
data = {
    'timestamp': ['2021-01-01', '2021-01-01', '2021-01-01', '2021-01-01', '2021-01-01', '2021-01-01'],
    'id': [1000, 1000, 1000, 1000, 1000, 1000],
    'color': ['Blue', 'Blue', 'Blue', 'Pink', 'Pink', 'Pink'],
    'a': [4598, 1479, 3547, 9811, 8746, 9856],
    'b': [1, 2, 3, 4, 5, 6],
    'c': [0.45, 0.89, 0.65, 0.06, 0.96, 0.46]
}

df = pd.DataFrame(data)

This is an extract from my DataFrame.
    timestamp    id color     a  b     c
0  2021-01-01  1000  Blue  4598  1  0.45
1  2021-01-01  1000  Blue  1479  2  0.89
2  2021-01-01  1000  Blue  3547  3  0.65
3  2021-01-01  1000  Pink  9811  4  0.06
4  2021-01-01  1000  Pink  8746  5  0.96
5  2021-01-01  1000  Pink  9856  6  0.46

What I want is this:
             Blue                     Pink
    timestamp    id  a     b  c     a     b  c     a     b  c     a     b  c     a     b  c     a     b  c
0  2021-01-01  1000  4598  1  0.45  1479  2  0.89  3547  3  0.65  9811  4  0.06  8746  5  0.96  9856  6  0.46

I tried
df = df.pivot_table(
    index = ['timestamp', 'id'],
    columns= 'color'
)

df.columns = df.columns.swaplevel(0, 1)
df.sort_index(axis=1, level=0, inplace = True)

which gave me
color            Blue               Pink
                    a  b         c     a  b         c
timestamp  id
2021-01-01 1000  3208  2  0.663333  9471  5  0.493333

Unfortunately I do not want any aggregation. Is there a way I can achieve what I want?

A: Here is a way to shape your df as you described. maybe there is a more straightforward way of achieving it. It feels strange to want a df in this shape, but I hope it makes sense for what you're trying to do
wide = (
    df.melt(
        id_vars = ['timestamp','id','color'],
        var_name = 'letter',
        value_name = 'value',
    ).set_index(['color','letter','id','timestamp'],append=True)
    .unstack()
    .unstack()
    .T
)

wide.index = wide.index.droplevel()
wide.columns = wide.columns.droplevel()

wide.loc['2021-01-01',1000]['Blue','a']

oops not actually what you want, here is what it looks like


text:
Q: PHP form passing vars I am trying to pass vars from a form using drop down lists, that are populated by a query. It currently goes to result.php
<form action="result.php" method="post">

<SELECT NAME=Model class="normal">
<OPTION VALUE=0>Phone
<?=$model_o?>
</SELECT>

<SELECT NAME=Mins  class="small">
<OPTION VALUE=0>Mins
<?=$minutes_o?>
</SELECT>

<SELECT NAME=Texts class="small">
<OPTION VALUE=0>Texts
<?=$texts_o?>
</SELECT>

<SELECT NAME=Freegifts class="big">
<OPTION VALUE=0>Choose Free Gifts
<?=$freegifts_o?>
</SELECT>

<SELECT NAME=Network class="normal">
<OPTION VALUE=0>Network
<?=$network_name_o?>
</SELECT>

<SELECT NAME=Merchant class="normal">
<OPTION VALUE=0>Contract/Prepay
<?=$merchant_category_o?>
</SELECT>

<button type="submit" value="search phones" class="red">Sumbit</button>

</form>

However, what I want it to do is pass any variables from each drop down to the URL, only if a option is selected.
For example, if Model is selected it will pass the variable on to the URL when submit is select e.g. result.php?model=iphone and if both a model and mins is selected the URL would something like e.g. result.php?model=iphone&mins=500
I hope this makes sense as I am having difficulties explaining what I am actually trying to active.
Thanks in advance :)

A: You could use JavaScript to remove any variables with zero values on submission, therefore they would not reach result.php (including the URL) as they wouldn't be in the $GET array.
You could engineer result.php so that if there are no zero values found it operates as normal but if any are found, a new URL is built containing only the other non-zero variables and result.php then could redirect back to itself.
To be honest, I wouldn't do any of the above. Since each of the drop-down menus have an option with a value of zero to begin with, you could simply ignore all zero values received in result.php, but this does not remove the variables with zero values from the URL. Think about why you want to do this. It is far more reasonable to this processing on the receiving end.

I'm assuming you meant to use GET not POST

A: For your default selections (the ones that don't count) set the value attribute to "". I believe this will indicate to the browser to not send that data along.
<select name="select1">
    <option value="">Default Selection</option>
    <option value="X">First option</option>
</select>

A: Since you're using GET, you can't have it only send form fields that have data associated with them.  Using GET will send everything about the form, including all fields, even if they don't have any data.  Are you able to parse it with Javascript or perhaps use POST instead?
Clarification
I say you're using GET despite your form tag indicating POST because of your follow up (result.php?model....).


text:
Q: All roots of the polynomial equation $x^4-4x^3+ax^2+bx+1=0$ are positive real numbers. Show that all the roots of the polynomial are equal. Suppose that all roots of the polynomial equation
$$x^4-4x^3+ax^2+bx+1=0$$
are positive real numbers. Show that all the roots of the polynomial are equal.
My work:
I assume the contraposition that all the roots are not equal.
Assume that the roots are $\alpha,\beta,\gamma,\delta$
So,$\alpha+\beta+\gamma+\delta=4$
and,$\alpha\beta\gamma\delta=1$
Here, by observation I can see that this holds for all the roots to be equal to 1, but I cannot prove it. Please help!

A: Hint : you are then in the equality case of the AM-GM inequality

A: Let $x_1$, $x_2$, $x_3$, $x_4$ be the roots of the equation
Sum of roots $x_1+x_2+x_3+x_4 = 4$
Product of roots $x_1.x_2.x_3.x_4 = 1$
We know AM > GM unless the quantities are equal
Hence $(x_1+x_2+x_3+x_4 )/4 = 1 > (x_1.x_2.x_3.x_4)^1/4$.
Therefore $x_1 = x_2 = x_3 = x_4 = 1$
Thus $x^4-4x^3+6x^2-4x+1 = 0$


text:
Q: error: conflicting types for 'whatever' I'm working on an embedded systems which provides an interface with certain types.
The problem is by including certain headers from c standard library I get an error: conflicting types
I use gettimeofday and I'm only using struct timeval, yet for using this sys/time.h also drags in time_t which interferes with the one defined by the system.
I can't touch either of those pieces of code and I need them both.
Is there a way to get around such issues? (I should be able to use the systems' declared types and some functions declared in c headers, headers which contain some declarations already done by the system.)

A: You can use macros to rename one of the time_t typedefs without modifying any headers:
#define time_t LIBC_time_t
#include <sys/time.h>
#undef time_t

#include <header_which_defines_the_time_t_you_want.h>

This is not guaranteed to work, but it does work a lot of the time.

A: One way to get around this, as a more or less last resort is to introduce another level of abstracion, and provide wrapper APIs to isolate the troublesome headers.
If you have something like this:
my_file.c:
#include <sys/time.h>
#include <some_system_header.h>

void foo(void)
{
     struct timeval tv;
     gettimeofday(&tv);
     ....
}

turns into
my_gettimeofday.c:
#include <sys/time.h> //only sys.time.h here, no system headers
#include "my_gettimeofday.h"

void my_gettimeofday(struct my_timeval *my_tv)
{
   struct timeval tv;
   gettimeofday(&tv);
   my_tv->sec  = tv.tv_sec;
   my_tv->usec = tv.tv_usec;
}

my_gettimeofday.h:
struct my_timeval {
   long sec, usec; //adjust to your platform if needed
};
void my_gettimeofday(struct my_timeval *my_tv);

my_file.c:
//no sys/time.h here.
#include <some_system_header.h>
#include "my_gettimeofday.h"
void foo(void)
{
     struct my_timeval tv;
     my_gettimeofday(&tv);
     ....
}

A: If it is only one function (gettimeofday), and one type, build a 'wrapper' function in a seperate source code file, include the correct header for the call of gettimeofday.
int my_gettimeofday(struct my_timeval *restrict tp, void *restrict tzp) {
    timeval t;
    t.time_t = my_timeval.time_t;
    // ...
    int ret = gettimeofday(&t, tzp);
    my_timeval.time_t = t.time_t;
    // .. copy the others
}

Invent the new type, struct my_timeval, which is the same contents as the one that is being conflicted with. The conflicts have been seperated.
Is that it?


text:
Q: Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause" I would like to display the column B in my below SQL, but when I add it to the query it gives me the following error:

Column T2.B'
  is invalid in the select list because it is not contained in either an
  aggregate function or the GROUP BY clause.

My code:
SELECT A, COUNT(B) as T1, B
FROM T2
WHERE ID=1
GROUP BY A

A: Put in other words, this error is telling you that SQL Server does not know which B to select from the group.
Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).

Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query
SELECT A, COUNT(B) AS T1
FROM T2
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.
However consider the following (illegal) query, which would produce this error:
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

*

*Using an aggregate
SELECT A, COUNT(B) AS T1, SUM(B) AS B
FROM T2
GROUP BY A

would return:

A  T1  B
1  2   92
2  3   68

*Adding the column to the GROUP BY list
SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A, B

would return:

A  T1  B
1  1   13
1  1   79
2  2   13
2  1   42

A: You can use case in update and SWAP as many as you want
update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

A: The consequence of this is that you may need a rather insane-looking query, e. g.,
SELECT [dbo].[tblTimeSheetExportFiles].[lngRecordID]            AS lngRecordID
          ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]  AS vcrSourceWorkbookName
          ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]      AS vcrImportFileName
          ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]       AS dtmLastWriteTime
          ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]            AS lngNRecords
          ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]          AS lngSizeOnDisk
          ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]        AS lngLastIdentity
          ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime] AS dtmImportCompletedTime
          ,MIN ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodFirstWorkDate
          ,MAX ( [tblTimeRecords].[dtmActivity_Date] )              AS dtmPeriodLastWorkDate
          ,SUM ( [tblTimeRecords].[decMan_Hours_Actual] )           AS decHoursWorked
          ,SUM ( [tblTimeRecords].[decAdjusted_Hours] )             AS decHoursBilled
      FROM [dbo].[tblTimeSheetExportFiles]
      LEFT JOIN   [dbo].[tblTimeRecords]
              ON  [dbo].[tblTimeSheetExportFiles].[lngRecordID] = [dbo].[tblTimeRecords].[lngTimeSheetExportFile]
        GROUP BY  [dbo].[tblTimeSheetExportFiles].[lngRecordID]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrSourceWorkbookName]
                 ,[dbo].[tblTimeSheetExportFiles].[vcrImportFileName]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmLastWriteTime]
                 ,[dbo].[tblTimeSheetExportFiles].[lngNRecords]
                 ,[dbo].[tblTimeSheetExportFiles].[lngSizeOnDisk]
                 ,[dbo].[tblTimeSheetExportFiles].[lngLastIdentity]
                 ,[dbo].[tblTimeSheetExportFiles].[dtmImportCompletedTime]

Since the primary table is a summary table, its primary key handles the only grouping or ordering that is truly necessary. Hence, the GROUP BY clause exists solely to satisfy the query parser.

A: I have solved this issue by adding the each group by clause which is mentioned in the error when we execute the query.
For eg: let error shows message as--
Column 'table.dealer' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Then I have added table.dealer column in the 'group by' clause as:
Group by table.dealer

Its solve my problem.

A: Add column in the group by like below:
SELECT A, COUNT(B) as T1, B
FROM T2
WHERE ID=1
GROUP BY A,B


text:
Q: Postgresql trigger not update - stack depth limit reached everyone!
i want to do a very simple trigger that sees if some conditionals are 0 they set false on the same table, buy i am doing wrong and it s not updating
CREATE or REPLACE FUNCTION chequeo_datos() RETURNS trigger AS $$
BEGIN
IF NEW.val_cuota = 0 or NEW.val_pat = 0 THEN
    UPDATE habitat SET status=False;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER chequeo_datos AFTER INSERT OR UPDATE ON public.habitat
    FOR EACH ROW EXECUTE FUNCTION chequeo_datos();

it gives me this error : "stack depth limit reached".
could you tell me what i am doing wrong?

A: Don't UPDATE the table, assign the new value to the record's column:
CREATE or REPLACE FUNCTION chequeo_datos() RETURNS trigger AS $$
BEGIN
IF NEW.val_cuota = 0 or NEW.val_pat = 0 THEN
    new.status := False;
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

For that to work, you need a BEFORE trigger:
CREATE TRIGGER chequeo_datos
    BEFORE INSERT OR UPDATE ON public.habitat
    FOR EACH ROW EXECUTE FUNCTION chequeo_datos()


text:
Q: Select DISTINCT According to Order of Another Column in Hive In Hive I have a table which looks like this:
  id | tier
  ---------
   1 | silver
   2 | silver
   3 | gold
   4 | platinum
   1 | gold
   3 | platinum

Tier is ordered ascending like silver, gold, platinum. I want to do a SELECT DISTINCT from the table such that, if an id appears more than once, the row with the highest tier is the one that's selected.
So the final table should look like this
  id | tier
  ---------
   2 | silver
   4 | platinum
   1 | gold
   3 | platinum

How can I write such a query? Thank you!

A: WITH CTE AS
    (SELECT id , tier ,ROW_NUMBER() OVER (PARTITION BY tier ORDER BY id desc) from tbalename  as rno)
SELECT id , tier from CTE where rno=1;

Link ROW_NUMBER()
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+WindowingAndAnalytics
Link CTE
https://blogs.oracle.com/taylor22/entry/hive_0_11_may_15


text:
Q: Ignore RegisterForComInterop Warning I have a VB .NET project with the msbuild task RegisterForComInterop.
This, expectedly, throws the warning
Type library "....tlb" is not registered, cannot unregister.

when building the solution the first time (and when doing a TFS team build).
I'm trying to eliminate warnings (and have a no warning policy) in the solution to improve code quality.
How can I tell msbuild to ignore this warning? It's an msbuild warning, not a compiler warning, so I can't just use the NoWarn tag in the vbproj...


text:
Q: Fuzzballs vs. black holes Now I am trying understand:
What are fuzzballs?
What is the difference between fuzzballs and black holes?
According to this presentation, one can construct fuzzball solution from ordinary BH solution in few steps:

*

*Start with standart metric, for example Schwarzschild metric:

$$
ds^2 = - \left(1-\frac{r_0}{r}\right) dt^2 + \frac{dr^2}{1-\frac{r_0}{r}} + r^2 (d\theta^2 + \sin^2 \theta d\phi^2)
$$

*Make the analytic continuation $t \to -i \tau$
$$
ds^2 =  \left(1-\frac{r_0}{r}\right) d\tau^2 + \frac{dr^2}{1-\frac{r_0}{r}} + r^2 (d\theta^2 + \sin^2 \theta d\phi^2)
$$

*Let the direction be a circle $0\le \tau \le 4\pi r_0$ and add time:

$$
ds^2 =  - dt^2 + \left(1-\frac{r_0}{r}\right) d\tau^2 + \frac{dr^2}{1-\frac{r_0}{r}} + r^2 (d\theta^2 + \sin^2 \theta d\phi^2)
$$

*Dimencionally reduce on the circle $\tau$, and obtain 3+1 dimensional metric in $(t,r,\theta, \phi)$ coupled to  scalar field $\Phi$:

$$
g_{\tau\tau} = e^{\frac{2}{\sqrt{3}} \Phi}
\;\;\;\;\;
\Rightarrow
\;\;\;\;\;
\Phi = \frac{\sqrt{3}}{2} \ln (1-\frac{r_0}{r})
$$
$$
g^E_{\mu\nu} = e^{\frac{1}{\sqrt{3}}\Phi} g_{\mu\nu}
$$
$$
ds^2_E =  - \left(1-\frac{r_0}{r}\right)^{1/2} dt^2 + \frac{dr^2}{(1-\frac{r_0}{r})^{1/2}} + r^2 \left(1-\frac{r_0}{r}\right)^{1/2}(d\theta^2 + \sin^2 \theta d\phi^2)
$$
This is solution of Einstein equations with scalar field as source:
$$
T_{\mu\nu} = \partial_\mu \Phi \partial_\nu \Phi - \frac{1}{2} g^E_{\mu\nu} \partial^\mu \Phi \partial^\nu \Phi
$$
$$
T^\mu_{\;\nu} = diag (-\rho, p_r, p_\theta , p_\phi) =  diag (-f, f, -f , -f)
$$
$$
f = \frac{3r_0^2}{8r^4(1-\frac{r_0}{r})^{3/2}}
$$
This construction looks very unnatural. Could someone explain me motivation of such strange construction?
Is the fuzzball simply solution of Einstein eqyuation with matter or more complex object?

A: Ramiro Hum-Sah comments answer well your question, but I will elaborate a bit more.
Fuzzballs are solutions of the equation of motion in string theory, that is specific configurations of strings and branes. Working in full non-perturbative string theory or M-theory is usually not feasible (yet) and anyway we may be interested in the 4D low energy description. That is why Fuzzballs are usually presented as solution of Supergravity (SUGRA), that is the low energy limit of string theory. Dimensionally reduced in 4D SUGRA appears as a gravity solution with additional vector and scalar fields, similarly to the example you mention.
The concrete difference between a fuzzball and a black hole in 4D is that while the black hole has no hairs, the fuzzballs have a non trivial multipole expansion, violating the no-hair theorem (and solving the information paradox). A fuzzball is expected to behave more like a star than a hole, meaning that it can exchange matter and information with the outside, like any other object.


text:
Q: Getting the number value of characters in a word and to do arithmetic operations with the number for encoding I just wanted to know how I can write a python program to encode a word using numbers.
for example : "World"
i want the output to be [w-d]+[o-l]+[r]
where w = 23, d =4 and so on.

A: The most analagous way to do it the way you describe it would be to use two variables left (l) and right (r) that will iterate the string and get their base values using ord(char) - ord('a') + 1:
my_string = "World"
my_string = my_string.lower()

l = 0
r = len(my_string)-1

total = 0

while (l < r):
    total += (ord(my_string[l]) - ord('a') + 1) - (ord(my_string[r]) - ord('a') + 1)
    r-=1
    l+=1
if l == r:
    total += ord(my_string[l]) - ord('a') + 1
print(total)

However, I would question if this is the best way to approach the problem. Is there a simpler ways to phrase this problem? Also when posting to stack overflow, clearly define you're problem, what steps you've taken, and what your desired output is for the given input.
See How to create a Minimal, Reproducible Example

A: What I got from your question is that you want to add even positioned letters and subtract odd positioned letters. By letter i mean, it's index in the alphabet.
So simple solution would be iterating to characters in string, getting its index on alphabet, adding to sum if even indexed, subtracting if odd indexed.
my_string = "WORLD"
my_string = my_string.lower()
sum = 0
for index in range(0, len(my_string)):
    num = ord(my_string[index])-96
    sum = (sum+num) if(index%2==0) else (sum-num)
print(sum)


text:
Q: Setting up an endpoint in an Always-On task I am currently having an issue with running a web server and a Discord bot asynchronously as an Always-On task.
On my local machine, I would use ngrok to expose my local host to receive the payloads from webhooks to be processed by my web server that is run using aiohttp, which would then have the Discord bot do different things based on the the content in the payload.
I am now looking to host this on PythonAnywhere, but am struggling to figure out how I could configure an endpoint without using ngrok. The web app on PythonAnywhere does not seem to be able to help me since it apparently does not support async.
Any help would be really useful for I have been going at it for days and still couldn't figure out a solution. Thanks in advance.


text: Q: Topological classification of the Kane-Mele model? Where should the Kane-Mele Model fall in the 10-fold way topological classification? I see that it is on a honeycomb lattice which is bipartite and thus has particle-hole symmetry. Going by that argument it should either be in the C or D class?


text:
Q: Why does my iPad keep trying to reply to ancient comments on SE chat? In the SE chat rooms in which I am most active, whenever I log in or refresh the page, it the message box appears with :1234567 or whatever already filled in.  It is trying to reply to comments from quite some time ago.  The message ID number is different from room to room, but it happens in almost every room.
I have deleted cookies, restarted, etc, all to no avail.  Mobile Safari on iOS 9.1, The url seems correct - no message ID number or anything.
How can I reset this or is it a feature/bug?


text:
Q: Does every ring with unity arise as an endomorphism ring? I don't believe that every ring with a $1$ is the endomorphism ring of an abelian group but I currently don't see how to produce a counterexample.

A: I came up with an example of an infinite ring which is not the endomorphism ring of an abelian group.
Proposition
Let $K$ be a division ring of characteristic $p > 0$.
Suppose $|K| > p \ (K$ may be an infinite division ring).
Then $K$ is not the endomorphism ring of an abelian group.
Proof:
Suppose $K$ is the endomorphism ring of an abelian group $G$.
Since $p = 0$ in $K$, $G$ can be regarded as a vector space over $F = \mathbb{Z}/p\mathbb{Z}$.
Since $|K| \neq p$, $\dim_F G > 1$.
Hence $G$ has a non-zero proper $F$-subspace $H$.
Hence there exists a non-zero proper $F$-subspace $H'$ such that $G = H \oplus H'$.
Let $f$ be the projection map $G \rightarrow H$ induced by the decomposition $G = H \oplus H'$.
Since $f$ can be regarded as an element of $K = End(G)$ and $f^2 = f$, $f = 1$.
This is a contradiction.
QED
EDIT
I found that the above idea can be applied to a division ring of characteristic $0$ except $\mathbb{Q}$.
Proposition 2
Let $K$ be a division ring.
Let $F$ be the prime subfield of $K$.
Suppose $(K \colon F) > 1$.
Then $K$ is not the endomorphism ring of an abelian group.
Proof:
Suppose $K$ is the endomorphism ring of an abelian group $G$.
Then $G$ can be regarded as as a vector space over $K$.
Hence it can be regarded as as a vector space over $F$.
Since $(K \colon F) > 1$, $\dim_F G > 1$.
Hence $G$ has a non-zero proper $F$-subspace $H$.
Hence there exists a non-zero proper $F$-subspace $H'$ such that $G = H \oplus H'$.
Let $f$ be the projection map $G \rightarrow H$ induced by the decomposition $G = H \oplus H'$.
Since $f$ can be regarded as an element of $K = End(G)$ and $f^2 = f$, $f = 1$.
This is a contradiction.
QED
EDIT 2
I found a large class of rings which are not the endomorphism rings of abelian groups.
Let $A$ be a ring.
An element $e$ of $A$ is called an idempotent if $e^2 = e$.
An idempotent which is neither $0$ nor $1$ is called a non-trivial idempotent.
If $e$ is an idempotent, $f = 1 - e$ is also an idempotent.
Lemma 1
An integral domain has no non-trivial idempotents.
Proof:
Let $A$ be an integral domain.
Let $e$ be an idempotent of $A$.
Then $e(1 - e) = 0$.
Hence $e = 0$ or $1$.
QED
Lemma 2
A local ring has no non-trivial idempotents.
Proof:
Let $A$ be a local ring.
Let $\mathfrak{m}$ be the maximal ideal of $A$.
Let $e$ be an idempotent.
If $e$ is an invertible element, $e = 1$.
Suppose $e$ is not invertible.
Then $e \in \mathfrak{m}$.
Hence $1 - e$ is invertible.
Since $1 - e$ is an idempotent, $1 - e = 1$.
Hence $e = 0$.
QED
Proposition 3 (generalization of propositions 1, 2)
Let $A$ be an algebra over a field $K$.
Let $F$ be the prime subfield of $K$.
Suppose $\dim_F A > 1$.
Suppose $A$ has no non-trivial idempotents (for example, $A$ is a division ring or an integral domain or a local ring).
Then $A$ is not the endomorphism ring of an abelian group.
Proof:
The same as the proof of proposition 2.

A: Proposition.
Let $A = \mathbb{Z}/2\mathbb{Z}\times \mathbb{Z}/2\mathbb{Z}$.
Then $A$ is not the endomorphism ring of an abelian group.
Proof:
Suppose $A$ is the endomorphism ring of an abelian group $G$.
Let $e = (1, 1)$ be the unity of $A$.
Then $2e = 0$.
Let $x \in G$.
Then $2x = 2(ex) = (2e)x = 0$.
Hence $G$ can be regarded as a vector space over a field $k = \mathbb{Z}/2\mathbb{Z}$.
Then $A = \operatorname{End}_k(G)$.
Suppose $n = \dim_k G$.
Then $|A| = 2^{n^2}$.
This is impossible.
QED


text:
Q: How to null-check a simple Function in Dart? void main() {
  Car myCar = Car(drive: slowDrive);
  myCar.drive();
}

class Car {
  Car({this.drive});
  Function? drive;
}

void slowDrive() {
  print('Driving slowly');
}

void fastDrive() {
  print('Driving fast');
}

The error says An expression whose value can be null must be null-checked before it can be dereferenced.
How can I null-check this?

A: It can be done using .call()
void main() {
  Car myCar = Car(drive: slowDrive);
  myCar.drive?.call();
}

class Car {
  Car({this.drive});
  Function? drive;
}

void slowDrive() {
  print('Driving slowly');
}

void fastDrive() {
  print('Driving fast');
}

call accepts also function with parameters
void main() {
  Car myCar = Car(drive: slowDrive);
  myCar.drive?.call(5);
}

class Car {
  Car({this.drive});
  Function(int)? drive;
}

void slowDrive(int a) {
  print('Driving slowly');
}

void fastDrive(int a) {
  print('Driving fast');
}

A: You can make the parameter drive required:
void main() {
  Car myCar = Car(drive : slowDrive);
  myCar.drive();
}

class Car {
  Car({required this.drive});
  Function drive;
}

void slowDrive() {
  print('Driving slowly');
}

void fastDrive() {
  print('Driving fast');
}

To guarantee that you never see a null parameter with a non-nullable type, the type checker requires all optional parameters to either have a nullable type or a default value. What if you want to have a named parameter with a nullable type and no default value? That would imply that you want to require the caller to always pass it. In other words, you want a parameter that is named but not optional.

https://dart.dev/null-safety/understanding-null-safety#required-named-parameters


text:
Q: json4s is faling with NPE, what can be the proper format for nested json var json= {"a1":"b","c1":"d","e1":{"f1":"g","h1":"i","j1":"k"}}
implicit val formats = org.json4s.DefaultFormats
parse(json).extract[Map[String, String]]

I am getting NullPointerException when i execute the code.
The NPE is because formats is null.
Do I need to use some different format ?

A: You can not extract like this because you are returning Map[String, String] but your input e1 contains Array. So you can use case class for extracting the value:
case class Data(a1: String, c1: String, e1: ArrayData)

case class ArrayData(f1: String, h1: String, j1: String)

def checkData : Data = {
    val json = """{"a1":"b","c1":"d","e1":{"f1":"g","h1":"i","j1":"k"}}"""
    implicit val formats = org.json4s.DefaultFormats
    parse(json).extract[Data]
  }

// output : Data(b,d,ArrayData(g,i,k))

Thanks.

A: Though it is a 4-year-old question, I wanted to give another look at the problem because converting JSON document structure is universal.
Parsing a JSON document with all fields requires a substantial amount of work. but if you don't need all the fields and the part you need is not changing, then this would be the way to extract the data needed.
var json= """{"a1":"b","c1":"d","e1":{"f1":"g","h1":"i","j1":"k"}}"""
implicit val formats = org.json4s.DefaultFormats
data=parse(json)

val a1 = (data \ "a1").extract[String]
val c1 = (data \ "c1").extract[String]

val e1 = data \ "e1"
val f1 = (e1 \ "f1").extract[String]
val h1 = (e1 \ "h1").extract[String]
val j1 = (e1 \ "j1").extract[String]

val e1 = data \ "e1" gives clue on how to handle sub objects.
@Learner's answer has a few key points though. we need a stringified JSON data to start with and we can use predefined classes if the data structure is not changing.
Remembering JSON has limited number of data types, this can be an easy task for small structures but the flexibility of JSON will make it hard when the structure grows big. Then you will either need to give up the flexible data or work hard for writing extractor classes for deep/complex data.


text:
Q: How to test AJAX with Ruby on Rails? Can somebody give advice, how to test AJAX in Ruby on Rails?
For example: i click to button, query going to TestController#new, and in that method we have respond_with(@test) and new.js.erb, where is html form. Ok, i can click_to this link/button, xhr query will work, but i don't get any responses, which i need to test.
Can some body help with this, please?
I'm using Rspec.

A: In Rails 4.2 , for send ajax request, set optional hash argument with key "xhr: true" to call of get, post, patch, put, or delete method.
For example:
get users_path + '?page=2', xhr: true

and then use assert_select for verify some HTML elements on updated page.

A: You should use Capybara and Selenium. Look at this great Railscast.

A: Depending on what your Ajax request has .. it may actually be best to test it on multiple levels.
Test your controller's response with a controller test.
Test your JS correctly dealing with this response with a pure JS testing framework like jasmine.
Test your flow through the application with something like cucumber, or an integration rspec (with the help of capybara/selenium).


text:
Q: Composer on Amazon Server ec2 - autoload not working I configured an Amazon Cloud server, installed php, apache, etc.   Then installed composer and ran $php composer.phar and its working.
But when I tried to include the vendor/autoload.php file (which I can clearly see on the server), I get this warning and fatal error because it can't seem to find the file:

Warning: require(/home/ec2-user/vendor/autoload.php): failed to open  stream: Permission denied in /var/www/html/index.php on line 12
Fatal error: require(): Failed opening required '/home/ec2-user/vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/html/index.php on line 12

Line 12 is simply:
require "/home/ec2-user/vendor/autoload.php";

Does anybody know what is causing this error or anything that would help eliminate the error?  Thanks.

A: I had the same problem, here are the steps i followed to solve it:

*

*Install composer as described in: https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html

*Copy all composer components under www root

*Change ownership of composer components to apache

*If you are using an ini file for the AWS credentials, place it under /.aws (under the root folder)

Here are the steps:
cd ~
mkdir composer
cd composer
curl -sS https://getcomposer.org/installer | php
php composer.phar require aws/aws-sdk-php
sudo cp -r ~/composer /var/www/html
sudo chown -R apache:apache /var/www/html/composer
sudo mkdir /.aws

Don't forget to copy the credentials file to ./aws.
You can also restrict read access to the credentials file to apace only:
sudo chown apahce:apache ./aws/credentials
sudo chmod 440 ./aws/credentials

Finally, update the required statement in the php file. In the example above i placed composer in its own folder so the reference would be:
require 'composer/vendor/autoload.php';


text:
Q: Cannot insert NULL into column while value is not null So im having this weird problem with trying to add an instance to the entities. Its a asp.net application using EF 6.0.
The exception:

SqlException: Cannot insert the value NULL into column 'OrderId',
  table 'BETA.MDF.dbo.Orders'; column
  does not allow nulls. INSERT fails. The statement has been terminated.

My code:
User user = (User)Session["CurrentUser"];
BetaEntities entities = new BetaEntities();

Beta.Order order = new Beta.Order();
order.OrderId = Guid.NewGuid().ToString();
order.OrderDate = DateTime.Now;
order.OrderedBy = user.UserId;
order.HandledBy = entities.Users.Where(x => x.Rank > 0).Select(i => i.UserId).FirstOrDefault();

entities.Orders.Add(order);

entities.SaveChanges();

My table:

Also this is my order class, i already tried [Databasegenerated]
public partial class Order
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string OrderId { get; set; }
    public System.DateTime OrderDate { get; set; }
    public int OrderedBy { get; set; }
    public int HandledBy { get; set; }
}

Example entry:

Please tell me if you need more details.
EDIT:
I tried setting the database datatype of OrderID to UNIQUEIDENTIEFIER and updated the entity model so the database should generate the guid(and i removed  itself but i still get the same exception.
This is my new class:
public partial class Order
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public System.Guid OrderId { get; set; }
    public System.DateTime OrderDate { get; set; }
    public int OrderedBy { get; set; }
    public int HandledBy { get; set; }
}

EDIT:
If i make OrderID NULLABALE and remove the primary key i get the following exception:
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException: 'Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.'
But this can be resolved by adding a primary key :( so removing the PK and making it NULLABLE isnt working.
Also i need to assign to GUID myself for further purposes so letting the database assign the guid itself(with [DatabaseGenerated(DatabaseGeneratedOption.Identity)]) is also not an option.

A: Your problem is that you set DatabaseGenerated attribute to the OrderId column.
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string OrderId { get; set; }

With this attribute EF will ignore value you set to OrderId and "try" generate unique value, but generating unique value will not work for string and OrderId will be NULL when INSERT query is generated.
If you are using EF "code first" then change type of OrderId to Guid and remove next line from code
order.OrderId = Guid.NewGuid().ToString();

And leave DatabaseGenerated attribute as it is.
When using DatabaseGenerated attribute for column - means that value of this column will be generated by database.
After changing your structure of Order class, you need update database accordingly. If you using "code-first" approach then you need generate migration script and run it against your database. In "database-first" approach you need update database manually
Even you said removing DatabaseGenerated attribute doesn't help, it will be most simpler solution as suggested by Ivan Stoev in the comments.
Because you generating unique string by yourself using Guid.NewGuid().ToString().


text:
Q: ASP File Object Issue I am working on an ASP classic website, which the client reported suddenly exhibited an issue with a previously working function which listed only "image" file types.  Upon reading the code, I found that the loop that lists the files in a folder, uses the InStr() function to identify files by their type, which should be "image."  However, I found that something must have changed in the OS, as the type is not longer "image", but "JPG", or "PNG", etc.  This dramatically changes the way the code works.  Following is a snipped of the code:

Set oFSO = Server.CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(Server.MapPath(sCurrentDirectoryPath))
Set oSubFolder = oFolder.Files

    iFileCount = 0

    For Each oFileName in oSubFolder

        If InStr(1, LCase(oFileName.Type),"image") > 0 Then
            iFileCount = iFileCount + 1
        End If
    Next

Because the InStr() function is trying to find a file type of "image", no files are counted up, and the function returns zero files found.  Whilst debugging, I found that the value being returned by oFileName.Type, was as follows:
This is the file type:JPG File
This is the file type:JPG File
This is the file type:Text Document
This is the file type:Data Base File
Files in the folder were two "whatever.jpg" files, a "whatever.txt" file, and a "thumbs.db" file.  So, it appears that the OS (Windows Server 2019) may have changed to be less generic with reporting an "image" file, and is now reporting "JPG file" or "PNG file", etc.  This of course, breaks this code!  Are there any suggestions from you'all on how I could go about modifying this code to work on reporting exactly how many image files are present?

A: On Windows 10, the Type values for .jpg and .png files are JPEG image and PNG image respectively. What OS are you using?
Also, Type doesn't actually analyze the file, you could have a virus.exe file in the folder that has been renamed to virus.jpg, and the Type value will still show it as JPEG. So if the function is indented to check user uploaded content to ensure images are actually images, the Type value will be of no use. If you have root access you could install a COM DLL that uses a program such as ExifTool to properly analyze files (https://github.com/as08/ClassicASP.ExifTool), however that would be a complete rewrite.
But assuming you're not looking to check if an image file is actually an image file, you could just split the filename extensions and use Select Case to count the image files if your OS is returning just XXX file and no longer XXX image in the Type value (alternatively you could split the Type value, but you'd still need to check for valid image file extensions):
Dim oFSO, oFolder, oSubFolder, oFileName, iFileCount, oFileNameSplit

Set oFSO = Server.CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(Server.MapPath(sCurrentDirectoryPath))
Set oSubFolder = oFolder.Files

    iFileCount = 0

    For Each oFileName In oSubFolder

        oFileNameSplit = Split(oFileName.Name,".")

        If uBound(oFileNameSplit) > 0 Then

            Select Case Trim(lCase(oFileNameSplit(uBound(oFileNameSplit))))

                Case "jpg", "jpeg", "png", "gif" ' Maybe add some more extensions...

                iFileCount = iFileCount + 1

            End Select

        End If

    Next

Set oFSO = Nothing
Set oFolder = Nothing
Set oSubFolder = Nothing

Response.Write(iFileCount)


text:
Q: APNS Houston gem moving to config files I want to move the following lines to my development.rb and production.rb so I don't need to change the certificate path in both production and development (reducing merge conflicts). Right now they are defined in my controller, but moving them to my config folders does nothing. Am I doing this right ?
in my development.rb
APN = Houston::Client.development
APN.certificate = File.read("/path/to/apple_push_notification.pem")

And then in my controller
         notification = Houston::Notification.new(device: phone.device_token)
         notification.alert = "Push me!"
         notification.sound = "default"
         notification.badge = 1
         APN.push(notification)

https://github.com/nomad/Houston

A: You don't need to move those files in development and production
You can even do this by placing in your controller just by checking the environment
if Rails.env.development?
  APN = Houston::Client.development
  APN.certificate = File.read("/path/to/apple_push_notification.pem")
elsif Rails.env.production?
  APN = Houston::Client.production  ## ALL you have to change this to production
  APN.certificate = File.read("/path/to/apple_push_notification.pem")
end


text:
Q: How to close the connection if the host does not respond within 5 seconds I'm trying to write program, that will check which proxies are active.
When my script tries to connect to inactive proxies, it takes up to even about 30 seconds. When I check list of thousands proxies it increases the working time of the script by a few hours.
Is it possible to break this function if it takes more than 5 seconds to respond?
def get(url, proxy):
proxies = {
    'http': 'http://'+proxy,
    'https': 'https://'+proxy
}
s = requests.Session()
s.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
s.proxies = proxies
r = s.get(url)
return [r.status_code, r.reason, r.text]

with open('proxy.txt') as ips:
for ip in ips:
    ip = ip.split('\n', 1)[0]
    try:
        get(url, ip)
        with open('working.txt', 'a') as the_file:
            the_file.write(ip+'\n')
    except:
        print("error")

Thank you.

A: Use the timeout kwarg with s.get. s.get(url, timeout=5)


text:
Q: Firebase create user swift doesn't work below I just typed is error showing "Cannot cover value of type '(,) -> Void' to expected argument type '(NSERROR!) -> Void!)'
on this line of code: what would be wrong?
FIREBASE_REF.createUser(email, password: password, withCompletionBlock: {(error,authData) -> Void in

@IBAction func creatAccountAction(sender: AnyObject) {
        let email = self.emailTextField.text
        let password = self.passwordTextField.text

        if email != "" && password != ""
        {
            FIREBASE_REF.createUser(email, password: password, withCompletionBlock: {(error,authData) -> Void in

            if error != nil {

                FIREBASE_REF.authUser(email, password: password, withCompletionBlock: { (error, authData) -> Void in

                    if error == nil {

                        NSUserDefaults.standardUserDefaults().setValue(authData.uid, forKey: "uid")
                    }
                    else {
                        print (error)
                    }
                })
            }
            else {
                print (error)
            }

            }

            )}

        else

A: Try this:
FIREBASE_REF.createUser(email, password: password, withCompletionBlock: {(error) -> Void in

This block has probably only one parameter

A: There are two options for creating a user, one just creates it and returns an error if it fails (withCompletionBlock), the other also returns the authData (withValueCompletionBlock): that's the one you want.
myRootRef.createUser(email, password: pw, withValueCompletionBlock: { error, result in

            if error != nil {
                print("error creating user")
            } else {
                let uid = result["uid"] as! String
                NSUserDefaults.standardUserDefaults().setValue(uid, forKey: "uid")
                //pass the parameters to another function to auth the user
                self.authUserWithAuthData( email, password: pw )
            }

        })


text:
Q: How to copy a Number column to VARCHAR column with leading and trailing zeros I am trying to copy Number column to VARCHAR column but its removing leading and trailing zeros. I tried with below update SQL.
UPDATE Employee  SET Salary_char = TO_CHAR(salary_num);

But its removing leading and trailing zeros. if value is 0.20 it persists .2
How to avoid this.

A: You need to provide a suitable number format model for your call to to_char(), e.g.
UPDATE Employee SET Salary_char = TO_CHAR(salary, '9999990.00')

with enough leading 9s to allow the highest value you can have in the original column.

A: Below update worked for me. It update number column values as it is in varchar column.
UPDATE Employee  SET Salary_char = TO_NUMBER(salary_num);


text:
Q: Can you explain to me how this code operates under the hood def aa(a):
    if a == 1:
        return 1
    else:
        return aa(a-1) + 1

I am able to understand the above recursion and how it is working.
However I cannot understand how this recursion is working. Can you help me?
def aa(a):
    if a == 1:
        return 1
    else:
        return aa(a-1) + aa(a-1)

I tried debugging as well. The cursor was jumping places. Didnt help me figure it out .

A: Think of this on a simple level, say with a number like 2:
def aa(a):
    if a == 1:
        return 1
    else:
        return aa(a-1) + aa(a-1)

Since 2 is greater than 1, we go straight to the else.
The else asks for us to evaluate aa(a-1) and then add aa(a-1) to it. To do this, we must first evaluate the leftmost value of this expression;
With a starting value of 2 it's easy to see that aa(a-1) is aa(2-1) or just aa(1) which will always return a value of 1 due to the first if statement. So the else will evaluate to aa(1) + aa(1) or simply 1 + 1
So what happens when we pass an initial value of 3? The logic follows like this (bold are the functions that will be evaluated on the next line):

*

*3 == 1 ? no

*aa(3-1) + aa(3-1)      // aa(2) + aa(2)

*

*2 == 1 ? no

*aa(2-1) + aa(2-1)

*

*1 == 1 ? YEP, return 1

*1 + aa(2-1)

*

*1 == 1 ? YEP, return 1

*1 + 1

*2 + aa(3-1)

*

*2 == 1 ? no

*aa(2-1) + aa(2-1)

*

*1 == 1 ? YEP, return 1

*1 + aa(2-1)

*

*1 == 1 ? YEP, return 1

*1 + 1

*2 + 2

Essentially you're evaluating the left side of the equation, and within that left side, you're evaluating a left and a right. But you evaluate the left first, then the left first etc. etc. until you finally get a result and then evaluate the right, continuing until you have an answer:

*

*left right

*

*left right

*

*value

*value right

*

*value

*value right

*

*left right

*

*value

*left right

*

*value

*value value


text:
Q: Go post a file with nested object field I need to POST the following curl command using Go
curl -X POST http://localhost:8001/routes/route_name -F "name=function" -F "config.file[1]=@my_file.lua"

I have been looking into multipart file upload examples, but I can't wrap my head around how to create a post with a nested field name (config.file is a config object with file as an array of strings) using CreateFormFile(key, val).
The problem I am having is according to the docs (https://pkg.go.dev/mime/multipart#Writer.WriteField) the WriteField API takes a field name and a value (path to file to post). I am not sure how to post a field name that is in a nested object e.g. CreateFormFile("config.file", filePath).
Anyone know how to convert the above curl command to Go using POST.


text:
Q: JRuby frozen objects versus Garbage Collector Could frozen objects in JRuby be the reason for a memory leak? Or does the Garbage Collector destroy frozen objects ?
My problem is that I have an app which has some frozen hashes running around and I did not find out just yet where they are coming from and I would really like to know if frozen objects could throw ActionView::Template::Error (GC overhead limit exceeded) or OutOfMemory Java error or at least contribute to such an error.
Thank you.

A: No. All Object#freeze does is call org::jruby::RubyObject::freeze which then calls org::jruby::RubyObject::setFrozen which sets a property on the IRubyObject.
Nothing here would have any effect on GC.


text:
Q: Error inserting date in Oracle I am trying to run this insert command
INSERT INTO DW_BATCH_HIST
(DW_BATCH_HIST.BATCH_NBR, DW_BATCH_HIST.TRANS_START_DATE, DW_BATCH_HIST.BATCH_STATUS)
VALUES(82,to_date('27-SEPT-2012 11:00:00.000','DD-MON-YYYY hh:mi:ss'), 1)

I get this error:

ORA-01841: (full) year must be between -4713 and +9999, and not be 0

The year is a valid year, so I don't understand why I am getting this error. What am I missing?

A: The month for the MON portion of the mask should be a three letter abbreviation, not four as you have it.
EDIT: As pointed out by others, the milliseconds should be removed as well.
'27-SEP-2012 11:00:00'

A: If you want to stay on the safe side with date / time formatting in Oracle (and most other databases), use the SQL standard timestamp literal format. In your case, write
TIMESTAMP '2012-09-27 11:00:00.000'

If that's not an option, fix your date as such:
to_date('27-SEP-2012 11:00:00','DD-MON-YYYY hh:mi:ss')
-- removed the T from SEPT, as well as the millisecond part

A: Change 'SEPT' to 'SEP' and remove the milliseconds from the time value.


text:
Q: URL Parameters in MVCReportViewer As you know, In SQL Server reporting service (SSRS), We can pass the parameters with URL (URL Access Syntax) and we can provide data source credentials in a URL by including the dsu:datasourcename=value & dsp:datasourcename=value (Setting Data Source Credentials in a URL).
Now, I want to open a report in my web application with dynamic data source credencial.
I'm using MVCReportViewer and when I set the MvcReportViewerFluent:ReportServerUrl parameter as http://ServerName/reportserver/?dsu:myDS=user&dsp:myDS=password, I get the blank page in iFrame.
When I remove "/?dsu:myDS=user&dsp:myDS=password", The report work correctly and ask user name and password inside the report.
Where am I going wrong?
Edit: Codes Added
Controller Code :
public ActionResult Index()
{
    var model = new {
        UserName = "user",
        Password = "pass",
        ReportPath = "/myReportPath",
        ServerUrl = "http://ServerAddress/reportserver/?dsu:ddst=pdm&dsp:ddst=pdm",
        Parameters = null,
        FormMethod = FormMethod.Post,
        HtmlAttributes = new { Height = 900, Width = 900, style = "border: none" }
    }
    return View(model);
}

View Code:
@Html.MvcReportViewerFluent(Model.ReportPath)
     .ReportServerUrl(Model.ServerUrl)
     .Username(Model.UserName)
     .Password(Model.Password)
     .Method(Model.FormMethod)
     .ReportParameters(Model.FormMethod)
     .Attributes(Model.HtmlAttributes).


text:
Q: restricting regex code in Notepad++ I have a database compiled with Notepad++. After some 10000 records (lines) I decided to add an extra one in the database to separate City, which includes the state The field "City looks like this "Dallas TX" and I wanted it in TWO columns "Dallas" "TX".
For instance
from
CR.jpg,Courtyard,USA,St George UT,y,n,n
to
CR.jpg,Courtyard,USA,St George, UT,y,n,n
Notice the comma after St George
I needed to REPLACE the SPACE between City and State with a COMMA
and I achieved that in Notepad by searching [ \t]+ and replacing with
,

but… a problem remains: in cities like New York I do not want a comma in between New and York.
Is there a way of coding to restrict the adding of the comma ONLY when it appears JUST before two capital letters, e.g. TX, NY, NV, etc?

A: Try replacing
\s([A-Z]{2},)

With
,$1

This looks for a space, exactly two letters, and a comma. It replaces the space with a comma and leaves the rest alone.
Here's a working demo.


text:
Q: NGINX proxy_pass to ELB with Variable I am trying to setup a proxy rule for nginx that will hit an internal loadbalancer in front of some node boxes serving an API. I want to use a variable in the address to force it to resolve because of how dynamic the addresses are in aws.
The original setup works fine but occasionally was pointing to an addresss that was no longer there which caused intermittent problems as would be expected:
location /protected/ {
  proxy_pass http://my-internal-aws-loadbalancer.com:8083/protected/;
}

This however produces gives a 404 error when I hit the same route:
location /protected/ {
  set $node "my-internal-aws-loadbalancer";
  proxy_pass http://$node:8083/protected/;
}

Also one thing to note is this is a post request. I guess I am just very confused as to why the addition of the variable breaks this.

A: So ... after a lot of looking and reading I believe I have this solved. When using a variable in the proxy_pass nginx does in fact not behave the same.
This article was extremely helpful. TLDR of the whole article in regards to this case is the addition of the variable does cause nginx to behave differently on the proxy_pass so removing the trailing slash from the variable URL and rewriting any thing that could come after it solves the issue.
location ~ ^/protected/(.*)$ {
  resolver 8.8.8.8;
  set $node "http:///my-internal-aws-loadbalancer.com:8083/";
  proxy_pass $node/protected/$1;
}


text:
Q: Adding a range to a Listbox I have an array with about 5 items in it that I need to set in a listbox, lets say (5,1,71,221,453) and I want to just add them without making a whole For each or whatever loop.
Is there a way that I can set multiple items to a listbox at once in VB.net? without iterating through them?

A: You can try:
ListBox1.Items.AddRange({5, 1, 71, 221, 453}.Cast(Of Object).ToArray)

If using an existing array, try:
ListBox1.Items.AddRange(myarray.Cast(Of Object).ToArray)


text:
Q: django model field for sets of values I have a django model called Product. I wish to have a set of values. Specifically, each product will have different sizes (say 500 mg, 1 g, bulk order; the specific sizes will be differ for each product), along with it, I should have corresponding cost. For example,

*

*1g - $500;

*5g - $1500;

*bulk order -ask for quote;

For another product, this could be:

*

*100ml - $100;

*200ml -$170;

*1L -$1000;

I could use something like:
size1 = models.CharField(max_length=200)
price1 = models.DecimalField
size2 = models.CharField(max_length=200)
price2 = models.DecimalField
size3 = models.CharField(max_length=200)
price3 = models.DecimalField

Is there a better way of achieving this? Is there something like sets field? Thanks!

A: Create another model - Size:
class Size(models.Model):
    product = models.ForeignKey(Product, on_delete = models.CASCADE)
    value = models.IntegerField(blank=True, null=True)
    units = models.CharField(blank=True, null=True)
    sequence = models.IntegerField()
    price = models.FloatField(blank=True, null=True)
    notes = models.CharField(blank=True, null=True)

This way you can create as many sizes as you want, sequence will indicate the order number of a Size object belonging to the product. If you want to just note about bulk order, then just fill the notes notes = 'bulk order - ask for quote' and skip units, value and price, those will be None by default.

A: class Product(models.Model):
   .....
   .....

class Price(models.Model):
    prodcut = models.ForeignKey(Product)
    TYPE_CHOICES = (
    (1, "Gram"),
    (2, "ML"),
    (3, "L"),
    )
    quanty_type = models.IntegerField(choices=TYPE_CHOICES, default=1)
    quanty = models.CharField(max_length=200)
    price = models.DecimalField()


text:
Q: Como disparar um método ao terminar de editar uma coluna do tipo Inteiro na JTable Preciso chamar um método que mostre para o usuário uma mensagem qualquer.
Este método deve ser chamado no exato momento em que o usuário terminar de editar uma coluna da JTable do tipo Inteiro e o usuário não tiver digitado um número inteiro.
Ou seja, o método deve ser chamado no momento em que a coluna ficar 'vermelha'.
Abaixo vou colocar  uma imagem de exemplo que o articuno usou em um de  seus posts, apenas para  exemplificar quando o evento devera ser chamado.

Abaixo está o código que  estou desenvolvendo.
 public class Dados {
        /**
         * @return the coluna0
         */
        public String getColuna0() {
            return coluna0;
        }
        /**
         * @param coluna0 the coluna0 to set
         */
        public void setColuna0(String coluna0) {
            this.coluna0 = coluna0;
        }
        /**
         * @return the colunaInteiro
         */
        public Integer getColunaInteiro() {
            return colunaInteiro;
        }
        /**
         * @param colunaInteiro the colunaInteiro to set
         */
        public void setColunaInteiro(Integer colunaInteiro) {
            this.colunaInteiro = colunaInteiro;
        }
        private String coluna0;
        private Integer colunaInteiro;
    }

.
public class TesteTableModel extends AbstractTableModel {

    private String colunas[] = {"Coluna0", "colunaInteiro"};
    private List<Dados> dados;
    private final int COLUNA_0 = 0;
    private final int COLUNA_INTEIRO = 1;

    public TesteTableModel(List<Dados> dados) {
        this.dados = dados;
    }

    //retorna se a célula é editável ou não
    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return true;
    }

    //retorna o total de itens(que virarão linhas) da nossa lista
    @Override
    public int getRowCount() {
        return dados.size();
    }

    //retorna o total de colunas da tabela
    @Override
    public int getColumnCount() {
        return colunas.length;
    }

    //retorna o nome da coluna de acordo com seu indice
    @Override
    public String getColumnName(int indice) {
        return colunas[indice];
    }

    //determina o tipo de dado da coluna conforme seu indice
    @Override
    public Class<?> getColumnClass(int columnIndex) {
        switch (columnIndex) {
            case COLUNA_0:
                return String.class;
            case COLUNA_INTEIRO:
                return Integer.class;
            default:
                return String.class;
        }
    }
    //preenche cada célula da tabela
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Dados dados = this.dados.get(rowIndex);
        switch (columnIndex) {
            case COLUNA_0:
                return dados.getColuna0();
            case COLUNA_INTEIRO:
                return dados.getColunaInteiro();
            default:
                return null;
        }
    }
}

.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class GuiPrincipal extends JFrame {

    private JTable table;
    List<Dados> dados = new ArrayList<Dados>();

    public GuiPrincipal(JTable table) throws HeadlessException {
        this.table = table;
    }

    public void addDadosInDados() {
        Dados dado = new Dados();
        dado.setColuna0("Dado qualquer");
        dado.setColunaInteiro(1);
        dados.add(dado);
    }

    public GuiPrincipal() {
        setLayout(new FlowLayout());
        setSize(new Dimension(700, 300));
        setLocationRelativeTo(null);
        setTitle("Exemplo JTable");
        addDadosInDados();// add dados em dados
        table = new JTable(new TesteTableModel(dados));
        table.setShowVerticalLines(false);
        table.setIntercellSpacing(new Dimension(0, 0));
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane);
    }

    // este é o método onde é executado nosso programa
    public static void main(String[] args) {
        GuiPrincipal gui = new GuiPrincipal();
        gui.setVisible(true);
    }
}

Como faço para disparar um método neste exato momento?

A: Tente aplicar umas das formas sugeridas abaixo:
1 - Utilizando PropertyChangeListener
É possível monitorar quando houver alguma edição de célula na tabela, adicionando um PropertyChangeListener a ela, filtrando apenas quando houver notificação de listeners de edição de células:
table.addPropertyChangeListener(e -> {

    if("tableCellEditor".equals(e.getPropertyName())) {
        if(!table.isEditing())
            JOptionPane.showMessageDialog(this,"fim da edição em alguma celula");
    }
});

Um problema dessa forma é que entrará na condicional sempre que qualquer célula da tabela sair do modo de edição.

2 - Utilizando um TableCellEditor
Esta forma é um pouco mais complicada, pois em situações onde se tem um tipo especifico de dados na coluna, pode ser necessário a criação de um TableCellEditor próprio, como pode ser visto neste exemplo de outra resposta, mas para simplificar a demonstração, utilizei a classe DefaultTableCellEditor.
class ShowMessageCellEditor extends DefaultCellEditor{

    public ShowMessageCellEditor(JTextField textField) {
        super(textField);
    }

    @Override
    public boolean stopCellEditing() {
        JOptionPane.showMessageDialog(null, "celula modificada");
        return super.stopCellEditing();
    }
}

E para aplicar na coluna específica:
table.getColumnModel().getColumn(1).setCellEditor(new ShowMessageCellEditor(new JTextField()));

No método getColumn(index) você deve passar o índice da coluna da tabela que quer que ocorra a ação ao terminar a edição. Lembre-se que índices em java iniciam em 0 e não 1.
As colunas de uma JTable utilizam editores que implementam a interface CellEditor, e essa interface possui o método stopCellEditing(), que detecta quando a edição na célula foi interrompida, e aceita a alteração realizada, mesmo que seja parcial, notificando em seguida todos os ouvintes de que aquela célula não está mais em modo de edição.
Anteriormente, a versão estava utilizando fireEditingStopped(), mas a função deste método é apenas notificar ouvintes do evento ocorrido, é dentro do stopCellEditing() que você deve disparar seu método.

Referencias:

*

*SWING JTable, cell start to edit event

*Concepts: Editors and Renderers(tutorial oracle)


text:
Q: Difference between array in row and columns I'm trying to move the content of column B3:B11 (range) to a column determined by the number of day in month at cell C3 (day). For each day in month (reeksorg) cell D2 contains: 1, E2: 2, F2: 3; up-to 31.
function Move() {
var sss = SpreadsheetApp.getActiveSpreadsheet();  // get present workbook
var ss = sss.getSheetByName('Sheet1'); //get active sheet
var range = ss.getRange('B3:B11').getValues(); //assign the range you want
// to copy

var day = ss.getRange('C3').getValues();  // day from date(C1)

Logger.log(day);             // this is correct in Log
Logger.log(range);           // idem
Logger.log(range.length);    // idem

var reeksorg = ss.getRange('D2:H2').getValues(); // "reeksorg" are day-
// numbers within month

Logger.log(reeksorg);         // returns "range", should be [[1.0],[2.0]]
//  etc.
Logger.log(reeksorg.length);  // returns [1.0],  should be [5.0]
}

Although the statements to create both ranges are similar the outcome differs.
See Log-output:

[17-08-18 16:04:21:095 CEST] [[3.0]]
[17-08-18 16:04:21:095 CEST] [[5.0], [6.0], [7.0], [8.0], [9.0], [10.0],
     [11.0], [12.0], [13.0]]
[17-08-18 16:04:21:096 CEST] 9.0
[17-08-18 16:04:21:198 CEST] [[1.0, 2.0, 3.0, 4.0, 5.0]]
[17-08-18 16:04:21:198 CEST] 1.0

My goal is to copy "range" to the appropriate row/column (D3:H11) using a for loop.
Please help, i've limited programming knowledge.

A: How about this?
function Move()
{
  var sss=SpreadsheetApp.getActiveSpreadsheet();
  var ss=sss.getSheetByName('Sheet1');
  var srcrange=ss.getRange('B3:B11');
  var day=ss.getRange('C3').getValue();// day from date(C1)
  var desrange=ss.getRange(3,day,10,1);
  srcrange.copyTo(desRange);
}


text:
Q: Cloudflare 525 error code and port scan Today, Cloudflare return code 525 for some https connections.
And I see many connections in iftop on the origin server. This connections - port scan.
I used iptables, and block all packets, not from 22, 80, 443 ports, but sometimes I get 525 code from Cloudflare anyway.
Any tips?

A: First, check Cloudflare Status and DownDetector, There was an outage caused at Cloudflare itself, a few days ago.
Second, Cloudfalre provides documentation on Fixing Error 525: SSL handshake failed, e.g.

*

*Make sure you have a valid SSL certificate installed on your origin server.

*Check with your hosting provider to make sure they're listening on port 443.

*Check to make sure your origin server is properly configured for SNI.

*Be sure the cipher suites your server uses match what is supported by Cloudflare.

*If the errors are intermittent, it might be that the TCP connection between Cloudflare and your origin is being reset during the SSL handshake. Ask your hosting provider/system administrator to check if there are any server issues... [and check Cloudflare status].


text:
Q: SharePoint designer 2013 workflow "send email" not working We created normal workflow "Send email" using SharePoint 2013 workflow. But we are not receiving emails. We tried same with SharePoint 2010 workflow and its working. We also tried alerts me on the list and sharing site, everything working fine means we are receiving emails. Except SharePoint 2013 workflow emails sending to mailbox are coming. Start task process workflow also created and also all tasks has been completed successfully but email are not received.
We checked SMTP server, everything configured correctly.
User Profile full sync was working fine and users are syncing from AD.
Note:We are suing SharePoint 2013 environment.
SP experts, Please suggest us.

A: Please check if "send mail" action does not work in both SharePoint workflow 2010 platform and SharePoint 2013 platform.
Please add the actions "log to history" before and after action "send mail" to check if the send mail action is performed.
And you can also add "pause for a duration" before the "send mail" action, see if it could help.
You may also check if there are some related ULS log.
And also try to hard code the email id rather picking from AD... and see the result.
Reference URL :
https://social.technet.microsoft.com/Forums/lync/en-US/3c76459c-01f5-4d75-be17-ee5b2ce1c1dd/sharepoint-designer-2013-workflow-not-sending-emails?forum=sharepointgeneral


text:
Q: Catch Soap response message c# .net I have a Service Reference to communicate with WCF.
Now I can send the message with a method to the server. *
But I can't catch the response message. The request is fine, because I can handle the message with Fiddler Classic, but i need to handle it with c#.
Here is my code:
ServiceReference1.PUPHAXWSPortTypeClient client = new ServiceReference1.PUPHAXWSPortTypeClient();
        client.ClientCredentials.HttpDigest.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
        client.ClientCredentials.HttpDigest.ClientCredential.UserName = "PUPHAX";
        client.ClientCredentials.HttpDigest.ClientCredential.Password = "puphax";
        await client.TABATCAsync("<ATC>N05BA%</ATC>"); //* this method

If i want to storage the data to a variable or ServiceReference1.TABATCResponse tABATCRequest i got an exception which is invalid UTF-8 bytes.
Sorry for my english, here is the service reference: http://neak.gov.hu//data/cms1030808/PUPHAXWS_v1.22.wsdl


text:
Q: Too few arguments to function woocommerce_update_product_acf_save_post() I have an action in my functions.php to inform subscribers of an product update. I have a working function that accepts 2 arguments ($product_id and $product). However when I
press update on a product an e-mail goes out with the old values of my ACFs.
add_action('woocommerce_update_product', 'action_on_product_save', 20, 2);

function action_on_product_save($product_id, $product) {
    $updating_product_id = 'update_product_' . $product_id;
    if (false === ($updating_product = get_transient($updating_product_id))) {

I found a topic from someone with the same issue, but this solution won't accept 2 arguments for some reason (probably my fault).
this is the code I found online which works if I uncomment all the $product related content further down. So with the code below my e-mail shows the updated ACF straight away. However without the productname as I can't add the $product argument without getting the Fatal error (see below)
add_action('acf/save_post', 'woocommerce_update_product_acf_save_post', 1000, 1);

function woocommerce_update_product_acf_save_post( $product_id ) {
    if (get_post_type($product_id) == "product") {
        remove_action('acf/save_post', 'woocommerce_update_product_acf_save_post');
        update_on_product_save( $product_id );
    }
}

function update_on_product_save($product_id) {

When I add the second argument however (see me change the arguments value to 2 below)
add_action('acf/save_post', 'woocommerce_update_product_acf_save_post', 1000, 2);

function woocommerce_update_product_acf_save_post( $product_id, $product ) {
    if (get_post_type($product_id) == "product") {
        remove_action('acf/save_post', 'woocommerce_update_product_acf_save_post');
        update_on_product_save( $product_id, $product );
    }
}

function update_on_product_save($product_id, $product ) {

I get an error;
Uncaught ArgumentCountError: Too few arguments to function woocommerce_update_product_acf_save_post(), 1 passed in /home/domain/public_html/wp-includes/class-wp-hook.php on line 307 and exactly 2 expected in /home/domain/public_html/wp-content/themes/hello-elementor-child/functions.php:50, referer: https://www.domain.com/wp-admin/post.php?post=7398&action=edit

A: I got it working with this! :)
function update_on_product_save($product_id) {

    global $product;
    $product = wc_get_product( $product_id );
    $product_title = $product->get_name();
    $product_image_id = $product->get_image_id();


text:
Q: CSS mystery: why the extra height in my div's? I'm just starting in on a new site and am getting extra space at the top of the div's I'm building for the home page. Using Safari's Web Inspector, I've eliminated any obvious padding or margins being responsible; but it's also seemingly telling me that the height of the div's is, for some reason, set to a greater amount than the image which should be its maximum height.
Sigh.... 10 minutes in and I'm already banging my head against my desk. Well, about to anyway.
This is the very-much-in-progress site:
http://compassionglobally.org/wordpress/
You can see a black strip above the first area and a grey one above the second area. I can't figure out where that space is coming from. And it's really bothering me.
I am using a WordPress theme which I realize may be interfering in my formatting, but I suspect that this isn't really the issue.
I removed all spaces and carriage returns since I know that this can cause space to be inserted, but it hasn't helped. I hope another set of eyes can!
Thanks!

A: It comes from the paragraph margin. Probably the easiest way to fix it (without removing the margins) is to wrap those paragraphs inside a container or to do something like this to the .homeStripContent:
.homeStripContent {
  float: left;
  width: 100%;
}

Or just to negate the top margin: .homeStripContent {margin-top: -28px;}

A: Adam
Maybe you just remove the blank

 that you really don't need it.
remove that

 after the .
And your layout will be good.
Take a look(which

 you should remove it.)


text:
Q: Como fazer insert no banco para formulários na mesma página? Estou testando um form antes de colocar na produção, porque já temos um sistema que insere a movimentação de patrimônio 1 a 1 e estou querendo fazer com que o operador consiga fazer várias ao mesmo tempo, por exemplo, vai mover 5 impressoras pro mesmo lugar que ele não tenha que fazer o processo 5 vezes...

então ele diz quantos produtos vai movimentar e clica em enviar e abre o número de formulários desejado

Minha dúvida é : Como eu faço para que quando ele clique no primeiro botão gravar ele faça o update no banco sem sair da página e se não for pedir muito, aparecer uma mensagem de inserido no 'quadrado' que clicou em gravar porque quem vai operar isso, não tem muita facilidade com computadores. Segue o código.
    <?php

$produtos = $_POST['produtos']

?>

<?php

 for ($i=0; $i < $produtos; $i++) {
   # code...
?>

                    <form>

                            Patrimonio
                            <input name="data[PessoaEmail][0][email_tipo_id]" required="required" id="PessoaEmail0EmailTipoId" type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email">

                            Teste
                            <input type="text" class="form-control" name="data[PessoaEmail][0][email_tipo_id]" required="required" id="PessoaEmail0EmailTipoId" placeholder="teste">

                      <button type="submit" class="btn btn-success btn-sm">Gravar</button>

                    </form>

<?php } ?>

A: Se seu problema for apenas quando clicar no botão enviar não quer que a pagina recarregue tu pode usar o Javascript o método preventDefault(), mas caso sua dúvida seja outra, tente deixar mais clara para que possamos te ajudar.

A: tira os campos de dentro do form e usa ajax para enviar os dados.
quando você tem um button type="submit" dentro de um form, sempre que o button type="submit" for acionado, ele vai atualizar a pagina e enviar os dados dos input dentro daquele form


text:
Q: Use inline SVG with HTML5 as a background in a DIV element I'm not very familiar with svgs. Please suggest anything I could use for the following situation.
I have two divs like the following. The first div generates an svg and the second div is a normal div. I want to use the SVG which is generating from the first div as the background for the second div(main-div). I don't want to use absolute/fixed positioning in here. Is there any way to do that except use positioning?

  <svg viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;">
    <path d="M0.00,49.99 C150.00,150.00 349.21,-49.99 500.00,49.99 L500.00,150.00 L0.00,150.00 Z" style="stroke: none; fill: #08f;"></path>
  </svg>

a

b

Thank you

A: The best would be to save SVG into an SVG file as it will be the most flexible for all browser.
After you can use the position even though you don't want.
Finaly after searching a bit more, I found out a subject using URI here.
But pay attention that it might not work in all browser (specialy olds ones).
So I search for a URI-Converter to SVG.
And the output is:
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 500 150' preserveAspectRatio='none' style='height: 100%25; width: 100%25;'%3E%3Cpath d='M0.00,49.99 C150.00,150.00 349.21,-49.99 500.00,49.99 L500.00,150.00 L0.00,150.00 Z' style='stroke: none; fill: %2308f;'%3E%3C/path%3E%3C/svg%3E");

Demo

.svg-div{
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 500 150' preserveAspectRatio='none' style='height: 100%25; width: 100%25;'%3E%3Cpath d='M0.00,49.99 C150.00,150.00 349.21,-49.99 500.00,49.99 L500.00,150.00 L0.00,150.00 Z' style='stroke: none; fill: %2308f;'%3E%3C/path%3E%3C/svg%3E");
}

a

b

A: *

*Firstly, you need to add xmlns="http://www.w3.org/2000/svg" to your svg element.

*Then, use the following JavaScript to set the background image.

var svg = document.getElementsByTagName('svg')[0];
var svgCode = window.btoa(svg.outerHTML);

document.getElementById('main-div').style.backgroundImage = "url(data:image/svg+xml;base64," + svgCode + ")";

  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 500 150" preserveAspectRatio="none" style="height: 100%; width: 100%;">
<path d="M0.00,49.99 C150.00,150.00 349.21,-49.99 500.00,49.99 L500.00,150.00 L0.00,150.00 Z" style="stroke: none; fill: #08f;"></path>
</svg>

a

b

Read this to understand why xmlns is required.


text:
Q: Get Job id and put them into a bash command Hello for a projet I need to execute a bash file only when all previous run have been finished so I use :
sbatch -d afterok:$JobID1:$JobID2:$JobIDN final.sh

in Order to run the JobIDN I do
for job in Job*.sh ; do sbatch $job; done

Then it prints all the jobIDs
I just wondered if someone haave a command in order to grab these IDs and put them directly to the command :
sbatch -d afterok:$JobID1:$JobID2:$JobIDN final.sh

exemple
for job in Job*.sh ; do sbatch $job; done
1
2
3

sbatch -d afterok:$1:$2:$3 final.sh

A: You can store the job ids in a variable and use it for your next command. Something like
jobs=$(seq 1 10 | awk '{ printf ":%s", $1 }')
     # \------/
 # your jobID printing function here

And then
sbatch -d afterok"$jobs" final.sh

A: You can do it with
for job in Job*.sh ; do sbatch --parsable $job; done | paste -s -d: | xargs -I{} sbatch --depedency afterok:{} final.sh

The paste command will gather all job IDS and write them on a single line, colon-separated, while xargs will take the result and insert it at the {} placeholder. The information about the job IDs is passed through pipes.


text:
Q: Best practice for accessing command line arguments globally in Java What's the best way to store a global setting passed to a Java program from the command line? for example if you were to run >Java myProgram -verbose I want to be able to know whether or not verbose was specified in all the private functions. It feels wrong to add five or ten parameters to every function just to pass the necessary variables along, but I've also been reading that global variables in Java are the work of the devil, even if they are only set once. This must be an extremely common issue but I haven't been able to find anything that explains the best way to deal with it and I'd appreciate if someone can point me in the right direction.

A: Global Variables are never the work of the devil in any language. Instead, they're more like a rubix cube.
If you know the absolute best ways to use them, you'll rarely run into a problem you can't solve. If you know the basic ways to use them, you'll get through it, but it will take a while to get everything to line up right. If you don't know how to use them, they'll just make for a pretty collection of colored squares...
The thing to keep in mind is that most times you need to use a global variable, you could instead use with dependency injection. It will have less bugs and probably yield the same results. The code will also be cleaner, which is always good.
Instead of adding 10 variables to your methods, why not add those variables to your class? Why not store them inside their own container so they're grouped logically?
For more information and implementation, I'd need to see more background.

A: Use the context object pattern.


text:
Q: Is there a penalty to interrupting training? I have several dwellers who train high SPECIAL attributes, but are needed elsewhere at times (someone has to keep the lights on).
I have noticed that, most of the time (I haven't checked for all scenarios), training times resume back where I left them if the dweller was interrupted or made to work elsewhere; it is as if the system is tracking how much training has been done and getting the dweller back on track.
Is training investment wasted on a dweller if it is interrupted for significant amounts of time for other tasks (including death and exploration)?

A: Dweller training is NOT wasted if you move them before it is finished. You might notice some discrepancies between the time left when you move them out and when you move them back in if you have a different number of dwellers in the room, or upgrade the room while they are gone.
For training, the more dwellers in the room, the faster everyone trains, though the gains are only about 10-20% reductions at best. If you have someone with 5 minutes left in training room A along with 5 others, and someone by themselves in training room B with 12 hours left it might be worth switching him,  though that depends to some extent on when you'll next check in.


text:
Q: VSCode navigation keybinding for command picker Does anyone know whether there is a keybinding to navigate up and down in VSCode's Command Picker(Ctrl+Shift+P).

I can navigate using the up arrow and down arrow buttons, but I want to bind up and down to ctrl+i, ctrl+j.

There seems like navigation keybinding for QuickOpen workbench.action.quickOpenNavigateNext but I can't find one for Show All Commands palette

A: I've managed to solve this by changing the Navigate Previous in Quick Open and Navigate Next in Quick Open to your choice of keys respectively.