text:
Q: Disappearing of different pictures on hosting I have more than 50 images on my website. I pull them all with ajax. My problem is it gives 404 not found error after 30 images.
I changed the formats of the images. I reduced the dimensions but in vain... I can access the pictures one by one in the new tab. I couldn't understand what the problem was. I am listing images dynamically. This issue does not exist on localhost. I only get an error when I upload it to the hosting panel.
The technologies I use are available in the tag.

A:
I can share code but i dont think that its happening bcs of it. because i published same website to another plesk account. There is no problem

I think that, it's the same problem as I had before. if you are requesting images from different domain. This issue can be because of hotlink protection.
if this images in your current domain and as you said. if you can access all images in new tab etc. I have doubt about ddos protection. I changed ddos protection settings in my plesk panel and  problem was gone...  you can uncheck this protection or increase limitation.

Prevent Ddos attacks with IIS dynamic IP limitation
Deny IP addresses based on number of simultaneous requests from a unique IP address

you can uncheck this protection or increase limitation. Ask your hosting  provider maybe you don't need this option


text:
Q: could to find or load main class org.apache.nutch.crawl.InjectorJob I'm using Linux with Hadoop, Cloudera and HBase.
Could you tell me how to correct this error?
Error: could to find or load main class org.apache.nutch.crawl.InjectorJob
The following command gave me the error:
src/bin/nutch inject crawl/crawldb dmoz/

if you need any other information ask for me.

A: I think you probably missed a step or two. Please confirm:

*

*Did you install Apache ANT and then navigate to the nutch folder and type in "ant"?

*Did you set the environment variables:

*

*NUTCH_JAVA_HOME: The java implementation to use.  Overrides JAVA_HOME.

*NUTCH_HEAPSIZE: The maximum amount of heap to use, in MB. Default is 1000.

*NUTCH_OPTS: Extra Java runtime options.Multiple options must be separated by white space.

*NUTCH_LOG_DIR: Log directory (default: $NUTCH_HOME/logs)

*NUTCH_LOGFILE: Log file (default: hadoop.log)

*NUTCH_CONF_DIR:  Path(s) to configuration files (default: $NUTCH_HOME/conf). Multiple paths must be separated by a colon ':'.

*JAVA_HOME

*NUTCH_JAVA_HOME

*NUTCH_HOME

If you install using "ant", then you will get a new folder in /nutch called /nutch/runtime/local and this is from where you must actually run nutch.
Tip: Try reading this page.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Control System 4 with just a keyboard? Is there a reference of keyboard shortcuts for System 4, so I can use a Macintosh SE with a keyboard and no mouse?
I found a Macintosh SE and a keyboard on the street several years ago. It didn't have any cables, so the only thing I could do with the Mac was use another power cable and turn it on. Yesterday, my ADB cable arrived, so I can use the keyboard, but I still don't have a compatible mouse. According to my Googling, the Macintosh SE runs System 4 and Finder 5.2.
Is there a reference of keyboard shortcuts for System 4, so I can play around with the system?

A: While it is reasonably possible to use a classic Mac without a keyboard, using one without a mouse requires a System software disk with the Easy Access control panel installed.
With Easy Access installed, you can press Command-Shift-Clear to toggle Mouse Keys at which point your numeric keypad can be used to control the mouse cursor and the computer will be frustrating, but functional.
A limited number of shortcuts are still documented on Apple's site in Archived Technical Note 28141. Also, you can select icons in open windows by typing the first letters of the icon's name (for example, 'sys' will select "System Folder"), followed by Command-O to open.

A: As far as I know, there aren't enough keyboard shortcuts (apart from your copy and paste, etc.) that'd allow you to play with the OS too much.
I also couldn't find a reference - things like this are surprisingly scarce.
I did find a Macintosh ADB mouse from here though - if you're alright with eBay or things like that.


text:
Q: Python append acting funny I have written a python code, to solve a puzzle. It was not working as expected. So while debugging I saw something very weird. Row is a list of lists. The append 1 to single row[n] appends to all lists inside row!
def trap( height):
        row = []

        for index, i in enumerate(height):
            if i == 0 and len(row) == 0:
                continue
            else:
                if(i > len(row)):#time for a new row
                  #to old rows append 0 below
                  for j in range(0, len(row)):
                        row[j].append(0)
                  row = row + [[0]] * (i - len(row))
                else:
                  for j in range(0,i):
                     row[j].append(0)
                  #PROBLEMATIC CODE START
                  for jo in range(i,len(row)):
                        if(index == 1):
                            print("jays are",row)
                            print("jo is",jo, row[jo])
                        row[jo].append(1)
                  #PROBLEMATIC CODE END (I GUESS?)

        print(row) #print this, it gives an idea

trap([2,0])

When I try this independently, it works fine, see:
row = [[0],[0]]
index = 1

for jo in range(0,len(row)):
      if(index == 1):
                  print("jays are",row)
                  print("jo is",jo, row[jo])
                  row[jo].append(1)
print(row)

The problematic code has been marked in the python as comment #PROBLEMATIC CODE START and #PROBLEMATIC CODE END. Call the trap() with [2,0]
row variable should be [[0,1],[0,1]]
but row variable is coming [[0,1,1],[0,1,1]]
I have been at this for many hours! I just don't understand why does .append() appends to all the lists inside row, but when I try the smaller code it works. Please help me and guide me

A: When creating a list using *, you are just copying the reference to the object and not the instance itself. Short example:
>>> a = [["abv"]] * 3
>>> a
[['abv'], ['abv'], ['abv']]
>>> a[0].append(1)
>>> a
[['abv', 1], ['abv', 1], ['abv', 1]]

I'm creating a list which contains the object ["abv"] 3 times. It's all the same object, just 3 times in the list.
As soon as I edit one item, it looks like all items are updated but actually it's all the same.
You'd need to create your list like this to create a new object for every iteration:
>>> a = [["abv"] for _ in range(3)]

So your code should be changed to this:
row += [[0] for x in range(i - len(row))]

A: To answer this question, you would need to modify your code a little bit.
#to old rows append 0 below
for j in range(0, len(row)):
    row[j].append(0)
row = row + [[0]] * (i - len(row))

You need to modify it to remove the multiple reference on the same object.
#to old rows append 0 below
for j in range(0, len(row)):
    row[j].append(0)
row += [[0] for x in range(i - len(row))]

with this, you should probably get the correct values.


text:
Q: What are menus called that prevent clicking other places until they are closed? I am trying to find out how to refer to a particular property of windows I frequently encounter.
These window prevent clicking anywhere else on the computer, and when you try to do so it is often accompanied by the "Windows Background" error sound and/or the menu flashing. An example would be the menu that appears when you are choosing where to save a file to.
I am hoping to find a program that stops Windows from preventing clicking while these menus are open, but I cannot seem to figure out how to refer to these menus in a way a search engine can identify in order to look for a program that would let me do so.
I would appreciate it if anyone knew anything about how to refer to this menu type and would be willing to share.

A: Such window is called Modal window


text:
Q: Changes in tp_compare vs. tp_richcompare between python 2 and 3? I am dealing withpython module which implements comparison operator or its objects (pygts, wrapping the GNU Triangulated Surface Library).
Py2 version defines tp_compare function pointer, which is a simple function testing for equality of the wrapped types, and it works fine.
When compiled for Py3, I assign the tp_richcompare function pointer, and the function is a simple proxy which calls the old comparison when the operation is equality test, otherwise returns "not implemented", as per rich comparison protocol (github):.
#if PY_MAJOR_VERSION >= 3
  static PyObject* rich_compare(PyObject *o1, PyObject* o2, int op){
    switch(op){
      case Py_EQ:{
         if(compare(o1,o2)) Py_RETURN_TRUE;
         Py_RETURN_FALSE;
      }
      default: Py_RETURN_NOTIMPLEMENTED;
    }
  }
#endif

Now when I run code which works in py2 under py3, I get crash with this backtrace line:
#6  0x00007f8b27a71c82 in rich_compare (o1=0x7f8aedf946f0, o2=0x9e6720 <_Py_NoneStruct>, op=2) at py/3rd-party/pygts-0.3.1/segment.cpp:459

which says the o2 is None.
How is it possible that there is no crash in py2? Does the py2 interpreter do the None check for me, and py3 does not? I cannot find any documented change here.
Thanks for hints.
EDIT:
Adding
 if(o2==Py_None) Py_RETURN_FALSE;

at the beginning of rich_compare made the crash go away, so my guess is correct, it seems. Documentation on that still appreciated.


text:
Q: Embedded System State Pattern: Storing information related to asynchronous events I have a embedded system software, where I go through bunch of hardware initialization steps and then go to either Mode1 or Mode2 depending on history of events that occurred. Even within a certain mode, I do certain things depending on the history of events
e.g.
if my display is off then in Mode 1 I take a flow which is different than what I would taken if the display was on. And the display notification arrives asynchronously, I don't explicitly query for that information.
There are few other similar events that arrive asynchronously that can change the course of action I would take further down the flow.
I am trying to understand how to store the information related to these events that happened in the past. I am inclined to store them as flags but then it defeats the purpose of using state pattern (and it is also error prone).
Another option I have is store these information in the state itself e.g.
Mode1_DisplayOff_Atrribx, Mode1_DisplayOff_Atrribx, Mode2_DisplayOff_Atrribx, Mode2_DisplayOff_Atrriby. But I fear this will make the state machine complex.
What should be the right approach here?
(Question is not necessarily related to embedded systems)

A: Some general design advise for this case, or for any case with complex state handling:

*

*Overall design advise: keep it as simple as possible. Strive for simplicity, not complexity.

*Create a state machine corresponding to the number of combinations of "modes", "events", "flags" etc that you have. This can be as simple or as advanced as needed - sometimes you might need to implement sub-states (for example in state "error", there are sub states "error display" and "error adc" etc).

*Avoid a jungle of flags: it is bad enough that you have to collect flags from numerous sources. If you also combine this with local decision makers, you will have to write complex code all over your program, where the local decision makers cause state changes. It will very soon turn impossible to keep track of program flow and code coverage.
This also tends to lead to tight coupling between a lot of modules that could have been independent of each other, which is always a very bad thing.

*Implement a standardized error handler for all states, with a standard error data type (error number, error origin etc).

*Keep the asynchronous information gathering separate from the state machine. That is, if the asynchronous events happen independently of which state the program is currently executing. If they don't, you'll have to integrate them in the state machine.

*Centralize the decision making of what to do next, at one single place in the program. Preferably combined with the error handler.
Your main loop would then look something like:
for(;;)
{
  state_result = state_machine[current_state]();
  event_result = gather_event(); // might need several of these

  current_state = evaluate_results (state_result, event_result);
}

Where evaluate_results is the only place in your program where state changes are allowed to occur. This function is only concerned with what state to execute next, it does not perform any actual work.


text:
Q: Call two functions with onPress in react native I have the following two buttons:
        <View style={styles.button}>
          <Button title="ADD" onPress={createDocumentHandler}/>
        </View>
        <View style={styles.button}>
          <Button title="CANCEL" color="red" onPress={props.onCancel}/>
        </View>

I want the first button to trigger both the "createDocumentHandler" function and the "props.onCancel" function
I thought it would be as easy as onPress={createDocumentHandler, props.onCancel} but that only triggers the second method for some reason

A: <Button title="ADD" onPress={createDocumentHandler}/>
createDocumentHandler = () => {
   actionA();
   actionB();
}

A: You create a custome function createDocumentHandler as :
createDocumentHandler = async() => {
// execute in whatever order
  let a =  await function1();
  let b =  await function2();
}

A: Try this
onCancel() => {
    {...}
 };
 function createDocumentHandler()
 {
     {...}
     return onCancel();
 }

function render(){
    return(
        <Button title="ADD" onPress={createDocumentHandler}/>
    )
}


text:
Q: Rspec error: unknown format for create action using json format Create method
def create
  @user = User.new(user_params)
  if @user.save
    respond_with("User #{@user.id}.", code: 200)
  else
    respond_with("User creation failed #{@user.errors}", code: 500)
  end
end

My specs:
describe "POST 'create'" do
  context "with valid parameters" do
    let(:credentials) { { :email => "new_user@example.net", :company_id => 1 } }
  it "creates a new user" do
    expect { post :create, :user => credentials }.to change(User, :count).by(1)
  end

Gives error: Unknown format
When code changed to expect { post :create, :user => credentials, :format => json }.to change(User, :count).by(1) error is:
undefined local variable or method `json'

What is the right way to spec for json response?


text:
Q: How do I check if the page is scrollable when the user first accesses it in React? I want to display scrollbar when the user first accesses each page
So I tried the code below:
function App() {
  const app = document.querySelector("#root");
  const [scrollHeight, setScrollHeight] = useState(app?.scrollHeight);

  useEffect(() => {
    setScrollHeight(app.scrollHeight);
  }, [scrollHeight])

  if (scrollHeight > window.innerHeight) {
    /* show scrollbar and do something */
  }

  return (/* some components */);
}

Isn't there a better idea?

A: In page.css or wrapper html element of Page component, you can set.
For page.css:

{ overflow: auto }

For wrapper html element:
"<div style={{overflow: 'auto'}}>"
Document link: overflow css


text:
Q: Elastic Search Should clause I'm trying to fetch users from ES based on the status of some of the fields.
I have 5 fields whose status I want to check and if any of these fields have the failed status I want to fetch that record. Since it's an OR condition between these 5 fields I was trying to use should in ES and adding terms to it. But it returns records of those users who don't match the criteria as well.
{
  "from": 0,
  "size": 50,
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "query": {
              "bool": {
                "must": [
                  {
                    "range": {
                      "segment_status.updated_at": {
                        "from": "2021-01-24",
                        "to": null,
                        "include_lower": true,
                        "include_upper": true,
                        "boost": 1
                      }
                    }
                  }
                ],
                "should": [
                  {
                    "terms": {
                      "segment_status.bse_status": [
                        2,
                        3,
                        4
                      ],
                      "boost": 1
                    }
                  },
                  {
                    "terms": {
                      "segment_status.nse_status": [
                        2,
                        3
                      ],
                      "boost": 1
                    }
                  }

                ],
                "adjust_pure_negative": true,
                "boost": 1
              }
            },
            "path": "segment_status",
            "ignore_unmapped": false,
            "score_mode": "avg",
            "boost": 1
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "marked_failed_manually": {
              "value": true,
              "boost": 1
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  },
  "sort": [
    {
      "segment_status.updated_at": {
        "order": "asc",
        "mode": "min",
        "nested_filter": {
          "term": {
            "segment_status.segment_type": {
              "value": "CASH",
              "boost": 1
            }
          }
        },
        "nested_path": "segment_status"
      }
    }
  ]
}

That is the query generated by the code. I'm using spring boot to build the query.

A: Just for reference, I tried this query and it seems to work.
{
  "from": 0,
  "size": 50,
  "query": {
    "bool": {
      "must": [
        {
        "nested":{
          "query":{
            "bool":{
              "must" : [
                {
                  "range" : {
                    "segment_status.updated_at" : {
                      "from" : "2021-08-30",
                      "to" : null,
                      "include_lower" : true,
                      "include_upper" : true,
                      "boost" : 1.0
                    }
                  }
                }
              ]
            }
          },
          "path" : "segment_status",
          "ignore_unmapped" : false,
          "score_mode" : "avg",
          "boost" : 1.0
        }
        },
        {
          "nested": {
            "query": {
              "bool": {
                "should": [
                  {
                    "terms": {
                      "segment_status.bse_status": [
                        2,
                        3
                      ],
                      "boost": 1
                    }
                  }

                ],
                "adjust_pure_negative": true,
                "boost": 1
              }
            },
            "path": "segment_status",
            "ignore_unmapped": false,
            "score_mode": "avg",
            "boost": 1
          }
        }
      ],
      "must_not": [
        {
          "term": {
            "marked_failed_manually": {
              "value": true,
              "boost": 1
            }
          }
        }
      ],
      "adjust_pure_negative": true,
      "boost": 1
    }
  },
  "sort": [
    {
      "segment_status.updated_at": {
        "order": "asc",
        "mode": "min",
        "nested_filter": {
          "term": {
            "segment_status.segment_type": {
              "value": "CASH",
              "boost": 1
            }
          }
        },
        "nested_path": "segment_status"
      }
    }
  ]
}


text:
Q: How to deal with tf.saved_model.save(model, filepath) Error? I use TFRS build a custom hybrid recommender; the model was trained and is able to make prediction well. But when I save it:
model = ...
filepath = 'saved_model/model0'
tf.saved_model.save(model, filepath)

error:
--------------------------------------------------------------------------- FailedPreconditionError                   Traceback (most recent call last) /tmp/ipykernel_2678112/2773535809.py in <module>
      5 #!mkdir -p saved_model
      6 filepath = 'saved_model/model0'
----> 7 tf.saved_model.save(model, filepath)

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/saved_model/save.py in save(obj, export_dir, signatures, options)    1278   # pylint: enable=line-too-long    1279   metrics.IncrementWriteApi(_SAVE_V2_LABEL)
-> 1280   save_and_return_nodes(obj, export_dir, signatures, options)    1281   metrics.IncrementWrite(write_version="2")    1282

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/saved_model/save.py in save_and_return_nodes(obj, export_dir, signatures, options, experimental_skip_checkpoint)    1313     1314   _, exported_graph, object_saver, asset_info, saved_nodes, node_paths = (
-> 1315       _build_meta_graph(obj, signatures, options, meta_graph_def))    1316   saved_model.saved_model_schema_version = (  1317       constants.SAVED_MODEL_SCHEMA_VERSION)

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/saved_model/save.py in _build_meta_graph(obj, signatures, options, meta_graph_def)    1485 1486   with save_context.save_context(options):
-> 1487     return _build_meta_graph_impl(obj, signatures, options, meta_graph_def)

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/saved_model/save.py in _build_meta_graph_impl(obj, signatures, options, meta_graph_def)    1434     1435   # Use _SaveableView to provide a frozen listing of properties and functions.
-> 1436   saveable_view = _SaveableView(checkpoint_graph_view, options,    1437                                 wrapped_functions)    1438   object_saver = util.TrackableSaver(checkpoint_graph_view)

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/saved_model/save.py in __init__(self, checkpoint_view, options, wrapped_functions)
    200     # Run through the nodes in the object graph first for side effects of
    201     # creating variables.
--> 202     self._trace_all_concrete_functions()
    203
    204     (self._trackable_objects, self.node_paths, self._node_ids,

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/saved_model/save.py in _trace_all_concrete_functions(self)
    304       for function in self.checkpoint_view.list_functions(obj).values():
    305         if isinstance(function, def_function.Function):
--> 306           function._list_all_concrete_functions_for_serialization()  # pylint: disable=protected-access
    307
    308   @property

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py in _list_all_concrete_functions_for_serialization(self)    1194       A list of instances of `ConcreteFunction`.    1195     """
-> 1196     concrete_functions = self._list_all_concrete_functions()    1197     seen_signatures = []    1198     for concrete_function in concrete_functions:

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py in _list_all_concrete_functions(self)    1176     """Returns all concrete functions."""    1177     if self.input_signature is not None:
-> 1178       self.get_concrete_function()    1179     concrete_functions = []    1180     # pylint: disable=protected-access

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py in get_concrete_function(self, *args, **kwargs)    1257   def get_concrete_function(self, *args, **kwargs):    1258     # Implements GenericFunction.get_concrete_function.
-> 1259     concrete = self._get_concrete_function_garbage_collected(*args, **kwargs)    1260 concrete._garbage_collector.release()  # pylint: disable=protected-access    1261     return concrete

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py in _get_concrete_function_garbage_collected(self, *args, **kwargs)    1237       if self._stateful_fn is None:    1238         initializers
= []
-> 1239         self._initialize(args, kwargs, add_initializers_to=initializers)    1240         self._initialize_uninitialized_variables(initializers)    1241

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
    778     self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
    779     self._concrete_stateful_fn = (
--> 780         self._stateful_fn._get_concrete_function_internal_garbage_collected(
# pylint: disable=protected-access
    781             *args, **kwds))
    782

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args,
**kwargs)    3155       args, kwargs = None, None    3156     with self._lock:
-> 3157       graph_function, _ = self._maybe_define_function(args, kwargs)    3158     return graph_function    3159

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/function.py in _maybe_define_function(self, args, kwargs)    3555     3556         self._function_cache.missed.add(call_context_key)
-> 3557           graph_function = self._create_graph_function(args, kwargs)    3558           self._function_cache.primary[cache_key] = graph_function    3559

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes)    3390     arg_names = base_arg_names + missing_arg_names    3391     graph_function = ConcreteFunction(
-> 3392         func_graph_module.func_graph_from_py_func(    3393             self._name,    3394             self._python_function,

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes, acd_record_initial_resource_uses)    1141
_, original_func = tf_decorator.unwrap(python_func)    1142
-> 1143       func_outputs = python_func(*func_args, **func_kwargs)    1144     1145       # invariant: `func_outputs` contains only Tensors, CompositeTensors,

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/eager/def_function.py in wrapped_fn(*args, **kwds)
    670         # the function a weak reference to itself to avoid a reference cycle.
    671         with OptionalXlaContext(compile_with_xla):
--> 672           out = weak_wrapped_fn().__wrapped__(*args, **kwds)
    673         return out
    674

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/training/tracking/tracking.py in _creator()
    279     @def_function.function(input_signature=[], autograph=False)
    280     def _creator():
--> 281       resource = self._create_resource()
    282       return resource
    283

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/data/ops/dataset_ops.py in <lambda>()
    241             # to have a weak reference to the Dataset to avoid creating
    242             # reference cycles and making work for the garbage collector.
--> 243             lambda: weak_self._trace_variant_creation()()),  # pylint: disable=unnecessary-lambda,protected-access
    244         name="_variant_tracker")
    245     self._graph_attr = ops.get_default_graph()

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/data/ops/dataset_ops.py in _trace_variant_creation(self)
    363       # pylint: disable=protected-access
    364       graph_def = graph_pb2.GraphDef().FromString(
--> 365           self._as_serialized_graph(external_state_policy=options_lib
    366                                     .ExternalStatePolicy.FAIL).numpy())
    367     output_node_names = []

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/util/deprecation.py in new_func(*args, **kwargs)
    550                 'in a future version' if date is None else ('after %s' % date),
    551                 instructions)
--> 552       return func(*args, **kwargs)
    553
    554     doc = _add_deprecated_arg_notice_to_docstring(

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/data/ops/dataset_ops.py in _as_serialized_graph(self, allow_stateful, strip_device_assignment, external_state_policy)
    302     if external_state_policy:
    303       policy = external_state_policy.value
--> 304       return gen_dataset_ops.dataset_to_graph_v2(
    305           self._variant_tensor,
    306           external_state_policy=policy,

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/ops/gen_dataset_ops.py in dataset_to_graph_v2(input_dataset, external_state_policy, strip_device_assignment, name)    1158       return _result    1159    except _core._NotOkStatusException as e:
-> 1160       _ops.raise_from_not_ok_status(e, name)    1161     except _core._FallbackException:    1162       pass

/napi/k_working_dir/ds_test/shared-space/venv/lib/python3.9/site-packages/tensorflow/python/framework/ops.py in raise_from_not_ok_status(e, name)    7105 def raise_from_not_ok_status(e, name):    7106   e.message += (" name: " + name if name is not None else "")
-> 7107   raise core._status_to_exception(e) from None  # pylint: disable=protected-access    7108     7109

FailedPreconditionError: Failed to serialize the input pipeline graph: ResourceGather is stateful. [Op:DatasetToGraphV2]

A: Solution:
# define create_model()
def create_model():
    """instantiate a model and compile it"""
    model = MyTFModel(...)
    model.compile(optimizer=tf.keras.optimizers.Adagrad(0.1))
    return model

# instantiate & compile your model by custom function create_model()
model = create_model()

# set model checkpoint to record the weight during & after fitting
model_checkpoint=tf.keras.callbacks.ModelCheckpoint('DeepCrossMultitaskModel{epoch:02d}',period=2,save_weights_only=True)

# fit the model & save weights during & after the fitting using model_checkpoint

history = model.fit(
    cached_train,
    validation_data=cached_test,
    validation_freq=5,
    epochs=epochs,
    callbacks=[model_checkpoint],
    verbose=0)

#!mkdir -p saved_model
filepath = 'saved_model/model_weight'

model.save_weights(filepath=filepath, save_format='tf')
# newly instantiate & compile a model
new_model = create_model()

# load the weights back to the new model
new_model.load_weights(filepath)

#double check: expect to produce the same thing as model(dict(test_df.head(3)))
new_model(dict(test_df.head(3)))

References & Credits

*

*The cause of the error, check out this post: Can't save custom subclassed model

*Solution: https://androidkt.com/how-to-save-and-load-model-weights-in-keras/

A: I had the same problem in my multitask model (TFRS) and following this solution posted here resolved the issue.
The metrics used in the retrieval task is the issue.
After training and evaluating the model I run this code to save it:
model.retrieval_task = tfrs.tasks.Retrieval()  # Removes the metrics.
model.compile()
model.save("./models/my_rec_model")

and when I need to perform inference, I use this:
model = tf.keras.models.load_model("./models/my_rec_model")


text:
Q: MySQL, get data based on two tables I am trying to get data based on two tables.
My tables look like this:
table1:
    id | value | email

table2:
    id | category | value | email

I am trying to get all values of table 1, as long as they are not in table2 with the category of my variable (myVar).
Example:
Our Variable is "DontPickMe".
In table1 we have value 1,2,3. In table2 we have 1,2. Number 1 got category "keepMe" and number 2 got category "DontPickMe" (our variable). The result should now be: 1,3.
In the example (result should be 1,3):
table1:
        id | value | email
               1
               2
               3
table2:
        id | category | value | email
             keepMe       1
            DontPickMe    2

I tried the below but it is wrong.. How can I achieve this?
let sql = 'SELECT value FROM table1 WHERE NOT EXISTS (SELECT category FROM table2 WHERE category = ?)';

    connection.query(sql, [myVar], function(error, result) {
        if (error) throw error;
        console.log(result)

A: So you can use this to get desired result
   let sql = 'SELECT value FROM table1 WHERE value NOT IN (SELECT value FROM table2 WHERE category = ?)';

  connection.query(sql, [myVar], function(error, result) {
    if (error) throw error;
    console.log(result)

A: SELECT distinct value FROM table1 left join  table2 on table1.category=table2.category
 WHERE table1.category = ? and table2.category is null

A: let sql = 'SELECT DISTINCT value FROM table1 LEFT JOIN table2 on table1.value = table2.value WHERE category = ?';

    connection.query(sql, [myVar], function(error, result) {
        if (error) throw error;
        console.log(result)

Sorry if wrong. :D


text:
Q: How to authenticate with google account via ruby on rails Can you please help me ?
I am new in rails and i want to login with google using rails 3.2.8.
How can i do this?

A: Try this
http://railscasts.com/episodes/304-omniauth-identity?view=asciicast
Watch Video and try

A: download this app from here it is for facebook authentication using omniauth-facebook gem.you rather then use omniauth-google gem.generate key secret key for your app and necessary settings on google.
 https://github.com/kashiftufail/facebook_login_using_devise_and_omniauth_facebook

Hope you will do


text:
Q: How to get FATfs working on Xmega A4? Not sure what I should add or what file to edit First of all, I have already been through http://elm-chan.org, and while it has helped me, it is a bit vague (in my opinion).
I am attempting to read an SD Card with an Xmega128a4u using ASF (because the non-ASF way is too underground for me...). Anyway, although ASF has an example with the Xplained board for Xmega C3, it is not very helpful, and my attempts at porting it fail.
So, the following is what I do:

*

*I start a Project in ASF (I'm programming in C)

*I add the FATfs, SD/MMC and systemClock divers(or modules or services) to my project through ASF Wizard.

*I get kind of lost... :(

I read in elm-chan's page that some sort of "glue file" but it's not very specific in what it should be. What should I #include in it or where should I #include it?
I'd appreciate some help on this as I have tried several things with no success.

A: you have to addapt the disk_read, disk_write, ... functions in the diskio.c file. they will connect the fatFS library with your (low-level) sd communication.
you should may first test a simple communication with the sd-card without file system.
I have the same "project" but with an arduino due board instead of Xmega and the simple communication does allready work, so I can read and write. But my problem is to addapt the FatFS correctly and I suppose that the fault can be localized in my diskio.c functions, cause they are individual.
Maybe someone has got the same problem and can help me?
Ciao
Imke


text:
Q: Sorting int variables in ascending order I am creating a lottery number generator in android, but have come to a recent standstill.
The way it works is, I populate an array list by looping through various times.
Then I shuffle the array list by calling collections.shuffle.
And finally, I create five int variables to obtain the first 5 elements from the array list.
This is all fine.
Now my problem is trying to print these out in ascending order. I have come across collections.sort, unfortunately this does not help, as it will only sort the array list in ascending order, removing my original aim of a unique random order.
Is there a way to get the following 5 integer variables to print in ascending order?
I couldn't find any relevent documentation on allowing me to add these 5 int variables to an int array and then call sort on the array, if that's at all possible.
 public void onClick(View view) {
    ArrayList<Integer> euroList = new ArrayList<Integer>();
    TextView textView1 = (TextView) findViewById(R.id.textview2);

    for (int i = 1; i <= 50; i++) {
        euroList.add(i);
    }

    Collections.shuffle(euroList);

    textView1.setText("");

    int num1 = euroList.get(0);
    int num2 = euroList.get(1);
    int num3 = euroList.get(2);
    int num4 = euroList.get(3);
    int num5 = euroList.get(4);

    textView1.setText(String.valueOf(num1) + " " + String.valueOf(num2)
            + " " + String.valueOf(num3) + " " + String.valueOf(num4) + " "
            + String.valueOf(num5));

Thank you for your time.

A: You can sort the first 5 elements of the list before extracting them. After the shuffle, and before getting the resulting elements, add this:
Collections.sort(euroList.subList(0, 5));

The whole thing will then look like this:
Collections.shuffle(euroList);
Collections.sort(euroList.subList(0, 5));

int num1 = euroList.get(0);
int num2 = euroList.get(1);
int num3 = euroList.get(2);
int num4 = euroList.get(3);
int num5 = euroList.get(4);

A: Extract the five int values to a new ArrayList <Integer> first. Sort that list. Then determine num1, num2,n...


text:
Q: Load-balance with LAN and Wi-Fi I have a Mac, which runs Mac OS X 10.6 or Ubuntu 9.10 or Windows XP (Multiboot). Solution can be for any of the systems, whatever works better.
I have two ISPs, one can be accessed via Wi-Fi, one can be accessed via LAN.
In Mac OS X I can define the priority, which network to choose first. But what I wish to do is to load-balance with both networks.
I don't want to buy extra hardware. I have some unused Wi-Fi routers if this would help.
Compiling and configuring programs in Linux is no problem for me.
Similar question: Load balancing with multiple gateways

A: A close-ish topic, for linux, would be the 'metric' setting for routes. Lower numbers are preferred over higher numbers. If you give both routes the same metric, then I would think they'd be chosen with equal probability.
I think the technique you're trying to achieve is called multihoming. I don't have any direct experience with it. However, a few things you'd probably need to keep in mind.

*

*By default, I think you'll end up with only one default route. This means that all outgoing traffic will prefer one interface by default. You'd need to look into having multiple default routes, or into changing that route dynamically over time.

*For the life of an individual incoming (TCP) connection, it should stay on the same interface which it came in on. I think.

Anywho, those are all the pointers I can think of at the moment.

A: You could use a routing metric system where you install both internet connections in your routing table with an equal metric. The operating system should then use both of these routes equally, effectively splitting your outbound traffic across both links.
Incoming traffic in reply to your requests should also be balanced as it will return to the interface (Public IP) that the request came out of.
The problem with this would be session persistence, for example you view a website via one of your links, but the next page view is load balanced out of your other interface, this would confuse some applications as your source IP address would be constantly changing.
Therefore I would probably only split some of your traffic onto the other interface using none equal cost routes, may be by application, destination or protocol. Just something that will keep your traffic paths consistent.

A: Connectify Dispatch has a solution that will do just what you need. Currently for Windows only, but people have had success virtualizing and using their software on OS X.
Since you already run (were running) Windows XP I figured you'd be able to figure that part out on your own.

The biggest problem with this is that Windows easily offers support for multiple NICs, while on OS X it isn't nearly as easy to implement.

A: There is kind of a workaround: My application is able to load-balance, I can define 2 connections which are then used both.
I then route one of the Server IPs to one of the IPS.
on mac os 10.6:
route add -host XXX.XXX.XXX.XXX 192.168.1.1
I know, this is very specific, and only works if the server-ips are always the same. And if the application can load-balance in any way.

A: I don't think this will be possible without doing something like all traffic going out is one ISP and traffic coming in is another ISP.
Reason being is splitting both traffic across 2 separate networks doesn't seem like they would make it back.  If you had 2 pipes from 1 ISP it might make be possible.
Like the person said earlier, I think you'll need a default anyways and could curb certain traffic through one route and the rest through another.  Just don't think load-balancing like you would on a LAN will work here.
Example: run updates using 192.168.2.* Wi-Fi ISP
run halflife using 192.168.1.* LAN ISP.

A: The url mentioned below is specifically meant for win 7 but you should get an idea from it. It changes the metric of default gateway depending on the load on the interface, thus leading to load sharing.
http://www.youtube.com/watch?v=Qh5Eb8sXvuk

A: I've heard this same question a dozen times a dozen different ways.
First, internal sessions and external sessions are handled similarly, but are not the same.  For every internal session, there could be multiple external, and vice versa.  What you are talking about isn't logically impossible, but does require a bit of programming and prep.  Some devices are being built with the ability to aggregate ethernet connections or wifi for faster network speeds internally on a network, but for external networking, I've only found devices with FAILOVER, which means they only switch when they have to.  However, you could use a basic switching (if statements with 0 or 1) in the connection protocol that redirects traffic over a different gateway for each EXTERNAL session.  You would then have to keep track of each EXTERNAL SESSION attatched to each INTERNAL SESSION, by wrapping a sub-session inside a main session with a sessionID.  You would then have to have a way to check for the site domain or use the sessionID to complete the internal routing (in other words, you'd need to be able to differentiate messages from the client for each external session\connection based on which site they were requesting data from or sending data to so that the pipe for each site would be set, keeping the site from rejecting the pipe).  This means you'd have to build a new network protocol into your router, and decide how to differentiate the connections (if only done by site domain, it might be doable from the router, but the client may try to use the ipaddress of the external gate for the website, which negates this; if done on both ends, the client needs to keep track of some identifier, typically a numerical value of binary masking, that allows the send recieve to be matched against the external session being routed on main gate).  In other words, you'd have to program your own protocol to handle the networking, and you'd have to decide if you want to build it yourself (making use of both client and host programming), or if you want to build something that's compatible with older existing programming (which would need to be bound by the messaging between host and client, putting more wear on the host but nothing new for the client).  If you know your unix, or you know your winserver programming, this can be done with just a bit of time, but it requires a larger amount of resources be allocated for each device being balanced.
For larger corporate style networks, you can mesh the networking, and give each floor or department a dedicated gateway, allowing for multiple ISP's, and never putting too much on any one of them.  You can also have Failover handled by a hub that sends changes or redirects to a different gateway when one of them has trouble.  This offers some fault tolerance.


text:
Q: Stored procedure takes time to fetch data on application layer I have written a stored procedure that talks to around 5 tables.
The performance on database layer looks good. Here is the output.
CALL `meetingsReport`('41', '%', '2016-01-01', '2018-01-01');
/* Affected rows: 0  Found rows: 3,288  Warnings: 0  Duration for 1 query: 4.203 sec. (+ 0.141 sec. network) */

Takes around 4 seconds to generate the report which is fine because the data set is huge, I am performing some pivoting and generate the final data-set.
When I get the data on app level (using laravel php) and calling the procedure as
    $params = array($eventId, $status, $startTime, $endTime);
    return DB::select('call meetingsReport( ?,?,?,?)', $params);

It takes time, I printed time-stamp to check why is it taking time. Here is the output.
12:26:47am - when the route is hit

12:27:00am - when the data is received by procedure call

It has taken around 13 seconds. What could be the reason?
UPDATE:
I tried with PDO
Here are the details:
try {
    $dbh = new PDO('mysql:host=localhost;dbname=livedb', 'username', 'password');
    $data = $dbh->query("CALL `meetingsReport`('41', '%', '2016-01-01', '2018-01-01') ");
    echo date("h:i:sa")."
";
    $dbh = null;
} catch (PDOException $e) {
     print "Error!: " . $e->getMessage() . "
";
     die();
}

and the output is:
10:23:22am
10:23:28am

It took 6 seconds, I pasted the same code on the framework and the output is:
01:15:54am
01:16:06am

It takes 12 seconds.

A: It's probably the prepare which is called by DB::select which is taking the additional time.
Honestly, you might get better results by creating a report table/view from those 5 large datasets.
Or look at your indexes on those tables
I've had some remarkable performance increases by simply combining several large tables into a view.
I assume this DB::select is only called rarely, otherwise you've got a real issue.

A: Look into this article if you have performance problems with large dataset
http://www.fromdual.com/mysql-materialized-views


text:
Q: C++ Classes and Xcode I don't understand why Xcode gives me "Expected parameter declarator" error on line 3.
Can you explain me what happens behind ?
class B;
class A {
    B b(this);
};

class B {
    B(A* a) { }
};

A: The reason for the error is that in-class member initialization needs to use either = or {}, not (), although I agree that "Expected parameter declaration" and "Expected ')'" are not particularly helpful error messages.
Also, at the point where you're declaring b to be initialized with the constructor of B, the compiler doesn't know about that constructor yet. Move the definition of B before A to solve this:
class A;

class B {
  public:
    B(A* a) { }
};

class A {
    B b = B(this);
    // or
    B b{this};
};

A: Initialize b in the constructor of A and have the constructor public:
class A;

class B {
public:
    B(A* a) { }
};

class A {
public:
    A() : b(this) {}
    B b;
};

int main()
{
    A a;
}


text:
Q: Related to Mule API I am facing the below issue , Please help.
Post deploying Mulesoft program to API Management .We have xml input and xml schema to validate it .For xml API we are getting the following error .
Schema could not be resolved for key : **/mytask/edit-application/detail
,POST application/xml (org.mule.module.apikit.exception.ApikitRuntimeException)
org.mule.module.apikit.validation.RestXmlSchemaValidator: 80**

Thanks


text:
Q: Hadoop performance problems because of too many nodes? i heard that hadoop can get performance problems if you run broad queries because too many nodes can be involved?
Can anyone verify or falsify this statement?
Thanks!
BR

A: The namenode has performance problems if you add too many files as it must store all file locations in memory. You can optimize this by periodically creating larger archives. For example, daily database dumps becomes monthly/yearly compressed archives that are still in a processable format
HDFS datanodes are just a filesystem and scale linearly. Adding more NodeManager nodes overall has no negative consequences, and YARN has been reported as running up to 1000 nodes, I would suggest using standalone clusters if you actually needed more than that.
As with any distributed system, you need to optimize network switching and system monitoring, but those are operational performance problems not specific to Hadoop


text:
Q: Singularities of $ {1}/{\cos(\frac{1}{z})}$ I would like to determine the singularities of $f$, given by $$f(z) = \frac{1}{\cos(\frac{1}{z})}.$$
It is clear to me that $z = 0$ and $z = \frac{2}{(1+2k)\pi}$ for $k\in\mathbb Z$ are singularities. However, I don't know how to handle by
$$ \cos(\frac{1}{z}) = \sum_{n=0}^\infty \frac{(-1) z^{-2n}}{(2n)!} \;\forall z\neq 0 $$
which are the types of those singularities. I would be very pleased if you give me any hint or explanation.

A: The Taylor series for secant is
$$
\sec(z) = \sum_{n = 0}^{\infty}(-1)^n\frac{E_{2n}z^{2n}}{(2n)!}
$$
where $E_{2n}$ is the Euler number. Then
$$
\sec(1/z) = \sum_{n = 0}^{\infty}(-1)^n\frac{E_{2n}}{z^{2n}(2n)!} = 1 + \frac{1}{2z^2} + \frac{5}{24z^4} + \frac{61}{720z^6} + \cdots
$$
Now, there are three types of singularities. We have removable, poles, and essential. What do we have here?
A removable singularity is defined as:

*

*If $f$ is bounded in some neighborhood of $z_0$, then one can define
$f(z_0)$ in a unique way such that the function is also analytic at
$z_0$

A pole is defined as:

*

*$f$ has a pole of finite order $m$ at $z_0$ if and only if $f(z)(z-z_0)^m$
is holomorphic at $z_0$ and has no zero at $z_0$.

Finally, an essential singularity is defined as:

*

*If the Laurent series has an infinite number of negative terms, then
we say that $z_0$ is an essential singularity of $f$.

A: The answer depends on how you define essential singularities. Usually, the classification in removable singularities, poles, and essential singularities requires isolated singularities. However, since the zeros of the denominator $cos(1/z)$ are, as you pointed out, located at $z_0=\frac{1}{\pi (k + \frac{1}{2})}$, we actually have isolated poles arbitrarily close to $z=0$. Therefore, there's no isolated singularity at $z=0$ and thus a cluster point instead of an essential singularity.
See also Finding the singularity type at $z=0$ of $\frac{1}{\cos(\frac{1}{z})}$.


text:
Q: Does gradle.properties have access to environment variables I looked around and could not find any way of accessing environment variables in my gradle.properties.
What I can do: In my build.gradle I can access environment variables like this System.getenv("MY_VAR"). I would like to do the same in my gradle.properties.
Example of what I want to do: In my gradle.properties replace build.foo=bar with build.foo=System.getenv("BAR")
So far all my attempts to access environment variables from gradle.properties have failed.
Any insight into the matter would be great, thanks!

A:
could not find any way of accessing environment variables in my gradle.properties.

You can't. gradle.properties is not anything fancy, it is a standard properties file.
You would need to post-process the properties somehow as indicated in this. Currently, Gradle does not offer any such functionality to "custom load" gradle.properties.

A: Not all environment variables are visible to gradle. If you can name them with the special prefix ORG_GRADLE_PROJECT_ these will be available. You can read about it here
ORG_GRADLE_PROJECT_foo can be accessed as foo within gradle.

A: From https://docs.gradle.org/current/userguide/build_environment.html
"... but if an option is configured in multiple locations, the first one wins:
system properties, e.g. when -Dgradle.user.home is set on the command line."
In Unix you could do like this: -Dgradle.user.home=$GRADLE_USER_HOME

A: According this Gradle documentation documentation. Environment Variable that follows this name pattern "ORG_GRADLE_PROJECT_foo=bar" will be added as a gradle property with the name "foo"


text:
Q: How to merge records from two tables into third using MYSQL I have 3 tables A, B, C
Schema of all 3 tables is same as mentioned below:
1st A table:
cpid ,name, place

2nd B table:
connectorid,dob

3rd C table:
ccpid cconnectorid

Now both tables A and B have many records.
Now some of the records in A and B are with same id.
Now I want to merge the records from A and B into Table C.
Merge logic is as follows
1)If records with cpid = connectorid ,insert into table c.
2)C Table  ccpid is the foreignkey for A table cpid and cconnectorid is the foreignkey B table connectorid.
3)Using select query.

A: You can use select insert  with a n inner join
 insert into table_c
 select a.cpid, b.connectorid, a.place
 from table_b as b
 inner join table_a as a  on a.id = b.id

A: You can try this solution for your query:
INSERT INTO `C`(`ccpid`, `cconnectorid`, `ccity`)
SELECT ta.`cpid`, ta.`cconnectorid`, tb.`place`
FROM `A`  as ta
  INNER JOIN `B` tb ON ta.`cpid` = tb.`cconnectorid`

A: You just need join data from both tables? This is simple JOIN function.
SELECT *
    FROM Table_A
    INNER JOIN Table_B
    ON Table_A.cpid =Table_B.connectorid;

You can insert this select to your Table_C.
Here is INNER JOIN, but I think you should take a look to JOINs, here are examples and you can read more about other JOINs.

INNER JOIN: Returns all rows when there is at least one match in BOTH
  tables LEFT JOIN: Return all rows from the left table, and the matched
  rows from the right table  RIGHT JOIN: Return all rows from the right
  table, and the matched rows from the left table  FULL JOIN: Return all
  rows when there is a match in ONE of the tables

A: use following query replace with your table names
INSERT INTO CTABLE(ccpid,cconnectorid,ccity)
(SELECT A.cpid ,B.connectorid, A.place FROM
TABLEA A INNER JOIN TABLEB B ON A.cpid = B.connectorid)


text:
Q: create dataframe of r2, residuals, and coeff from linear models Exactly like this question but how do you also get the R squared value for each model? link
Sample data
test <- data.frame(row=c(1:16),
plot = c(1,1,1,1,1,2,2,2,3,3,3,3,3,3,3,3),
                 logT = c(1.092,1.091,1.0915,1.09,1.08,1.319,1.316,1.301,1.2134,1.213,1.21,1.22,1.23,1.20,1.19,1.19),
                 utc_datetime = c(2020-03-05T00:00:00Z,2020-03-05T00:30:00Z,2020-03-05T01:00:00Z,2020-03-05T01:30:00Z,2020-03-05T02:00:00Z, 2020-03-06T01:00:00Z,2020-03-06T01:30:00Z,2020-03-06T02:00:00Z,
2020-03-10T02:00:00Z,2020-03-10T02:30:00Z,2020-03-10T03:00:00Z,2020-03-10T03:30:00Z,2020-03-10T04:00:00Z,2020-03-10T04:30:00Z,2020-03-10T05:00:00Z,2020-03-10T05:30:00Z,),
hrs_since = 1,2,3,4,5,1,2,3,1,2,3,4,5,6,7,8))

A deeper explanation of the data I am dealing with is here but I believe the sample data provided above would suffice data. Ideally, I would want to use the utc_datetime as the x axis/IV value but no code I've tried works with using that so I created the hrs_since variable which works.
I am looking for an output datframe that looks something like this:

plot
slope(coeff)
r2 value
rsd

1
2.1
.96
.01

2
1.3
.85
.01

3
.8
.99
.02

When I run the code below...
output <- ddply(test, "plot", function(x) {
  model <- lm(logT ~ hrs_since, data = x)
  coef(model)
})

I create a dataframe that looks like this:

plot
(Intercept)
hrs_since

1
2.1
.96

2
1.3
.85

3
.8
.99

But when I add summary(model)$r.squared to it, such as below...
output <- ddply(test, "plot", function(x) {
  model <- lm(logT ~ hrs_since, data = x)
  coef(model)
  summary(model)$r.squared
})

I create a dataframe that looks like this:

plot
V1

1
0.98

2
0.97

3
0.89

Where the correct R squared value has been added as column V1 to the df "output", but I have for some reason lost the coeff column? Ideally, I want to also add rsd and maybe st.dev columns but have not attempted yet because getting the R squared and coeff columns correct are the most important parameters I need. Also, originally I tried using r.squared(model) instead of summary(model)$r.squared in the line below coef(model), but this resulted in getting the error "Error in UseMethod("pmodel.response") :
no applicable method for 'pmodel.response' applied to an object of class "lm""
Also, I tried a method using this code as well and it worked but the coeff was not returned in the parameters returned for each plot
output <- test %>%
  group_by(plot) %>%
  do(glance(lm(lnT~hrs_since, data=.)))

Thank you in advance!

A: Here's an approach that nests each of the models in a dataframe and captures the results in the dataframe as well. Then uses the broom package to extract  the statistics. There are two different broom functions that extract the intercept and r2, so I run them separately and combine into one dataframe.
library(dplyr)
library(modelr)
library(tidyverse)

dat_all <- data.frame()

#nest the datasets as separate dataframes
for (p in unique(test$plot)){
    data <- data.frame(x = test$logT[test$plot == p], y = test$hrs_since[test$plot == p])
    names(data) <- c("logT", "hrs_since")
    dd <- data.frame(plot = p, data = data) %>%
        group_by(plot) %>%
        nest()
    dat_all <- rbind(dat_all, dd)
}

myModel <- function(x){
    lm(data.logT ~ data.hrs_since, data = x)
}

#use map to run the model and each of the nested dataframes
dat_all <- dat_all %>%
    mutate(model = map(data, myModel))

#extract the intercepts
i <- dat_all %>%
    mutate(tidy = map(model, broom::tidy)) %>%
    unnest(tidy) %>%
    filter(term == "(Intercept)") %>%
    select(plot, intercept = estimate)

#extract r2
r <- dat_all %>%
    mutate(glance = map(model, broom::glance)) %>%
    unnest(glance) %>%
    select(plot, r.squared)

#combine statistics by plot
results <- i %>%
    left_join(r, by = "plot")

   plot intercept r.squared
  <dbl>     <dbl>     <dbl>
1     1      1.10     0.618
2     2      1.33     0.871
3     3      1.22     0.380


text:
Q: Need help to finding error line in Spyder IDE I use Spyder IDE, but most of the time I can not find the line that the error occurred easily. For example this is one of those errrors:
runfile('C:/Users/m/Desktop/python/third.py', wdir='C:/Users/m/Desktop/python')
Traceback (most recent call last):

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-1-22ecdcbaada4>", line 1, in <module>
    runfile('C:/Users/m/Desktop/python/third.py', wdir='C:/Users/m/Desktop/python')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/m/Desktop/python/third.py", line 134
    predicted_stock_price = (predicted_stock_price + 1) *
                                                          ^
SyntaxError: invalid syntax

How can I understand which line of code caused the error? Why this IDE doesn't show the error line simply like other IDEs?
EDIT: It seems the rule of last line that some friends mentioned in comments doesn't work all the time. For example for this new error:
runfile('C:/Users/m/Desktop/python/third.py', wdir='C:/Users/m/Desktop/python')
Using TensorFlow backend.
Traceback (most recent call last):

  File "<ipython-input-18-22ecdcbaada4>", line 1, in <module>
    runfile('C:/Users/m/Desktop/python/third.py', wdir='C:/Users/m/Desktop/python')

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/m/Desktop/python/third.py", line 45, in <module>
    r = s.get('https://platform.tgju.org/fa/tvdata/history?symbol=AFGHAN_USD&resolution=60&from=1556027700&to=1561211760' , json = data ).json()

  File "C:\ProgramData\Anaconda3\lib\site-packages\requests\models.py", line 897, in json
    return complexjson.loads(self.text, **kwargs)

  File "C:\ProgramData\Anaconda3\lib\json\__init__.py", line 348, in loads
    return _default_decoder.decode(s)

  File "C:\ProgramData\Anaconda3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())

  File "C:\ProgramData\Anaconda3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

JSONDecodeError: Expecting value


text:
Q: Bootstrap Treeview's href property not rendering a link I'm working on a .net core application where I'm using the Bootstrap Treeview. Here is part of the javascript that sets up my tree:
       var tree = [
    {
        text: "Assets",
        href: "http://localhost:63690/asset/index",
        nodes: [
        {
            text: "Barcode"
        },
        {
            text: "Importation"
        }
        ]
    },
    {
        text: "Inventory",
        nodes: [
        {

and here is my markup in my view:

Based on the information on this page I should just be able to put the URL in the href property. But when I run the app, no link or anchor gets rendered and nothing happens when I click on my Assets node. What am I missing?
I also added the following to geenrate the treeview:
 $('#tree').treeview({
        data: tree,
        levels: 5,
        backColor: 'white',
        expandIcon: "glyphicon glyphicon-triangle-right",
        collapseIcon: "glyphicon glyphicon-triangle-bottom",
        showBorder: false
    });

A: I just get the same problem, and I find the solution in project's document.

enableLinks
Boolean. Default: false
Whether or not to present node text as a hyperlink. The href value of
  which must be provided in the data structure on a per node basis.

So you should add enableLinks: true to your code like this:
 $('#tree').treeview({
    data: tree,
    levels: 5,
    backColor: 'white',
    expandIcon: "glyphicon glyphicon-triangle-right",
    collapseIcon: "glyphicon glyphicon-triangle-bottom",
    showBorder: false,
    enableLinks: true
});


text:
Q: Xml To MYSQL Import using mysql procedure i have written the below sql procedure to load data from xml to MYSQL table.
CREATE  PROCEDURE pbadge (path varchar(255), node varchar(1000))
BEGIN
    declare xml_content text;
    declare v_row_index int unsigned default 0;
    declare v_row_count int unsigned;
    declare v_xpath_row varchar(50000);

 START TRANSACTION;
    SAVEPOINT sp_order;

    set xml_content = load_file(path);

    -- calculate the number of row elements.
    set v_row_count  = extractValue(xml_content, concat('count(', node, ')'));

    -- loop through all the row elements
    while v_row_index < v_row_count do
        set v_row_index = v_row_index + 1;
        set v_xpath_row = concat(node, '[', v_row_index, ']/@*');
        insert into badges values (
            extractValue(xml_content, concat(v_xpath_row, '[1]')),
            extractValue(xml_content, concat(v_xpath_row, '[2]')),
            extractValue(xml_content, concat(v_xpath_row, '[3]')),
            extractValue(xml_content, concat(v_xpath_row, '[4]'))

        );
    end while;
 COMMIT;

and my xml is like below,
<?xml version="1.0" encoding="utf-8"?>

<badges>

 <row Id="1" UserId="2" Name="Autobiographer" Date="2010-08-05T19:11:16.743" />

  <row Id="2" UserId="11" Name="Autobiographer" Date="2010-08-05T19:36:16.583" />

  <row Id="3" UserId="17" Name="Autobiographer" Date="2010-08-05T19:46:16.673" />

  <row Id="4" UserId="25" Name="Autobiographer" Date="2010-08-05T19:51:16.787" />

  <row Id="5" UserId="36" Name="Autobiographer" Date="2010-08-05T20:16:16.817" />

  <row Id="6" UserId="44" Name="Autobiographer" Date="2010-08-05T20:21:16.947" />

  <row Id="7" UserId="48" Name="Autobiographer" Date="2010-08-05T20:41:16.923" />

  <row Id="8" UserId="58" Name="Autobiographer" Date="2010-08-05T21:01:16.963" />

  <row Id="9" UserId="6" Name="Autobiographer" Date="2010-08-05T21:46:17.117" />

  <row Id="10" UserId="6" Name="Student" Date="2010-08-05T21:56:20.137" />
  ..
  ..
  ..
  ..

  <row Id="1000" UserId="647" Name="Student" Date="2010-08-05T21:56:20.137" />

i used below command in mysql command window,
call pbadge ('/home/naveen/Desktop/Badges.xml', '/badges/row');

it  works fine up to 852 row.
when i increase the xml row count above 852 nothing will be imported to table and the message displayed like below,
mysql> call pbadge ('/home/naveen/Desktop/Badges.xml', '/badges/row');
Query OK, 0 rows affected, 1 warning (0.00 sec)

can any one help me to solve this.
Thanks

A:
" Every table (regardless of storage engine) has a maximum row size of
  65,535 bytes. Storage engines may place additional constraints on this
  limit, reducing the effective maximum row size... BLOB and TEXT
  column contents are stored separately from the rest of the row.
  [Source] "

This does not mean the TEXT data type can store anything without limits [source]:

*

*The TEXT data type has a maximum length of 65,535 (216 – 1) bytes (approx. 64KB).

*The MEDIUMTEXT data type has a maximum length of 16,777,215 (224 – 1) bytes (approx. 16MB)

*The LONGTEXT data type has a maximum length of 4,294,967,295 (232 – 1) bytes (approx. 4GB)

The effective maximum length is even less if the value contains multibyte characters.

" it works fine up to 852 row... xml row count above 852 nothing will be imported to table"

That is because the other rows were never stored in the xml_content TEXT value as the number of characters in Badges.xml crossed the limit of 65,535 bytes (size > 64 KB).
The solution is to change the data type of xml_content from TEXT to MEDIUMTEXT if your XML file contents are lesser than 16MB (or LONGTEXT for larger contents lesser than 4GB). Change the declaration in your code to:
declare xml_content mediumtext;


text:
Q: Determining if a time is GMT or BST in Java? If I have a date supplied to a system written in Java, is there any way of telling if it is GMT or BST?

A: For formatting, you should really use a DateFormat implementation (e.g. SimpleDateFormat). That will let you specify the time zone (and output format).
Ultimately, you need to post code so we know what a "date supplied to a system" looks like.
It can always be identified. (EDIT: Unless you just got a string, like you did.)
There's something like this if you're interested in a TimeZone class.
Use those proper DateFormat Java Docs. Answer your own questions, then ask the ones you can't answer. That's what SO is for.
The Date class is timezone dependent.
One google search prevents a duplicate like this.


text:
Q: What is the fastest/most efficient way to find the least significant set bit in an integer in R? I have the question similar to What's the fastest method to return the position of the least significant bit set in an integer in Python 3? , finding the first set bit in a binary number , and Position of least significant bit that is set for R. I need to find the position of the least significant set bit in an integer in R. The solution proposed by  Spätzle is the following:
unlist(lapply(x, function(z) min(which(as.integer(intToBits(z)) == 1))-1))

Are there more efficient ways to do it?

A: The following is much faster:
f <- function(x){
  log2(bitwAnd(x,-x))
}

For comparison:
g <- function(x){
  unlist(lapply(x, function(z) min(which(as.integer(intToBits(z)) == 1))-1))
}

A quick test:
> library(microbenchmark)
> tests <- floor(runif(1000,1,2^31))
> sum(f(tests) == g(tests)) #just to check
[1] 1000
> microbenchmark(f(tests),g(tests))
Unit: microseconds
     expr      min        lq       mean   median        uq       max neval
 f(tests)   38.435   40.5515   45.82673   42.667   45.1355   146.337   100
 g(tests) 1985.940 2083.9680 2530.79036 2131.218 2287.4280 11749.204   100

A: If you have long vectors and want to go to C++ then the following code might help you (together with Rcpp and the ffs function from strings.h):
#include <Rcpp.h>
#include <strings.h>
using namespace Rcpp;

// [[Rcpp::export]]
Rcpp::IntegerVector lsb(const IntegerVector x)
{
  IntegerVector res(x.size());
  std::transform(x.begin(), x.end(), res.begin(), ffs);
  return(res-1);  # To start from 0
}

Save the code above as a file, say lsb.cpp, and compile it using sourceCpp("lsb.cpp") from the Rcpp package.
It is slightly faster - at least for longer input vectors where the overhead becomes negligible
> x <- floor(runif(10000,1,2^31))
> microbenchmark::microbenchmark(f(x), g(x), lsb(x))
Unit: microseconds
   expr       min         lq        mean    median         uq       max neval
   f(x)   121.771   129.6360   168.91273   133.241   151.0110  1294.667   100
   g(x) 36165.757 40508.1740 50371.45183 42608.686 60460.5270 94664.255   100
 lsb(x)    25.767    26.8015    34.58856    33.035    35.2385   156.852   100


text:
Q: How to make transparent cut in another transparent background? I would like to make tutorial of new elements in layout, where I put another layer on my whole view. Then I would like to cut some places to see the layer underneath. In brief cut out that adjusts to the element underneath.
Now I make another black transparent layout.
Then create another layout with white transparent, but it doesn't clean, delete my area with black transparent so effect is like in picture. This place should be with transparent white to see what is underneath. In code look at @+id/test
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">
[ my linear layout with elements]

                </LinearLayout>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/tutorial"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/tutorial_background">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/test"
            android:layout_width="380dp"
            android:layout_height="32dp"
            android:layout_marginStart="15dp"
            android:layout_marginTop="100dp"
            android:layout_marginEnd="16dp"
            android:background="@color/tutorial_white_background"
            android:padding="8dp" />

        <Button
            android:id="@+id/btnGoToWorkList"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="100dp"
            android:layout_marginEnd="100dp"
            android:layout_marginBottom="100dp"
            android:text="OK, TAKE ME TO WORK LIST"
            app:layout_constraintBottom_toTopOf="@+id/tutorialDontShowAgain"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

        <CheckBox
            android:id="@+id/tutorialDontShowAgain"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:buttonTint="@color/mdtp_white"
            android:text="@string/tutorial_dont_show_again"
            android:textColor="@color/mdtp_white"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Screen test

A: You can do it very easily, by using third party library :
Add this in your root build.gradle file (not your module build.gradle file):
allprojects {
    repositories {
        ...
        maven { url "https://jitpack.io" }
    }
}

Add the library to your module build.gradle
dependencies {
    implementation 'com.github.faruktoptas:FancyShowCaseView:1.3.9'
}

Sample Usage
new FancyShowCaseView.Builder(this/*Pass Your Context Here*/)
        .focusOn(view/*Pass Your View Object On Which You Want To Focus On*/)
        .title("Pass Title Here")
        .build()
        .show();

You can see result here :


text:
Q: Store generated primary key in temp variable db2 I'm in the process of writing batch loading SQL script and I would like to store the generated primary key of an insert statement into a temp variable and use it to reference the foreign key in the other tables. Any ideas?
I'm doing the following:
Y = INSERT INTO X(.....)

INSERT INTO Z(...,Y,);

A: I know in SQL Server you can do:
INSERT INTO MyTable ....
SELECT @Foo = @@IDENTITY

INSERT INTO SomeOtherTable(... fk_col ...) VALUES (... @foo ...)


text:
Q: how to use a variable as object? this is the function in class that i use
public function content($search) {
        $this->dbconnection();
        $search = mysql_real_escape_string($search);

        $q= mysql_query("SELECT title FROM xx WHERE title LIKE '%$search%'");
        $s = mysql_fetch_array($q);
        foreach ($s as $key => $val) {
            $$key = $val;
        }

    }

and on index.php file
$cl= new Class;
$test = $cl->content('cloud');

and question is
how can i echo the variable which i set inside foreach loop?
$test->title; < this is not working for sure, but this explains the thing that i am trying to do.

A: Return the array as an object:
public function content($search)
{
    $this->dbconnection();
    $search = mysql_real_escape_string($search);

    $q = mysql_query("SELECT title FROM xx WHERE title LIKE '%$search%'");
    $s = mysql_fetch_assoc($q);

    return (object)$s;
}

Then in your code:
$cl= new Class;
$content = $cl->content('cloud');
echo $content->title;

Alternatively, you could fetch the row as an object by using mysql_fetch_object

A: Set a public property in your class and assign the title variable to it.  Add this to the top of your class:
public $title = '';

Then assign the variable in your foreach as such:
$this->title = $whatever;

A: I really don't understand what you are trying to do in this code snippet.
Your function content() does not return a Value. So there is nothing saved in your $test Variable.
Your content() Function creates a bunch of Variables with the key Values received from the Query as Name. So if you want to get the Value of your "$title" Variable/key you just have to echo that.
Try:
echo $title;

after you have called the content() function. This should echo you the Value of the title you were searching for, provided your query returned something and "title" as a Key.
If you want to make something like:
$res = $classObject->content('cloud');
echo $res->title;

You will have to create such an Object, which has a title Attribute and return that in your Function.


text:
Q: Mac app: remove trial version when installing licensed App Store version I've developed a Mac app which I'm going to distribute through the Mac App Store.
I've also made a trial version which I want to distribute through my website. When the trial period has passed, the user is presented a link to the App Store so she can buy the actual licensed app.
What I'd like to know is; what is the best way to make sure that when the App Store version is being installed, the trial version is overwritten? What if the trial version is still running? Should I make sure it is killed? Can the App Store install an app if there already exists one with the same name in the Applications directory? I don't want the user to have 2 apps installed with the same name.
Can anyone point me in the right direction?

A: make them ONE app .. same bundle identifier.
One app cannot delete another app
but the appstore can OVERWRITE an existing app IIRC


text:
Q: ERROR IN KERAS CUSTOM LOSS "TypeError: Value passed to parameter 'reduction_indices' has DataType float32 not in list of allowed values: int32, int64" I have defined a custom loss in Keras for the function:
(y - yhat)^2 + (y * yhat).
def customLoss(y_true, y_pred, sample_weight=None):
    y_true = K.cast(y_true, 'float32')
    y_pred = K.cast(y_pred, 'float32')
    loss = K.square(y_true - y_pred) + K.prod(y_true, y_pred)
    loss = loss * K.cast(sample_weights, 'float32')
    return loss

When I run model.fit, it fails on TypeError:
earlystopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss',
                                            mode='min', verbose=1, patience=20)
history = model.fit(Xtrain, ytrain_raw,
                    validation_data=(Xval, yval_raw), batch_size=128,
                    epochs=500, verbose=1, callbacks=[earlystopping],
                    sample_weight=sample_weights)

Error:
TypeError: in user code:

    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:571 train_function  *
        outputs = self.distribute_strategy.run(
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:951 run  **
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2290 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/distribute/distribute_lib.py:2649 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py:533 train_step  **
        y, y_pred, sample_weight, regularization_losses=self.losses)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/compile_utils.py:205 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:143 __call__
        losses = self.call(y_true, y_pred)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/losses.py:246 call
        return self.fn(y_true, y_pred, **self._fn_kwargs)
    <ipython-input-477-99f75f332877>:4 customLoss
        loss = K.square(y_true - y_pred) + K.prod(y_true, y_pred)
    /usr/local/lib/python3.6/dist-packages/keras/backend/tensorflow_backend.py:1716 prod
        return tf.reduce_prod(x, axis, keepdims)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/dispatch.py:180 wrapper
        return target(*args, **kwargs)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/math_ops.py:2196 reduce_prod
        name=name))
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/gen_math_ops.py:6642 prod
        name=name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:578 _apply_op_helper
        param_name=input_name)
    /usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/op_def_library.py:61 _SatisfiesTypeConstraint
        ", ".join(dtypes.as_dtype(x).name for x in allowed_list)))

    TypeError: Value passed to parameter 'reduction_indices' has DataType float32 not in list of allowed values: int32, int64

However, if I remove the K.prod(y_true, y_pred) part, the code runs without any hitches.
def customLoss(y_true, y_pred, sample_weight=None):
    y_true = K.cast(y_true, 'float32')
    y_pred = K.cast(y_pred, 'float32')
    loss = K.square(y_true - y_pred) #+ K.prod(y_true, y_pred)
    loss = loss * K.cast(sample_weights, 'float32')
    return loss

What could be wrong???

A: I believe the error arises from the second argument in your call for K.prod(). This function takes a single tensor x but you have specified two tensors y_true and y_pred.
The error itself arises because the second argument of K.prod() refers to an axis, which must be an integer, not a float.
It sounds like you may want to use tf.keras.layers.multiply() or tf.keras.layers.dot().


text:
Q: Not able to signup a new developer environment (DE) Just signed up for a new Developer Environment (DE) at https://developer.salesforce.com/signup
As usual, fill out the sign up form and click the "Sign me Up" button.
However, this time, after clicking the signup button, the page stops at the same page (signup) and doesn't receive any email for user activation.
Then, I waited for several hours, still no email.
I've also tried different email addresses and the results are all the same.
Is there any changes about developer environment signup?

A: There was some issue in product side and it is resolved now .
You will be able to sign up to developer edition org with out any issues.
Thanks for reporting the issue.


text:
Q: Idiomatic way to initialise std::optional from another std::optional and something else I want to initialise an std::optional from another std::optional and some additional arguments provided that the latter std::optional is not empty. Unfortunately std::optional::optional 4) and 5) are not suitable as the amount of arguments is different.
I was able to come up with the following, but it still feels excessive. I particularly don't like specifying return type for the lambda explicitly.
Is there an better (as in more succinct and more expressive) way to achieve this?
#include <iostream>
#include <optional>
#include <tuple>

struct A {
    A(std::optional<int> oi, float f, char c)
    :
        val{
            [&] () -> decltype(val) /* I don't like specifying type here */ {
                if (oi)
                    return {{*oi, f, c}};
                else
                    return std::nullopt;
            }()
        }
    {
    }

    std::optional<std::tuple<int, float, char>> val;
};

int main()
{
    auto print = [](auto& r) {
        if (r)
            std::cout
                << std::get<0>(*r) << "; "
                << std::get<1>(*r) << "; "
                << std::get<2>(*r) << std::endl;
        else
            std::cout << "nullopt" << std::endl;
    };

    auto one = A({}, 1.0, 'c');
    print(one.val);

    auto two = A(10, 2.0, 'c');
    print(two.val);
}

Live example.

A: Just trust the compiler to do the right thing:
A(std::optional<int> oi, float f, char c) {
    if (oi) {
        val.emplace(*oi, f, c);
    }
}

This is also of course a great use-case for a map() member function†, which you can write as a non-member function:
A(std::optional<int> oi, float f, char c)
    : val(map(oi, [&](int i){ return std::tuple(i, f, c); }))
{ }

†Recently proposed in P0798 by TartanLlama.


text:
Q: compare list elment to a string I have the following list
l=['web','python']

and the following string
st='python, C, something, find'

I want to check if any element in the list is in the string
I tried using
any(x in l for x in st)

however it gives false
seems python can't recognize the element in the string, is there a way to check elements from list to a string if there is a match. i did it successfully using a for a loop and splitting the string to a list however that is not efficient with the real data as it contain a long lists and strings. need something efficient.
thanks

A: You would first need to split the string, or else you will be iterating over the individual characters.
Try this:
l=['web','python']
st='python, C, something, find'

any([x in l for x in st.split(',')]) # True

But this isn't the most efficient. For better performance, you could take a look into using a trie.

A: If your would like to check if any element in the list is in the string
then your code should be
any(x in st for x in l)

A: You can use this method
word_list = ['web','python']
string = 'python, C, something, find'

exist = filter(lambda x : x in string , word_list)
print(list(exist))

output:
['python']

A: You were close. How about:
any(x in l for x in st.replace(',', '').split())

which returns:
True

A different approach:
import re
re.search(r'\b(' + '|'.join(l) + r')\b', st)

The search will return None if there's no match and the match if there is one. You can use it like:
if re.search(r'\b(' + '|'.join(l) + r')\b', st):
    print(f'there was a match: {t.groups()}')
else:
    print('no match')


text:
Q: Error on Tutorial of Firebase for Flutter I got the error after follow the tutorial of Firebase for Flutter: https://codelabs.developers.google.com/codelabs/flutter-firebase/#4.
I'm using Andriod Studio 4.0.1.
dev_dependencies:
  flutter_test:
    sdk: flutter
  cloud_firestore: ^0.14.0+2

Error:
lib/main.dart:84:31: Error: The argument type 'Map<String, dynamic> Function()' can't be assigned to the parameter type 'Map<String, dynamic>'.
 - 'Map' is from 'dart:core'.
      : this.fromMap(snapshot.data, reference: snapshot.reference);
                          ^

Solution from @Peter Haddad:
this.fromMap(snapshot.data(), reference: snapshot.reference);

Another Error:
The following FirebaseException was thrown building MyHomePage(dirty, state: _MyHomePageState#257aa):
[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()

The relevant error-causing widget was:
  MyHomePage     file:///D:/Private/Project/workspace_flutter/baby_names/lib/main.dart:12:13
When the exception was thrown, this was the stack:
#0      MethodChannelFirebase.app (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:118:5)
#1      Firebase.app (package:firebase_core/src/firebase.dart:52:41)
#2      FirebaseFirestore.instance (package:cloud_firestore/src/firestore.dart:43:21)
#3      Firestore.instance (package:cloud_firestore/src/firestore.dart:246:30)
#4      _MyHomePageState._buildBody (package:baby_names/main.dart:35:25)

A: You are using a new version of cloud firestore. Therefore you have to do the following now:
this.fromMap(snapshot.data(), reference: snapshot.reference);


text:
Q: Error: inject Angular $http service into requires plugin I want to use AngularJS $http service in my custom requireJS plugin. The following is my code.
I can see angular module in my plugin "foo", but I don't know how to get $http service from the angular module.
Could anybody give me some direction? Thx in advance.
main.js
require.config({
    waitSeconds : 20, //make sure it is enough to load all scripts
    paths: {
        cordova: '../lib/js/ng-cordova',
        angular: '../lib/js/angular/angular',                   // <---- here is angular
        angularAnimate: '../lib/js/angular/angular-animate',
        angularTouch: '../lib/js/angular/angular-touch',
        angularSanitize: '../lib/js/angular/angular-sanitize',
        uiRouter: '../lib/js/angular-ui/angular-ui-router',
        ionic: '../lib/js/ionic.bundle',
        ionicServiceCore: '../lib/js/ionic-core',
        angularIonic: '../lib/js/ionic-angular'
      }
}

foo.js
define(['angular'],function(angular){

  return {
    load: function(name,req,onLoad,config){
      console.log(angular);
      //
      // I want to use $http here
      // but how to retrieve $http from angular module???
      //
    } // load
  };

});

A: You should be able to get $http service with this code:
define(['angular'], function(angular) {

  return {
    load: function(name, req, onLoad, config) {
        var $http = angular.injector(['ng']).get('$http');
        // $http.get(...).then(...)
    }
  };

});


text:
Q: Another one about Win32 Vs UI Automation I'm building a (Web/WinForms Application I didn't decide yet) and I have a running simple WinForms Application that I couldn't access through my new application by any means and I just want to read some values and maybe edit some values (Labels, Buttons, some trivial stuff). so I used Spy++ as advised in this question.
So, I was able to see the values that I need to read/edit through this great tool. and I was able to edit some values (Like hide, Uncheck, Disable, etc on some labels and buttons) and they reflected on the application.
So I want to move to the next step and I was advised that I have two options. Whether Win32 or UI Automation. I have no clue about both of them, so a little guidance would be great.
I just have 3 more questions regarding this problem:

*

*which would be better to use against WinForms and why?

*and does any of the two options can be used through a WebApplication or both options need to be implemented within a WinForms Application ?

*Does any of those options have a limitation in editing values ?

A: (If you are still searching..)
It depends on what is mor familiar to you. Also, generally, I think, UI Automation is slightly easier, since for Wind32SDK you need to use a lot of pinvoke and stuff like that which probably does not come easy to pure .net people.
For Win32, http://www.pinvoke.net/default.aspx/ is really the one greatest place to start, giving you all the signatures and some sample code.
For UI Automation, there are a lot of places as well to start with lots of samples. One among many is http://blogs.msdn.com/b/winuiautomation/ .
Also note that they are not comparable in power and usability. Like said, UI Automation is more natural, Win32 also allows you to access many values you cannot reach through automation. I think UI Automation is mostly read-only.
It is fun to enable/disable a button in a foreign application. When finding out that it often works I thought to use it on some protected commercial product (that simply has the "pro" buttons disabled") just to check if there is an additional protection in place. :) Meaning as well that if you want to have such a feature in your app, know that a user can always make a hidden element visible or a disabled one enabled.


text:
Q: Spring JPA and form filter I have a web page with a search form (with name and surname fields) and a table of persons. When user inserts a name n and a surname s I have to show the persons with name like n and surname like s. When user inserts only the name I have to filter only by name and the same when user inserts only the surname.
My searchPersons method in Controller looks like:
@RequestMapping(value = RouteConfig.SEARCH_PERSONS)
public @ResponseBody Page<Person> searchPersons(@ModelAttribute Person p, Pageable pageable) {
    return pazienteRepository.findAll(where(nameIsLike(p.getName())).and(surnameIsLike(p.getSurname())), pageable);
}

I write a PersonSpecifications class:
public class PersonSpecifications {

    public static Specification<Person> nomeIsLike(String name) {
        return (Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) ->
                cb.like(cb.lower(root.<String>get(Person_.nome)), getLikePattern(name));
    }

    public static Specification<Person> surnameIsLike(String surname) {
        return (Root<Person> root, CriteriaQuery<?> query, CriteriaBuilder cb) ->
             cb.like(cb.lower(root.<String>get(Person_.surname)), getLikePattern(surname));
    }

Now if I have name and surname my search is ok. The problem is when name or surname is not valued in the web form.
What's the best practice in this situation?

A: You can just put a check for name and surname both having values, in your searchPersons method. If name != null, add name condition, if surname != null add surname condition. As long as 1 condition was added, execute query.


text:
Q: instance has no attribute while passing it to instance method I am trying to pass a method attribute local_filename of get_img_url to ImgurDownload but getting the error
"AttributeError: ImgurDownload instance has no attribute 'local_filename'"

Is it possible to make local_filename available in the global scope so other methods can access it?
import re, os, glob, sys
import requests
from bs4 import BeautifulSoup
import pdb
import pprint

# imgur url pattern
imgurUrlPattern = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?')

class ImgurDownload():

    #local_filename = None

    def __init__(self, link_url, target_subreddit, submissionid):
        self.link_url = link_url
        self.target_subreddit = target_subreddit
        self.submissionid = submissionid

    def download_image(self):
        response = requests.get("{}".format(self.link_url))
        if response.status_code == 200:
            #pdb.set_trace()

            #------------->2. local_filename is what i want to get from get_img_url <------------
            print('Downloading %s...' % self.local_filename)
            with open(self.local_filename, 'wb') as fo:
                for chunk in response.iter_content(4096):
                    fo.write(chunk)

    def get_img_url(self):

        if "imgur.com/" not in self.link_url:
            pass # skip non-imgur submissions

        if len(glob.glob('reddit_%s_%s_*' % (self.target_subreddit, self.submissionid))) > 0:
            pass # we've already downloaded files for this reddit submission

        if 'http://i.imgur.com/' in self.link_url:
            # The URL is a direct link to the image.
            mo = imgurUrlPattern.search(self.link_url) # using regex here instead of BeautifulSoup because we are pasing a url, not html

            imgurFilename = mo.group(2)
            if '?' in imgurFilename:
                # The regex doesn't catch a "?" at the end of the filename, so we remove it here.
                self.imgurFilename = imgurFilename[:imgurFilename.find('?')]

            #--------------------> 1. I want this instance var to be passed on to ^ download_image method <~-----------------------
            self.local_filename = 'reddit_%s_%s_album_None_imgur_%s' % (self.target_subreddit, self.submissionid, imgurFilename)
            self.download_image()

    def print_self_dict(self):
        pprint.pprint(self.__dict__)

sample = "http://i.imgur.com/yhemck6.jpg"
x = ImgurDownload('http://i.imgur.com/C5uIWlD.jpg','brogress','2cgwwn')
print x.download_image()
#x.print_self_dict()

A: self.local_filename is only defined if a) you call get_img_url first and b) the link contains imgur.com. In your example, you haven't done a).

A: When self.local_filename variable is accessed in download_image() method python will check for the local_filename instance variable. Yet because this variable was not set as an instance variable before it was accessed in download_image(), python will throw you an AttributeError.
We have assure that this variable is instantiated before accessing it. The best approach is to instantiate it inside the init(). Then when it comes to download_image(), it haves an initialized local_filename variable appended in to self.


text:
Q: Create a loop that includes both a code chunk and text I am trying to figure out how to create a loop that inserts some text into the rmarkdown file, and then produces the graph or table that corresponds to that header. The following is how I picture it working:
for(i in 1:max(month)){
### `r month.name[i]` Air quaility

```{r, echo=FALSE}
plot(airquality[airquality$Month == 5,])
```
}

This ofcourse just prints the for loop as text, if i surround the for loop with r`` I would just get an error.
I want the code to produce an rmd file that looks like this:
May Air Quality
Plot
June Air Quality
Plot
and so on and so forth.
Any ideas?  I cannot use latex because I at my work they do not let us download exe files, and I do not know how to use latex anyways. I want to produce a word document.

A: You can embed the markdown inside the loop using cat().
Note: you will need to set results="asis" for the text to be rendered as markdown.
Note well: you will need two spaces in front of the \n new line character to get knitr to properly render the markdown in the presence of a plot out.
# Monthly Air Quality Graphs
```{r pressure,fig.width=6,echo=FALSE,message=FALSE,results="asis"}

attach(airquality)
for(i in unique(Month)) {
  cat("  \n###",  month.name[i], "Air Quaility  \n")
  #print(plot(airquality[airquality$Month == i,]))
  plot(airquality[airquality$Month == i,])
  cat("  \n")
}
```

A: As mentioned here, you could also make use of the pander package:
# Monthly Air Quality Graphs
```{r pressure2, fig.width=6, echo=FALSE, message=FALSE, results="asis"}
library(pander)
for (i in unique(airquality$Month)) {
   # Inserts Month titles
   pander::pandoc.header(month.name[i], level = 3)
   # Section contents
   plot(airquality[airquality$Month == i,])
   # adding also empty lines, to be sure that this is valid Markdown
   pander::pandoc.p('')
   pander::pandoc.p('')
}
```

A: Under some conditions I find it helpful to write a loop that writes chunk code rather than write a chunk that runs a loop. Weird solution but it has worked for me beautifully in the past when a bare bones set of chunks is all I need. For your airquality case it would look like this:
## model chunk ##

# ## May Air Quality
# ```{r May}
#
# plot(airquality[airquality$Month == 5,])
#
# ```

# all months in airquality
aqmonths <- c("May",
            "June",
            "July",
            "August",
            "September")

for (m in aqmonths) {
  cat(
    paste0(
      "## ", m, " Air Quality",
      "\n\n",
      "```{r ", m, "}",
      "\n\n",
      "plot(airquality[airquality$Month == ", match(m, months), ",])",
      "\n\n",
      "```",
      "\n\n"
    )
  )
}

This will print code for all 5 chunks to the console, and then I can copy and paste into a .Rmd document. It is possible to include any chunk options such as captions or fig arguments in the chunk-writing loop as well. Depending on what else you try to bring in, using functions like match() as in the example is often helpful.
Pros: Preserves ability to use cross-references and set individual captions or options.
Cons: Making changes to all chunks usually requires re-copying the entire output of the chunk-writing loop, which can be tiresome and a bit unwieldy.

A: What about reusing the chunks inside a loop using <<label>> as described here: https://bookdown.org/yihui/rmarkdown-cookbook/reuse-chunks.html
Label your chunk, set eval=F
 ```{r my_chunk, echo=FALSE, eval=F}
plot(airquality[airquality$Month == 5,])
```

Then loop
for(i in 1:max(month)){
<<my_chunk>>
}