text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Asynchronous transactions in MySQL InnoDB? I want to implement parallel processing of multiple DB transactions which lock only a few rows for short periods of time. For Example we have this query executed every time an user opens the page:
START TRANSACTION;
SELECT * FROM table_1 WHERE worktime < UNIX_TIMESTAMP() FOR UPDATE;
...WORK...
...UPDATE...
COMMIT;
In a multiuser environment, this kind of row locking would lead to Deadlocks every time the select statement would be executed. Currently I would solve the problem using a second table to store the locked IDs:
START TRANSACTION;
LOCK TABLE table_1 WRITE, table_locks WRITE;
SELECT id FROM table_1 WHERE worktime < UNIX_TIMESTAMP() AND id NOT IN table_locks;
...insert locked Ids into Table "table_locks"...
...this prevents other calls to read from this table...
UNLOCK TABLES;
COMMIT;
...Perform calculations and Updates...
DELETE FROM table_locks WHERE id = ...
The problem of this method is, that if something goes wrong after "locking" a row by storing its ID in the table_locks table, this Row would never be updated anymore. Of course I can set a timeout to release such locks automatically after some time, but this doesen't seem properly done to me. But is there something possible like:
SELECT * FROM table_1 WHERE worktime < UNIX_TIMESTAMP() AND NOT LOCKED BY OTHER TRANSACTION FOR UPDATE
?
A: You could mark rows to be done by your session:
UPDATE table_1
SET marked_by_connection_id = CONNECTION_ID(),
marked_time = NOW()
WHERE worktime < UNIX_TIMESTAMP() AND marked_by_connection_id IS NULL;
Then you can feel free to work on any row that has your connection id, knowing that another session will not try to claim them:
SELECT * FROM table_1 WHERE marked_by_connection_id = CONNECTION_ID();
. . .
No locking or non-autocommit transaction is needed.
At the end of your session, unmark any rows you had marked:
UPDATE table_1 SET marked_by_connection_id = NULL
WHERE marked_by_connection_id = CONNECTION_ID();
Or alternatively your app could unmark individual rows as it processes them.
But perhaps your session dies before it can unmark those rows. So some rows were marked, but never processed. Run a cron job that clears such abandoned marked rows, allowing them to get re-processed by another worker, although a bit late.
UPDATE table_1 SET marked_by_connection_id = NULL
WHERE marked_time < NOW() - INTERVAL 30 MINUTE;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24311206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I make a Two argument python function? Is anyone able to help me on the below, I am struggling to understand what the question means by "where {person} is replaced by the first name in the visitors to be identified as a member." The below code is my attempt but I am not sure how to incorporate visitors into the function too...
members = ['Danny', 'Alex', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']
def check_group(members,visitors):
for m in members:
if m == 'Danny':
return f'Member present: {m}.'
else:
return 'No members.'
check_group(members, visitors)
A: You have to loop over the visitors and then check if the visitor is a member. If you reach the end of the loop you haven't found any member and return "No members".
members = ['Danny', 'Alex', 'Kieran', 'Zoe', 'Caroline']
visitors = ['Scott', 'Helen', 'Raj', 'Danny']
def check_group(members, visitors):
for visitor in visitors:
if visitor in members::
return f'Member present: {visitor}.'
return 'No members.'
check_group(members, visitors)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68190876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: modify url by clicking a div I have a page in php, and I'm trying to add an ?id=variable_value extension to it's url when I click on a div, but when I click it gives me an undefined url error with the extension
Here is the script:
<script language="javascript" type="text/javascript">
var Pokemon_ID = 1;
function changeUrl() {
location.href=this.href+'?id='+Pokemon_ID;return false;
}
document.getElementById( 'right-btn' ).onclick = function() {
changeUrl();
};
</script>
And the div :
<div id="right-btn" href="pokedex.php" onclick="changeUrl()">
A: Don't use two separate ways of attaching handlers when you only need one. Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead.
The problem is that when assigning the handler via onclick, the this in changeUrl is undefined, because the calling context is global. Feel free to avoid using this when it can cause confusion.
Just use addEventListener alone. Also, you'll have to use getAttribute('href') instead of .href because divs are not supposed to have href properties.
const Pokemon_ID = '5';
document.getElementById('right-btn').addEventListener('click', function(e) {
// location.href = e.target.getAttribute('href') + '?id=' + Pokemon_ID;
console.log('changing URL to ' + e.target.getAttribute('href') + '?id=' + Pokemon_ID);
});
<div id="right-btn" href="pokedex.php">text</div>
A: Try this instead:
location.href += '?id=' + Pokemon_ID;
A: Because you call changeUrl() within the onclick method you loose the context of this. This in changeUrl is not your div. Maybe you have to pass this into the method with changeUrl(this) or you just pass the href with changeUrl(this.href).
Than use:
function changeUrl(target){
location.href=target.href+'?id='+Pokemon_ID;
}
A: As mentioned by CertainPerformance above, you are not passing the right arguments to you function to work correctly; Using you code as a reference, you can either pass the original event to you changeUrl() function, then use the e.target to get to your 'right-btn' element.
Javascript:
var Pokemon_ID = 1;
function changeUrl(e) {
var href = e.target.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl(e);
};
HTML:
<div id="right-btn" href="pokedex.php">Click Me 4</div>
However, if you realy want to use this in your function to refer to the 'right-btn' element, then you can change the code to;
Javascript:
var Pokemon_ID = 1;
function changeUrl() {
var href = this.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl.call(e.target);
};
The changes being the call in the event handler:
changeUrl.call(e.target);, which calls you function in the 'context' of the e.target, making the this in your changeUrl() function to the element. Then you can use the this as in var href = this.getAttribute('href');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49959525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it safe to use integers as hash keys? Is it safe to use integers as hash keys?
my %hash;
my $str = ...
for $str.NFC {
%hash{$_} = ...
}
A:
A normal Hash coerces all its keys to strings:
my %a = '1' => 'foo', 2 => 'bar';
say %a.pairs.perl; # ("1" => "foo", "2" => "bar").Seq
Note how the second key became the string "2", even though it was originally passed to the Hash as an integer.
When you do hash look-ups, the subscript is also automatically converted to a string before it is used:
say %a{"2"}.perl; # "bar"
say %a{2}.perl; # "bar"
Note how the subscript 2 correctly found the element with key "2".
The conversion from integers to strings is well-defined in Perl 6, yielding a unique string for each unique integer, so the example you gave is fine.
If you don't want your Hash keys to be converted to strings, you can override the key handling using the {} notation in the declaration:
my %b{Any} = '1' => 'foo', 2 => 'bar';
say %b.pairs.perl; # ("1" => "foo", 2 => "bar").Seq
say %b{"1"}.perl; # "foo"
say %b{1}.perl; # Any
say %b{"2"}.perl; # Any
say %b{2}.perl; # "bar"
Note how in this case the second key 2 stays an integer, and doing a look-up with the string subscript "2" does not find it, nor does the subscript 1 find the entry with key "1".
%b{Any} means "accept keys of any type, and don't coerce them". This is sometimes called an 'object Hash' because it can map from any object to a value.
%b{Int} would mean "accept only Int keys, and don't coerce them". In this case you'll get an error if you even try to use anything that isn't already an Int.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44955867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Save Visual Studio Build Configuration Currently I use Visual Studio 2013 and I want to use my own build configuration (like Debug or Release for example) which I've created in project A, in project B. Is there a possibility to save and import a build config in general and to use it in other projects?
Jonas
A: To my understanding, this is not possible directly, as the representation of the configuration is implicitly represented in the solution file (*.sln) and the project file (*.vcproj) by its name and conditions; however, similar to the answer to this question, the project files can be edited manually and similar parts can be factored out using the Import element, which is documented here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30421967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android camera doesn't work after cordova compile I just compiled my cordova project to a .apk for android. You can open the (android) camera with a button.
When I was debugging my project the camera opened when you clicked on said button, but after compiling the project and installing it on my android smartphone, it wouldn't open the camera anymore.
Do you know how to make sure the camera opens, if you need more information, please let me know.
The camera opens with this code
HTML
<button onclick="capturePhotoWithData()">Capture Photo With Image Data</button>
Javascript / JQuery
function onPhotoDataSuccess(imageData) {
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
alert('Failed because: ' + message);
}
function capturePhotoWithData() {
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29609379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback): initialization failed Goal: Run a GPT-2 model instance.
I am using the latest Tensorflow and Hugging Face Transformers.
*
*Tensorflow - 2.9.1
*Transformers - 4.21.1
Notebook:
pip install tensorflow
pip install transformers
from transformers import pipeline, set_seed
generator = pipeline('text-generation', model='gpt2')
set_seed(42)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
ImportError: numpy.core.multiarray failed to import
The above exception was the direct cause of the following exception:
SystemError Traceback (most recent call last)
SystemError: <built-in method __contains__ of dict object at 0x7f5b58a64d00> returned a result with an error set
The above exception was the direct cause of the following exception:
ImportError Traceback (most recent call last)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
1001 try:
-> 1002 return importlib.import_module("." + module_name, self.__name__)
1003 except Exception as e:
~/anaconda3/envs/python3/lib/python3.8/importlib/__init__.py in import_module(name, package)
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _gcd_import(name, package, level)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _find_and_load(name, import_)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _load_unlocked(spec)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap_external.py in exec_module(self, module)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/__init__.py in <module>
36 from ..utils import HUGGINGFACE_CO_RESOLVE_ENDPOINT, http_get, is_tf_available, is_torch_available, logging
---> 37 from .audio_classification import AudioClassificationPipeline
38 from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/audio_classification.py in <module>
19 from ..utils import add_end_docstrings, is_torch_available, logging
---> 20 from .base import PIPELINE_INIT_ARGS, Pipeline
21
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/base.py in <module>
33 from ..feature_extraction_utils import PreTrainedFeatureExtractor
---> 34 from ..modelcard import ModelCard
35 from ..models.auto.configuration_auto import AutoConfig
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/modelcard.py in <module>
43 )
---> 44 from .training_args import ParallelMode
45 from .utils import (
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/training_args.py in <module>
25 from .debug_utils import DebugOption
---> 26 from .trainer_utils import (
27 EvaluationStrategy,
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/trainer_utils.py in <module>
46 if is_tf_available():
---> 47 import tensorflow as tf
48
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/__init__.py in <module>
36
---> 37 from tensorflow.python.tools import module_util as _module_util
38 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/__init__.py in <module>
36 from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
---> 37 from tensorflow.python.eager import context
38
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/eager/context.py in <module>
34 from tensorflow.python import tf2
---> 35 from tensorflow.python.client import pywrap_tf_session
36 from tensorflow.python.eager import executor
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/client/pywrap_tf_session.py in <module>
18 from tensorflow.python import pywrap_tensorflow
---> 19 from tensorflow.python.client._pywrap_tf_session import *
20 from tensorflow.python.client._pywrap_tf_session import _TF_SetTarget
ImportError: initialization failed
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_4924/2487422996.py in <cell line: 1>()
----> 1 from transformers import pipeline, set_seed
2
3 generator = pipeline('text-generation', model='gpt2')
4 set_seed(42)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _handle_fromlist(module, fromlist, import_, recursive)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in __getattr__(self, name)
990 value = self._get_module(name)
991 elif name in self._class_to_module.keys():
--> 992 module = self._get_module(self._class_to_module[name])
993 value = getattr(module, name)
994 else:
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
1002 return importlib.import_module("." + module_name, self.__name__)
1003 except Exception as e:
-> 1004 raise RuntimeError(
1005 f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
1006 f" traceback):\n{e}"
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback):
initialization failed
def query(payload, multiple, min_tokens, max_tokens):
nlp_setup()
list_dict = generator(payload, min_length=min_tokens, max_new_tokens=max_tokens, num_return_sequences=multiple)
return [d['generated_text'].split(payload)[1].strip() for d in list_dict
output = query("Banking customer's needs:", 3000, 50, 50)
RunTime, SystemError and ImportError all occur during import of transformers:
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback): initialization failed
A: Changed Kernel: conda_tensorflow2_p38
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73247922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Storing references to components created at runtime Given the following Blazor component:
@foreach (var col in columns)
{
@foreach (row in rows)
{
<MyInput @onkeydown="KeyDown" @ref="NewInput"></MyInput>
}
}
@code {
private List<MyInput> inputs = new List<MyInput>();
private MyInput NewInput
{
get { return _NewInput; }
set
{
_NewInput = value;
inputs.Add(_NewInput);
}
}
MyInput _NewInput;
private async Task KeyDown(KeyboardEventArgs args)
{
if (args.Code == "ArrowDown")
{
//TODO: Find out which dynamic MyInput-instance
// within the inputs collection triggered the event
}
}
}
I'm trying to add cursor navigation between the MyInputs using the arrow keys. For this to work, I obviously need to know which MyInput component triggered the key-event.
I managed to store all MyInput instances into a List by abusing the @ref property, but I can't figure out which instance within my list triggered the event.
Does Blazor offer any way to find out which dynamically created MyInput-instance triggered the event?
A: Suppose you've defined a component named"
ChildComponent.razor
<div>@ID.ToString()</div>
@code {
[Parameter]
public int ID { get; set; }
}
Which has a parameter property ID, provided by the parent component, like this:
ParentComponent.razor
@for (int i = 0; i < 10; i++)
{
<ChildComponent @ref="component" ID="i" />
}
@code
{
private ChildComponent component { set => components.Add(value); }
List<ChildComponent> components = new List<ChildComponent>();
protected override void OnInitialized()
{
foreach (var component in components)
{
Console.WriteLine(component.ID);
}
}
}
Now, you can identify the component by its ID. A simple and effective way, though you may do that in other ways.
Note: This is wrong:
<MyInput @onkeydown="KeyDown" @ref="NewInput"></MyInput>
because you assign the name of a method, the "KeyDown", to the @onkeydown compiler directive, which is only applicable to Html tags, not to component.
You can do something like this:
<MyInput ID="id" @ref="NewInput"></MyInput>
ID should be a parameter property defined in MyInput component, which is a child component, mind you. You also have to define an EventCallback which should be triggered from an event handler for the keydown event. In the cuurent case the EventCallback should return to the parent component, the ID of the child component in whose html tag, say an input html element, the keydown event occurs. I hope you succeed to get what I'm saying... if not, don't hesitate to ask questions.
UPDATE:
Note: I've added some code to my previous code sample to demonstrate how to return the ID of each ChildComponent when you hit the KeyDown button of an input Html element embedded in each child component. Additionally, my code also demonstrate how to return a reference to each component when its KeyDown event takes place:
ChildComponent.razor
<input type="text" @onkeydown="@KeyDown" />
@code {
[Parameter]
public int ID { get; set; }
// [Parameter]
// public EventCallback<int> CallBack { get; set; }
[Parameter]
public EventCallback<ChildComponent> CallBack { get; set; }
private void KeyDown(KeyboardEventArgs args)
{
// if (args.Code == "ArrowDown")
// {
// InvokeAsync(() => { CallBack.InvokeAsync(ID); });
// }
if (args.Code == "ArrowDown")
{
InvokeAsync(() => { CallBack.InvokeAsync(this); });
}
}
}
ParentComponent.razor
<div>@output</div>
@for (int i = 0; i < 10; i++)
{
<ChildComponent CallBack="ShowID" @ref="component" ID="i" />
}
@code
{
private ChildComponent component { set => components.Add(value); }
List<ChildComponent> components = new List<ChildComponent>();
protected override void OnInitialized()
{
foreach (var component in components)
{
Console.WriteLine(component.ID);
}
}
private string output = "";
// private void ShowID(int id)
// {
// output = id.ToString();
// }
private void ShowID(ChildComponent child)
{
output = child.ID.ToString();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66861129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Life cycle of an iphone app? I am confused of how an iphone app goes when it start running. I mean when I am trying to write a app, I get confused and lost of terms like "viewDidLoad", "viewDidUnload", "dealloc", "applicationDidLoad" etc. I have no idea when one comes first, which one comes later when an app runs. For instance, say, I would like to add a view(or picture) showing my app logo when the app is just opened (just like what most apps would do). So, where (viewDidLoad or applicationDidLoad) should I put my code in?
Well, this is just an example. I will appreciate it if you can tell me the answer. But what I am most concerned is about the life cycle of running a app, i.e at which state, which method will be called. Thanks in advance!
A: To start, you might want to know this:
the first code you get to run after the application has finished launching, is the one you put in the Application Delegate in the method application:didFinishLaunchingWithOptions. The app delegate is the class that is set to receive general notifications about what's going on with the app, like it finished launching :)
The other kind of 'notifications' of changes in the state of the app, or the life cycle of views are:
-viewDidLoad
-viewWillAppear:animated:
-viewDidAppear:animated:
-viewWillDisappear:animated:
-viewDidDisappear:animated:
-viewDidUnload
Those methods are declared in UIViewController, and you can implement them in your UIViewController subclasses to customize the behaviour of a view in those situations (each method name is self explanatory)
The life cycle of an app is pretty well covered here: http://developer.apple.com/library/ios/documentation/iphone/conceptual/iphoneosprogrammingguide/iphoneappprogrammingguide.pdf page 27
About showing a logo when the app launches, apps achieve that setting a "splash" image by putting its name in the info.plist property-list file, in the UILaunchImageFile key.
A: I think the official developer guide delivered by apple will help you. This is the link:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7261449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: serializing separate address string into one in javascript you may already know how to parse an address into separate sections such as unit number / street number / street name / town / state and etc...
Almost similar issue here. I want to serialize those separately entered data into one. For example, I have
Level /
Unit number /
Street number /
Street name /
Street type /
Town /
State /
Post code / Etc...
Let's say user entered
blank / blank / 10 / Flinders / lane / blank / VIC / 3000
Then I would like to have the information in one string like
10 Flinders Lane VIC 3000
I'm currently doing this as the follow
if (level !== '' && level !== 0) {string = level + '/';}
if (unit !== '' && unit !== 0) {string += unit;}
if (streetNo !== '' && streetNo !== 0) {string += '/' + streetNo + ' ';}
else {string += ' ';}
string += streetName + ' ' + streetType + ' ';
if (town !== '' && town !== '--' && town !== 0) {string += town + ' ';}
else {string += ' ';}
string += state;
it is hard coded but I cannot come up with any better way. I would like to know if there is any better and efficient + professional way to achieve this.
A: Because the delimiters you want on the string seem to vary according to which part of the string they follow (some have '/', others have ' '), there's probably not a lot you can do there.
If the delimiter were always the same (such as a space), you might use an array and then use join:
var parts = [];
if (level !== '' && level !== 0) parts.push(level);
if (unit !== '' && unit !== 0) parts.push(unit);
if (streetNo.g !== '' && streetNo.g !== 0) parts.push(streetNo.g);
if (streetName !== '' && streetName !== 0) parts.push(streetName);
if (streetType !== '' && streetType !== 0) parts.push(streetType);
if (town !== '' && town !== 0 && town !== '--') parts.push(town);
if (state !== '' && state !== 0) parts.push(state);
string = parts.join(' ' );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18175026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tachograph Card Authentication I am trying to remote authentication for tachograph. I have a problem between tachograph and can bus communication. i am successful open session 10 7E and send company card ATR. But when i passed to authentication of company card.
i send : 0x31,0x01,0x01,0x80,0x03.
tacho respond: 10 0C 71 01 01 80 04 00
i send fc : 30 00 14 00 00 00 00 00
but tacho not respond me. Can anyone give me any idea?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71719495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the difference between static_cast and Implicit_cast? What is implicit_cast? when should I prefer implicit_cast rather than static_cast?
A: Prefer implcit_cast if it is enough in your situation. implicit_cast is less powerful and safer than static_cast.
For example, downcasting from a base pointer to a derived pointer is possible with static_cast but not with implicit_cast. The other way around is possible with both casts. Then, when casting from a base to a derived class, use implicit_cast, because it keeps you safe if you confuse both classes.
Also keep in mind that implicit_cast is often not needed. Using no cast at all works most of the time when implicit_cast does, that's where 'implicit' comes from. implicit_cast is only needed in special circumstances in which the type of an expression must be exactly controlled, to avoid an overload, for example.
A: I'm copying over from a comment i made to answer this comment at another place.
You can down-cast with static_cast. Not so with implicit_cast. static_cast basically allows you to do any implicit conversion, and in addition the reverse of any implicit conversion (up to some limits. you can't downcast if there is a virtual base-class involved). But implicit_cast will only accept implicit conversions. no down-cast, no void*->T*, no U->T if T has only explicit constructors for U.
Note that it's important to note the difference between a cast and a conversion. In the following no cast is going on
int a = 3.4;
But an implicit conversion happens from double to int. Things like an "implicit cast" don't exist, since a cast is always an explicit conversion request. The name construct for boost::implicit_cast is a lovely combination of "cast using implicit conversions". Now the whole implementation of boost::implicit_cast is this (explained here):
template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }
The idea is to use a non-deduced context for the parameter t. That will avoid pitfalls like the following:
call_const_version(implicit_cast(this)); // oops, wrong!
What was desired is to write it out like this
call_const_version(implicit_cast<MyClass const*>(this)); // right!
The compiler can't deduce what type the template parameter Dst should name, because it first must know what identity<Dst> is, since it is part of the parameter used for deduction. But it in turn depends on the parameter Dst (identity could be explicitly specialized for some types). Now, we got a circular dependency, for which the Standard just says such a parameter is a non-deduced context, and an explicit template-argument must be provided.
A: implicit_cast transforms one type to another, and can be extended by writing implicit cast functions, to cast from one type to another.
e.g.
int i = 100;
long l = i;
and
int i = 100;
long l = implicit_cast<long>(i);
are exactly the same code
however you can provide your own implicit casts for your own types, by overloading implicit_cast like the following
template <typename T>
inline T implicit_cast (typename mpl::identity<T>::type x)
{
return x;
}
See here boost/implicit_cast.hpp for more
Hope this helps
EDIT
This page also talks about implicit_cast New C++
Also, the primary function of static_cast is to perform an non changing or semantic transformation from one type to another. The type changes but the values remain identical e.g.
void *voidPtr = . . .
int* intPtr = static_cast<int*>(voidPtr);
I want to look at this void pointer, as if it was an int pointer, the pointer doesn't change, and under the covers voidPtr has exactly the same value as intPtr.
An implicit_cast, the type changes but the values after the transformation can be differnet too.
A: Implicit conversions, explicit conversions and static_cast are all different things. however, if you can convert implicitly, you can convert explicitly, and if you can convert explicitly, you can cast statically. The same in the other direction is not true, however. There is a perfectly reasonable relationship between implicit casts and
static casts. The former is a subset of the the latter.
See section 5.2.9.3 of the C++ Standard for details
Otherwise, an expression e can be
explicitly converted to a type T using
a static_cast of the form static_-
cast(e) if the declaration T t(e);
is well-formed, for some invented
temporary variable t (8.5).
C++ encourages use of static_casts because it makes the conversion 'visible' in the program. Usage of casts itself indicates some programmer enforced rule which is worth a look so better use static_cast.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/868306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Build vim with --remote-tab on OSX I built vim using:
./configure --with-x --enable-pythoninterp --with-features=huge
but don't have access to vim --remote-tab. I'm using OSX version 10.11.2. I'm hoping to use Vim and not MacVim since I'm using tmux too.
Here's the output of vim --version if it's helpful:
vim --version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Apr 5 2016 09:24:37)
MacOS X (unix) version
Included patches: 1-658
Compiled by *******
Huge version without GUI. Features included (+) or not (-):
+acl +farsi +mouse_netterm +syntax
+arabic +file_in_path +mouse_sgr +tag_binary
+autocmd +find_in_path -mouse_sysmouse +tag_old_static
-balloon_eval +float +mouse_urxvt -tag_any_white
-browse +folding +mouse_xterm -tcl
++builtin_terms -footer +multi_byte +terminfo
+byte_offset +fork() +multi_lang +termresponse
+cindent -gettext -mzscheme +textobjects
-clientserver -hangul_input +netbeans_intg +title
+clipboard +iconv +path_extra -toolbar
+cmdline_compl +insert_expand -perl +user_commands
+cmdline_hist +jumplist +persistent_undo +vertsplit
+cmdline_info +keymap +postscript +virtualedit
+comments +langmap +printer +visual
+conceal +libcall +profile +visualextra
+cryptv +linebreak +python +viminfo
-cscope +lispindent -python3 +vreplace
+cursorbind +listcmds +quickfix +wildignore
+cursorshape +localmap +reltime +wildmenu
+dialog_con -lua +rightleft +windows
+diff +menu -ruby +writebackup
+digraphs +mksession +scrollbind -X11
-dnd +modify_fname +signs -xfontset
-ebcdic +mouse +smartindent -xim
+emacs_tags -mouseshape -sniff -xsmp
+eval +mouse_dec +startuptime -xterm_clipboard
+ex_extra -mouse_gpm +statusline -xterm_save
+extra_search -mouse_jsbterm -sun_workshop -xpm
system vimrc file: "$VIM/vimrc"
user vimrc file: "$HOME/.vimrc"
2nd user vimrc file: "~/.vim/vimrc"
user exrc file: "$HOME/.exrc"
fall-back for $VIM: "/usr/local/share/vim"
Compilation: gcc -c -I. -Iproto -DHAVE_CONFIG_H -DMACOS_X_UNIX -g -O2 -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=1
Linking: gcc -L/usr/local/lib -o vim -lm -lncurses -liconv -framework Cocoa -framework Python
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36432158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: awesomewm remap tag display I'm trying to remap my the tag display feature thats traditionally mapped to modkey, "Control", "#" .. i + 9. I have removed any other instance of {modkey, "Tab"} mappings in my rc.lua, and attempted to replace the word Control with the word Tab. However, despite the rc compiling it the command doesn't run. I have no idea why this might be hopefully one of you more experienced users will be able to see my issue.
awful.key({ modkey, "Tab" }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
awful.tag.viewtoggle(tag)
end
end,
{description = "toggle tag #" .. i, group = "tag}),
A: As Uli says in the comment, what can and cannot be a modified is a constraint coming from Xorg. It cannot be Tab.
But. With awful.keygrabber, you can create a keybinding on modkey+Tab, then from that callback, start the keygrabber and intercept the number keys from there. When the keygrabber detect Tab is released, then stop it. There is multiple built-in methods and property to make this rather easy.
See https://awesomewm.org/apidoc/core_components/awful.keygrabber.html for more details.
Just take the Alt+Tab example (link above) and modify it to fit your use case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68708320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: hbase for storing gamers' last 1000 key hits So for my use case, I need to save only the last 1000 key hits of each gamer. and there will be only 2 fields --> gamerId (all numeric) and keyId (also all numeric). so, lets say, gamer 1123 already has 999 keyIds stored, when the 1000th keyId comes in for that gamer, normal insertion. however, once 1001st keyId comes in, we need to remove the earliest recorded keyId for that gamer and persist that 1001st in. so, at all times, there can only be max 1000 keyIds for each gamer in the db. We have +/- 100 million of gamers and very high keyId traffic, and this table will be looked up and written into very frequently.
will HBase be suitable for this? if it's not, what could be the alternative?
Thanks
A: In principle, you can get this done in hbase very easily thanks to versioning. I've never tried something as extreme at 1,000 versions per column (normally 5-10) but I don't think there is any specific restriction as to how many versions you can have. You should just see if it creates any performance implications. Also check out this discussion: https://www.quora.com/Is-there-a-limit-to-the-number-of-versions-for-an-HBase-cell
When you define your table and your column family, you can specify the max versions parameter. This way, when you simply keep doing the Puts with the same row value, the key for that row will keep generating new versions (they will all be time-stamped as well. Once you do your 1,001th Put, the 1st put will automatically be deleted, and so on on the FIFO basis. Similarly, when you do a Get on that row-key, you can use various methods to retrieve a range of versions. In that case it depends on what API you will be using to get the values (this is easy to do with native Java API, but not sure about other access methods).
100mln rows is quite small for HBase, so generally it shouldn't be a problem. But of course if each of your rows really has 1,000 versions, then you are looking at 100bln key-values. Again, I'd say it's doable for HBase, but you should see imperially whether this causes any performance problems and you should size your cluster appropriately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67796121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: i am not able to remove grayscale via jquery my css code
.content-img {
-webkit-transition: all 1s ease;
-moz-transition: all 1s ease;
-o-transition: all 1s ease;
-ms-transition: all 1s ease;
transition: all 1s ease;
-webkit-filter:grayscale(100%);
}
my jquery
$('.content-img').hover(function () {
$(this).css('-webkit-filter', 'grayscale(0)');
});
I just wanted to write jQuery. it doesnt work.
A: Why do you need to use jQuery at all?
You can use this:
.content-img:hover {
-webkit-filter: grayscale(0%);
filter: grayscale(0%);
}
Here, I made you this fiddle using css only, with :hover selector.
But be careful, filter has limited support, look at filter article on MDN.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23931234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I use spring boot datasource to get connection object so as to use it with conn.executeQuery() manually? I am working on spring boot application with Mysql backend and trying to use springboots datasource Bean to get connection object so as to use it with the following stmts:
stmt =conn.createStatement()
stmt.executeQuery("show tables");
which is expected to return the table list. Below is the code of connection class:
public class Test {
@Autowired
DataSource datasource;
public void test1(){
System.out.println("Inside Test Method");
try {
Connection conn = datasource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("show tables");
while (rs.next()) {
System.out.println(rs.getString("TableNames"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(NullPointerException e){
System.out.println("Null Pointer exception");
}
}
}
But the datasource object is throwing null value and hence it doesnt return any connection object.
Following is the application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
driver-class-name: com.mysql.jdbc.Driver
username: ****
password: ****
initial-size: 1
max-idle: 2
max-active: 3
Ideally the datasource object should read these properties and be able to return connection object. Not sure if my understanding is correct.
Can anyone help me out in figuring the issue pls ?
A: I think spring boot automated this process completely. One doesn't have to inject the data source manually & connection pool mechanism is also automated. Just adding the connection properties and pool properties in yaml file or properties file under src/main/resources. It will inject the data source for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39037011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Do channel ids for guide categories (like music) change in the YouTube Data API? After fetching the list of channels from the guide with the guideCategories endpoint, a list of kind youtube#guideCategory is returned. These IDs can be used to get a list of channels from the channels endpoint for the given category.
My question is do these IDs change? Can I store this list of guide categories and reuse them for multiple languages/regions?
A: Assuming it works the same way as VideoCategories do, the IDs should work for and remain consistent across any region that supports it.
For example, when I used the API explorer and specified USA, Germany, or Australia for the region, the guideCategory ID for Music (GCTXVzaWM) was available for all three, so that guideCategory is supported in and will work for all three of those regions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32697350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: set readonly property to false for an html text input on clicking on Edit I need to set readonly false when i click on Edit and when i click on edit button should change to save button. i made two input box type="submit". i need to make all the fields editable when i click on edit. please help me to find out the answer.
<form role="form" data-toggle="validator" method="post">
<div class="container padd bpadd">
<?php if(isset($account_list)){ print_r($account_list);exit;
}?>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Name -->
<div class="form-group">
<div class="form-item">
<input type="text" name="RMName" value="<?= isset($accountList['name']) ? $accountList['name'] : '' ?>" id="inputName" readonly="readonly" class="readonlyinput"/>
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input type="email" id="inputEmail" name="inputEmail" value="<?= isset($accountList['email']) ? $accountList['email'] : '' ?>" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<!--
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input type="password" name="password"value="<?= isset($accountList['password']) ? $accountList['password'] : '' ?>" id="InputPassword" readonly="readonly" />
</div>
</div>
</div>
-->
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input type="text" name="dob" value="<?= isset($accountList['dob']) ? $accountList['dob'] : '' ?>" id="InputDob" readonly="readonly" class="readonlyinput"/>
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input name="Phone" type="text" id="InputNumber" value="<?= isset($accountList['phone_number']) ? $accountList['phone_number'] : '' ?>" readonly="readonly" class="readonlyinput"/>
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Name -->
<div class="form-group">
<div class="form-item">
<input type="text" name="OrgName" value="<?= isset($accountList['organisation']) ? $accountList['organisation'] : '' ?>" id="InputOrgName" readonly="readonly" class="readonlyinput"/>
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Name -->
<div class="form-group">
<div class="form-item">
<input type="text" name="OrgId" value="<?= isset($accountList['organisation_id']) ? $accountList['organisation_id'] : '' ?>" id="InputOrgId" readonly="readonly" class="readonlyinput"/>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-item">
<div class="form-group">
<input type="text" name="City" value="<?= isset($accountList['city']) ? $accountList['city'] : '' ?>" id="InputCity" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-item">
<div class="form-group">
<input type="text" name="State" value="<?= isset($accountList['state']) ? $accountList['state'] : '' ?>" id="InputState" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-item">
<div class="form-group">
<input type="text" name="Country" value="<?= isset($accountList['country']) ? $accountList['country'] : '' ?>" id="InputCountry" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
</div>
</div>
<div class="bbutton">
<footer class="footer text-center">
<div class="button-panel">
<div class="bbutton">
<input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle()"/>
<a><input type="submit" class="button" title="Save" value="SAVE" hidden="hidden"/></a>
</div>
</div>
</footer>
</div>
</form>
</div>
<script>
function inputToggle()
{
}
</script>
A: Use this function. Suppoesing .edit class of edit button
$('.edit').on('click', function(){
$('input').prop('readonly',true);
});
But don't set this property initially
A: Use .prop to toggle readonly property of the :input elements.
Also note, e.preventDefault() as submit button will submit and relaod the form.
var edit = true;
function inputToggle(e) {
e.preventDefault();
$(':input').prop('readonly', edit = !edit);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form role="form" data-toggle="validator" method="post">
<div class="container padd bpadd">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Name -->
<div class="form-group">
<div class="form-item">
<input type="text" name="RMName" value="" id="inputName" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input type="email" id="inputEmail" name="inputEmail" value="" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input type="text" name="dob" value="" id="InputDob" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="form-item">
<div class="form-group">
<input name="Phone" type="text" id="InputNumber" value="" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Name -->
<div class="form-group">
<div class="form-item">
<input type="text" name="OrgName" value="" id="InputOrgName" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-12 col-sm-12 col-xs-12">
<!-- Name -->
<div class="form-group">
<div class="form-item">
<input type="text" name="OrgId" value="" id="InputOrgId" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-item">
<div class="form-group">
<input type="text" name="City" value="" id="InputCity" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-item">
<div class="form-group">
<input type="text" name="State" value="" id="InputState" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="form-item">
<div class="form-group">
<input type="text" name="Country" value="" id="InputCountry" readonly="readonly" class="readonlyinput" />
</div>
</div>
</div>
</div>
</div>
<div class="bbutton">
<footer class="footer text-center">
<div class="button-panel">
<div class="bbutton">
<input type="submit" class="button" title="Edit" value="EDIT" onclick="inputToggle(event)" />
<a>
<input type="submit" class="button" title="Save" value="SAVE" hidden="hidden" />
</a>
</div>
</div>
</footer>
</div>
</form>
Fiddle demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36468817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Bitnami GitLab 5.2.0: gitlab_sidekiq not running and could not be started We are using Bitnami GitLab 5.2.0.
We stumbled upon that we can't push into new repository, like
[email protected]:sandbox/testgit2.git,
but we can work with old ones. Closer investigation showed that gitlab_sidekiq is not running.
/opt/bitnami/ctlscript.sh restart gitlab_sidekiq
gitlab_sidekiq could not be started
Where to look? Should I update first?
UPDATE: Bitnami GitLab 5.2 server is broken down: can't push code into new repositories.
(While old repositories are unaffected)
TestProject4>git remote add origin git
@192.168.133.10:sandbox/testproject4.git
TestProject4>git push -u origin master
fatal: '/opt/bitnami/apps/gitlab/repositories/sandbox/testproject4.git' does not appear to be a git repository
fatal: The remote end hung up unexpectedly
UPDATE WITH ANSWERS:
I am using virtual machine in VirtualBox on my PC (in 1 team as pilot moving the VM to some VM host)
Yes, I modified gitlab.yml
/opt/bitnami/apps/gitlab/htdocs/log/sidekiq.log has this lines in repetition, so they should give clue (look like some thing wrong when reading some file)
DEPRECATION WARNING: You have Rails 2.3-style plugins in vendor/plugins! Support for these plugins will be removed in Rails 4.0. Move them out and bundle them in your Gemfile, or fold them in to your app as lib/myplugin/* and config/initializers/myplugin.rb. See the release notes for more on this: http://weblog.rubyonrails.org/2012/1/4/rails-3-2-0-rc2-has-been-released. (called from <top (required)> at /opt/bitnami/apps/gitlab/htdocs/config/environment.rb:5)
/opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse': (<unknown>): found character that cannot start any token while scanning for the next token at line 73 column 1 (Psych::SyntaxError)
from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse_stream'
from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:151:in `parse'
from /opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:127:in `load'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:113:in `initialize'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:71:in `new'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:71:in `instance'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/settingslogic-2.0.8/lib/settingslogic.rb:48:in `[]'
from /opt/bitnami/apps/gitlab/htdocs/config/initializers/1_settings.rb:38:in `<top (required)>'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `block in load'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:236:in `load_dependency'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/activesupport-3.2.13/lib/active_support/dependencies.rb:245:in `load'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:588:in `block (2 levels) in <class:Engine>'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:587:in `each'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/engine.rb:587:in `block in <class:Engine>'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `instance_exec'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:30:in `run'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:55:in `block in run_initializers'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `each'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/initializable.rb:54:in `run_initializers'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/application.rb:136:in `initialize!'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.13/lib/rails/railtie/configurable.rb:30:in `method_missing'
from /opt/bitnami/apps/gitlab/htdocs/config/environment.rb:5:in `<top (required)>'
from /opt/bitnami/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
from /opt/bitnami/ruby/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:55:in `require'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/lib/sidekiq/cli.rb:199:in `boot_system'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/lib/sidekiq/cli.rb:47:in `parse'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/sidekiq-2.8.0/bin/sidekiq:7:in `<top (required)>'
from /opt/bitnami/ruby/bin/sidekiq:23:in `load'
from /opt/bitnami/ruby/bin/sidekiq:23:in `<main>'
GitLab says it requires ruby 1.9.3, but here I see 1.9.1. Can that be problem?
A: It is strange. What are you using, the installer, the virtual machine or the cloud image? If the sidekiq server is not running it is possible that the repository was not created properly. Could you check if there is any error in the sidekiq log file?
/opt/bitnami/apps/gitlab/htdocs/logs/sidekiq.log
Did you modify any configuration file for GitLab?
EDITED:
The problem seems a wrong configuration in the gitlab.yml. It is also important the white spaces. Could you check your change in that file?
/opt/bitnami/ruby/lib/ruby/1.9.1/psych.rb:203:in `parse': (): found character that cannot start any token while scanning for the next token at line 73 column 1 (Psych::SyntaxError)
GitLab CI ships Ruby 1.9.3 latest stable version. The folder name uses 1.9.1 for backguard compatibility Why is my gem "INSTALLATION DIRECTORY:" ...1.9.1 when the "RUBY VERSION:" is 1.9.3
Please post the gitlab.yml file if you do not find the exact error.
A: In my case I had <tab> in my yml file.
It's quite strange error though!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17690321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Group by and foreach I want to print only once the title and all related images id_post
table IMAGES
id_images | dir_image | post_id
1 image1.jpg 1
2 image2.jpg 1
3 image3.jpg 1
4 image4.jpg 1
5 image5.jpg 2
6 image6.jpg 2
7 image7.jpg 2
8 image8.jpg 2
table POSTS
id_post | slug | title
1 title_post Title Post
2 title_post_2 Title Post 2
PHP code:
$slug = $_GET['slug'];
$stmt = $DB_con->prepare("SELECT * FROM posts, images
WHERE posts.id_post = images.post_id
AND slug=:slug");
$stmt->execute(array(":slug"=>$_GET['slug']));
while($row=$stmt->fetch(PDO::FETCH_BOTH))
{
?>
<h1><?php print utf8_encode($row['title']);?></h1>
<?php
}
?>
Accessing the page "Title post 2", the result is:
Title post 2
image5.jpg
Title post 2
image6.jpg
Title post 2
image7.jpg
Title post 2
image8.jpg
How to get the result:
Title post 2
image5.jpg
image6.jpg
image7.jpg
image8.jpg
How I enter the SQL statement the "group by" to group images:
SELECT * FROM posts, images
WHERE posts.id_post = images.post_id
AND slug=:slug
And then inside the while inserting a foreach with the images of the group by?
while($row=$stmt->fetch(PDO::FETCH_BOTH))
{
?>
<h1><?php print utf8_encode($row['title']);?></h1>
<?php
}
?>
Inserting if not solve for me, it will be necessary to create several ifs
A: If you just want to do it in procedural PHP, you could do something like this:
$runningTitle = '';
while($row=$stmt->fetch(PDO::FETCH_BOTH)) {
if ($row['title'] != $runningTitle) {
$runningTitle = $row['title'];
print "<h1>";
print utf8_encode($row['title']);
print "</h1>";
}
// now render images.
}
However I would recommend using a more object orientated approach to build the html string and then return it as a single string, to echo at the end, rather than rendering everything out procedurally. It's often tidier to complete all your program logic before rendering a page, rather than rendering while you are still asking the code to make decisions.
You are using PHP in it's traditional form - as a templating language. It has come a long way since then.
A: It's some easy and fast and if your "join" images are few, not many.
Your group by, use a GROUP BY and get all images concatenated by SEPARATOR with GROUP_CONCAT
SELECT
posts.*,
COUNT(0) total,
GROUP_CONCAT(dir_image SEPARATOR '|') images
FROM
posts
INNER JOIN images ON (posts.id_post = images.post_id )
WHERE
slug=:slug
GROUP BY
id_post
This is your loop, create an array exploding the SEPARATOR over field "images" and do the loop
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
$aImages = explode('|', $row['images']);
?>
<h1><?php print utf8_encode($row['title']); ?></h1>
<div>
<ul>
<?php
echo '<li>' . implode('</li><li>', $aImages) . '</li>'
?>
</ul>
</div>
<?php
}
?>
Or
while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
$aImages = explode('|', $row['images']);
?>
<h1><?php print utf8_encode($row['title']); ?></h1>
<div>
<?php
foreach ($aImages as $sImage) {
?>
<a href="<?php echo $sImage;?>"><?php echo $sImage; ?></a>
<?php
}
?>
</div>
<?php
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36168046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: threading: function seems to run as a blocking loop although i am using threading I am trying to speed up web scraping by running my http requests in a ThreadPoolExecutor from the concurrent.futures library.
Here is the code:
import concurrent.futures
import requests
from bs4 import BeautifulSoup
urls = [
'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=ibfxcfd&showcategories=CFD',
'https://www.interactivebrokers.eu/en/index.php?f=41634&exch=chix_ca',
'https://www.interactivebrokers.eu/en/index.php?f=41634&exch=tase',
'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=chixen-be&showcategories=STK',
'https://www.interactivebrokers.eu/en/index.php?f=41295&exch=bvme&showcategories=STK'
]
def get_url(url):
print(url)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
a = soup.select_one('a')
print(a)
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as executor:
results = {executor.submit( get_url(url)) : url for url in urls}
for future in concurrent.futures.as_completed(results):
try:
pass
except Exception as exc:
print('ERROR for symbol:', results[future])
print(exc)
However when looking at how the scripts print in the CLI, it seems that the requests are sent in a blocking loop.
Additionaly if i run the code by using the below, i an see that it is taking roughly the same time.
for u in urls:
get_url(u)
I have add some success in implementing concurrency using that library before, and i am at loss regarding what is going wrong here.
I am aware of the existence of the asyncio library as an alternative, but I would be keen on using threading instead.
A: You're not actually running your get_url calls as tasks; you call them in the main thread, and pass the result to executor.submit, experiencing the concurrent.futures analog to this problem with raw threading.Thread usage. Change:
results = {executor.submit( get_url(url)) : url for url in urls}
to:
results = {executor.submit(get_url, url) : url for url in urls}
so you pass the function to call and its arguments to the submit call (which then runs them in threads for you) and it should parallelize your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65206486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: mysql query show only 1 result i want to output the result based on todays date.
the problem is, the output only show 1 result?
database report table:
id | r_amount | id_therapist | date | time | t_tanning | t_deep
// this query works fine echoing all the result if i use while loop
$today = date('Y-m-d');
(1) $q = $db->query("SELECT * FROM report WHERE date='$today' ORDER BY date ASC")
// this query only show 1 output result?
(2) $q = $db->query("SELECT *, SUM(IF(t_tanning LIKE 'Pro Tan%', r_amount, 0)) AS totalProTan FROM report WHERE date='$today' ORDER BY date ASC")
while($r = $q->fetch_array(MYSQLI_ASSOC)) :
// (1) echoing all result from database
echo $r['r_amount'].'<br>';
// (2) echoing only 1 result????
echo $r['totalProTan'].'<br>';
endwhile;
A: If the date field is of type datetime, you'll have to do something like
SELECT ... WHERE DATE(date)=CURDATE()
Notice that I'm using curdate() in the query. There's no need to generate the date value in PHP. MySQL is perfectly capable of doing that itself.
A: Try adding a GROUP BY statement to the second SQL statement.
*
*you should group by the key of the elemnts you want to be shown in the end result
A: The use of the aggregate function SUM will result in a single result. You are asking the database to get all the rows then sum up a value and give you the value.
To see the result for many groups of values you have to add a group by clause.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5638014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UISearchBar stays when seguing to another view controller via push I followed this guide: http://www.jhof.me/simple-uisearchcontroller-implementation/
The only difference in my code is
instead of self.tableView.tableHeaderView = self.searchController.searchBar;
I have self.navigationItem.titleView = self.searchController.searchBar;
When I segue from the results table view controller, the uisearchbar stays in the navigation bar.
A: I rewrite the sample from Apple, you can see I comment self.tableView.tableHeaderView = self.searchController.searchBar; then set it to navigation bar's title view, just like you. You can find search bar is here in snapshot.
- (void)viewDidLoad {
[super viewDidLoad];
APLResultsTableController *qresultsTableController = [[APLResultsTableController alloc] init];
self.resultsTableController = qresultsTableController;
_searchController = [[UISearchController alloc] initWithSearchResultsController:qresultsTableController];
self.searchController.searchResultsUpdater = self;
[self.searchController.searchBar sizeToFit];
// self.tableView.tableHeaderView = self.searchController.searchBar;
self.navigationItem.titleView = self.searchController.searchBar;
self.searchController.hidesNavigationBarDuringPresentation = NO;
// we want to be the delegate for our filtered table so didSelectRowAtIndexPath is called for both tables
self.resultsTableController.tableView.delegate = self;
self.searchController.delegate = self;
self.searchController.dimsBackgroundDuringPresentation = NO; // default is YES
self.searchController.searchBar.delegate = self; // so we can monitor text changes + others
// Search is now just presenting a view controller. As such, normal view controller
// presentation semantics apply. Namely that presentation will walk up the view controller
// hierarchy until it finds the root view controller or one that defines a presentation context.
//
self.definesPresentationContext = YES; // know where you want UISearchController to be displayed
}
snapshot is here,
UISearchBarController has a property named hidesNavigationBarDuringPresentation default is YES, set it to NO if you want to use it as navigation item's title view
self.searchController.hidesNavigationBarDuringPresentation = NO;
I have tested, it works. hope it helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37758849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to fix "Error Connection Timed Out Error" of a codeigniter website on a godaddy server? I have uploaded a basic codeigniter website on godaddy server without any database connection. In the config file base url is set to the domain name, index_page is blank & uri_protocol is set to request_uri. I also have the .htaccess file with the code but not sure what to do in it. Here what should i do to remove this error?
I have tried playing with the base url and uri_protocol and also made changes to the .htaccess file but no help either.
My .htaccess code -
Options +FollowSymLinks
RewriteEngine on
# Send request via index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
A: Have your /folder/app/.htaccess like this:
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /folder/app/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule>
then in /folder/app/application/config/config.php you need to have this config:
$config['base_url'] = '';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54004299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i format a string as currency in a data bound DataGrid in WPF C#? I have some data being shown in a DataGrid. The data comes from SQL, where a "money" type can be null. When i display this data, all is OK when i format the data in a double column format as currency. ie:
internal void FillGrid()
{
bD = new DataTable();
DataTable dt = EmployerQuery(); //queries the SQL DB
bD.Columns.Add(new DataColumn("ID", typeof(int)));
bD.Columns.Add(new DataColumn("EmployerName", typeof(string)));
bD.Columns.Add(new DataColumn("FlatMinAmount", typeof(double)));
bD.Columns.Add(new DataColumn("DistrictRate", typeof(double)));
bD.Columns.Add(new DataColumn("VendorRate", typeof(double)));
bD.Columns.Add(new DataColumn("Description", typeof(string)));
bD.Columns.Add(new DataColumn("EmployeeCount", typeof(int)));
foreach (DataRow sqlRow in dt.Rows)
{
var row = bD.NewRow();
row["ID"] = sqlRow["ClientID"];
row["EmployerName"] = sqlRow["OfficialName"];
row["FlatMinAmount"] = sqlRow["FlatMinAmount"];
row["DistrictRate"] = sqlRow["DistrictRate"];
row["VendorRate"] = sqlRow["VendorRate"];
row["Description"] = sqlRow["Description"];
row["EmployeeCount"] = sqlRow["EmployeeCount"];
bD.Rows.Add(row);
}
However, I then save the data as a .csv file. When i read that file back, the values for "FlatMinAmount" that were null are not allowed to be inserted into a column type double, so I cannot format the data columns as type double, since many are null.
<dg:DataGrid Name="newGrid" ItemsSource="{Binding ElementName=readGrid, Path=readGrid}" AutoGenerateColumns="False"
Margin="5" Height="175" Width="Auto" ColumnWidth="Auto">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Binding="{Binding ID}" Header="Employer ID" Width="Auto" IsReadOnly="True"/>
<dg:DataGridTextColumn Binding="{Binding EmployerName}" Header="Employer Name" Width="Auto" IsReadOnly="True"/>
<dg:DataGridTextColumn Binding="{Binding FlatMinAmount, StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>
<dg:DataGridTextColumn Binding="{Binding DistrictRate, StringFormat=C}" Header="District Rate" Width="Auto" IsReadOnly="True"/>
<dg:DataGridTextColumn Binding="{Binding VendorRate, StringFormat=C}" Header="Vendor Rate" Width="Auto" IsReadOnly="True"/>
<dg:DataGridTextColumn Binding="{Binding Description}" Header="Description" Width="Auto" IsReadOnly="True"/>
<dg:DataGridTextColumn Binding="{Binding EmployeeCount}" Header="EmployeeCount" Width="*" IsReadOnly="True"/>
</dg:DataGrid.Columns>
</dg:DataGrid>
DataTable r = new DataTable();
try
{
//string csv = string.Empty;
//r.Columns.Add("ID", typeof(int));
//r.Columns.Add("EmployerName", typeof(string));
//r.Columns.Add("FlatMinAmount",typeof(double));
//r.Columns.Add("DistrictRate", typeof(double));
//r.Columns.Add("VendorRate", typeof(double));
//r.Columns.Add("Description", typeof(string));
//r.Columns.Add("EmployeeCount", typeof(int));
r.Columns.Add("ID");
r.Columns.Add("EmployerName");
r.Columns.Add("FlatMinAmount");
r.Columns.Add("DistrictRate");
r.Columns.Add("VendorRate");
r.Columns.Add("Description");
r.Columns.Add("EmployeeCount");
// Read sample data from CSV file
using (CsvFileReader reader = new CsvFileReader(filename))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
//foreach (string s in row)
{
r.Rows.Add(row[0], row[1], row[2], row[3], row[4], row[5], row[6]);
}
}
}
(readGrid is then set to r in code-behind)
If they are string, then i cannot use the StringFormat=C in the binding to show $ etc. Also, it seems I cannot style a DataGridTextColumn. So, how can i display the values I read in from .csv as $xx.xx?
A: use Double.Parse() - http://msdn.microsoft.com/en-us/library/system.double.parse.aspx to format the value when you read it in. This will allow you to use double and you can then apply the appropriate formatting for output.
Updated:
The issue you seem to be having that when reading from file the value is null and when reading from database it is DBNull. By default DataTable allows for DBNull values. If you want to mimic this for read, try the following
DataTable r = new DataTable();
try
{
r.Columns.Add("ID");
r.Columns.Add("EmployerName");
r.Columns.Add("FlatMinAmount");
r.Columns.Add("DistrictRate");
r.Columns.Add("VendorRate");
r.Columns.Add("Description");
r.Columns.Add("EmployeeCount");
// Read sample data from CSV file
using (CsvFileReader reader = new CsvFileReader(filename))
{
CsvRow row = new CsvRow();
while (reader.ReadRow(row))
{
//foreach (string s in row)
{
double d;
double? val2 = null;
double? val3 = null;
double? val4 = null;
if (Double.TryParse(row[2], out d)) val2 = d;
if (Double.TryParse(row[3], out d)) val3 = d;
if (Double.TryParse(row[4], out d)) val4 = d;
r.Rows.Add(row[0], row[1], val2, val3, val4, row[5], row[6]);
}
}
}
A: Use the TargetNullValue attribute:
<dg:DataGridTextColumn Binding=""{Binding FlatMinAmount,TargetNullValue='Not Specified',StringFormat=C}" Header="FlatMinAmount" Width="Auto" IsReadOnly="True"/>
A: If you know the number is null, can't you just set the value of the column to DBNull?
row["FlatMinAmount"] = DBNull.Value;
Here's a little console app I ran to show this working:
class Program
{
static void Main(string[] args) {
DataTable tbl = new DataTable();
DataColumn col = new DataColumn("Blah", typeof(double));
tbl.Columns.Add(col);
DataRow row = tbl.NewRow();
row["Blah"] = DBNull.Value;
Console.WriteLine("Result: " + row["Blah"].ToString());
Console.ReadKey();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13272144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ag grid not retrieving data when mounted with vue using axios I have this strange case when trying to retrieve data from mongoDB using axios not showing on grid. It should be already successful given the data can already loaded into the view (already tested it), but it's nowhere inside beforeMount, mounted, or ready hook.
I already tried with
this.gridOptions.onGridReady = () => {
this.gridOptions.api.setRowData(this.ticketData)
}
but only yields partial success (unreliable),
here's a code snippet to show what I mean,
<template>
<div class="ticketing">
<ag-grid-vue style="width: 100%; height: 350px;"
class="ag-fresh"
:gridOptions="gridOptions"
>
</ag-grid-vue>
{{testData}} <!--testData can be loaded-->
<input type="button" @click.prevent="showData" value="test"> </div>
</template>
<script>
//import stuff
//header and url stuff
export default {
//component stuff
data () {
return {
gridOptions: null,
ticketData: [],
testData: [] // only for testing purpose
}
},
methods: {
showData () {
console.log('data shown')
this.testData = this.ticketData // this is working
}
},
beforeMount () {
var vm = this
axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}})
.then(function (response) {
vm.ticketData = response.data
}) // this is working
.catch(function (error) {
console.log(error)
})
this.gridOptions = {}
this.gridOptions.rowData = this.ticketData // this is not working
this.gridOptions.columnDefs = DummyData.columnDefs
}
// mount, ready also not working
}
</script>
To be more specific, I still can't determine what really triggers onGridReady of ag-grid in conjunction with Vue component lifecycle, or in other words, how can I replace button to show testData above with reliable onGridReady/Vue component lifecycle event?
A: You define vm.ticketData and after you call it like this.ticketData
You can change it by: this.rowData = vm.ticketData
A: You are setting this.gridOptions.rowData outside of the axios callback, so this.ticketData is still empty.
Set it inside the callback:
mounted() {
var vm = this
axios.get(ticketingAPIURL, {'headers': {'Authorization': authHeader}})
.then(function (response) {
vm.ticketData = response.data
vm.gridOptions = {}
vm.gridOptions.rowData = vm.ticketData
vm.gridOptions.columnDefs = DummyData.columnDefs
})
.catch(function (error) {
console.log(error)
})
}
A: it is due to overlapped intialization between axios, ag-grid, and vue.
after much tinkering, I am able to solve it with using Vue's watch function:
watch: {
isAxiosReady(val) {
if (val) {
this.mountGrid() // initiate gridOptions.api functions
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46011034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: unexpected character '?' express When I run my server.js file I get a syntax error with something along the lines like the following:
Unexpected character ? in the file @babel\core\lib\transformation\normalize-file.js:209
When I try to execute my server.js with following code:
import path from 'path';
import express from 'express';
var app = express();
var port = 3000;
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
But its fine if I run it with following code:
import http from 'http';
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
There seems to be an issue with express and babel maybe?
I'll add the package.json and the .babelrc below:
package.json:
{
"name": "counter",
"version": "0.0.1",
"private": true,
"devDependencies": {
"@babel/cli": "^7.0.0",
"@babel/core": "^7.0.1",
"@babel/node": "^7.0.0",
"@babel/plugin-syntax-dynamic-import": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"babel-plugin-dynamic-import-node": "^2.1.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"express": "^4.16.3",
"nodemon": "^1.18.4",
"path": "^0.12.7",
"react": "^16.5.1",
"react-dom": "^16.5.1",
"react-scripts": "^1.1.4"
},
"dependencies": {
"prop-types": "^15.6.1",
"react-redux": "^5.0.7",
"redux": "^3.5.2"
},
"scripts": {
"start": "nodemon --exec babel-node server\\server.js ",
"build": "react-scripts build",
"eject": "react-scripts eject",
"test": "react-scripts test"
}
}
.babelrc:
{
"presets": ["@babel/preset-react","env"],
"plugins": ["@babel/plugin-syntax-dynamic-import","dynamic-import-node"]
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52357650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Nested ALOGD statement I have situation where:
#define DBG_ALOGD(a) ALOGD("%s:%d: ", __FUNCTION__, __LINE__); ALOGD a
#define DBG_MSG(a) do { if (debuggable) {DBG_ALOGD(a);} } while (0)
DBG_MSG(a) used by the applications to print the logs.
DBG_MSG("Hi %d", 2);
will print as
LOG_TAG: function_name:121
LOG_TAG: Hi 2
I wanted combine FUNCTION:LINE along with the "Hi 2" in single line.
I tried
#define DBG_ALOGD(a) ALOGD("%s:%d:%s", __FUNCTION__, __LINE__, a)
#define DBG_MSG(a) do { if (debuggable) {DBG_ALOGD(a);} } while (0)
It didn't worked as a is not a plain string it also have %d
Please suggest how can I change the #define to have a combination of these.
A: I think you can use the macro variable parameters (variadics) :
#include <stdio.h>
#define DBG_ALOGD(fmt, ...) ALOGD("%s:%d: " fmt, __FUNCTION__, __LINE__, __VA_ARGS__ );
#define DBG_MSG(fmt, ...) do { if (debuggable ) {DBG_ALOGD(fmt, __VA_ARGS__ );} } while (0)
int main(void)
{
int debuggable = 1;
DBG_MSG("%s(%d)\n", "test", 0);
DBG_MSG("%s", "hello");
return 0;
}
I tested it with printf function instead of ALOGD, but I think that the result will be the same.
Warning, you will not be able to call directly DBG_MSG("simple string") since the compiler will wait for something not empty in ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48740108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Symfony3 - Validation of an embedded form I have an embedded form like this:
-> Parent (class)
|---> Attribute 1 (collection) : children (class) : required
.......|-----> Attribute 1 : child_name (string) : required
.......|-----> Attribute 2 : child_description (string) : required
I want, when I send the form:
*
*There is at least one parent object sent (I mean the children attribute contains at least one row of (child_name and child_description)
If the data received will be like this :
*
*parent[children][__name__][child_name]=value1&parent[children][__name__][child_description]=value2
Where name is the iteration in the ArrayCollection of the attribute children
So when we send two children in the form, we get this data:
*
*parent[children][0][child_name]=value1&parent[children][0][child_description]=value2&parent[children][1][child_name]=value3&parent[children][1][child_description]=value4
I want that:
*If the user will send only nothing (empty form), he gets an error that the atribute children is required.
*If the user will send only the child_name (or the child_description) value, he gets an error that the child_description (or the child_name) is also required. I mean if he doesn't event send the varaible child_name (or child_description) in the form like this:
*
*parent[children][__name__][child_name]=value1 (without the name and the value of the variable parent[children][__name__][child_description])
I tried to validate this form from the Entity But I got some problems.
In the Parent Entity class:
/**
* Parent
*
* @ORM\Table(name="parent")
* @ORM\Entity
*/
class Parent
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var \Doctrine\Common\Collections\ArrayCollection
*
* @Assert\NotBlank(message="Error", groups={"Creation"})
* @Assert\NotNull(message="Error", groups={"Creation"}))
* @Assert\Count(
* min = 1,
* minMessage = "Error",
* groups={"Creation"}
* )
* @ORM\OneToMany(targetEntity="Children", mappedBy="parent", cascade={"ALL"}, orphanRemoval=true)
*/
protected $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
/**
* Add child
*
* @param Child $child
* @return children
*/
public function addChild(Child $child)
{
$this->children[] = $child;
$child->setParent($this);
return $this;
}
/**
* Remove child
*
* @param Child $child
*/
public function removeChild(Child $child)
{
$this->children->removeElement($child);
}
public function getChildren()
{
return $this->children;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
}
Then, the Child Entity class:
/**
* Child
*
* @ORM\Table(name="child")
* @UniqueEntity(
* fields={"child_name","child_description"},
* message="already registred"
* )
*/
class Child
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var Parent
*/
private $parent;
/**
* @ORM\Column(name="child_name", type="string", length=255 )
*
* Assert\NotBlank(message="empty", groups={"Creation"})
* Assert\NotNull(message="null", groups={"Creation"})
* @Assert\Length(
* min=3,
* minMessage="too short",
* groups={"Creation"}
* )
* @Assert\Type(
* type="string",
* message="you need a string",
* groups={"Creation"}
* )
*/
private $child_name;
/**
* @ORM\Column(name="child_description", type="string", length=255 )
*
* Assert\NotBlank(message="empty", groups={"Creation"})
* Assert\NotNull(message="null", groups={"Creation"})
* @Assert\Length(
* min=3,
* minMessage="too short",
* groups={"Creation"}
* )
* @Assert\Type(
* type="string",
* message="you need a string",
* groups={"Creation"}
* )
*/
private $child_description;
public function __construct()
{}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set childName
*
* @param string $childName
*
* @return Child
*/
public function setChildName($childName)
{
$this->child_name = $childName;
return $this;
}
/**
* Get childName
*
* @return string
*/
public function getChildName()
{
return $this->child_name;
}
/**
* Set childDescription
*
* @param string $childDescription
*
* @return Child
*/
public function setChildDescription($childDescription)
{
$this->child_description = $childDescription;
return $this;
}
/**
* Get childDescription
*
* @return string
*/
public function getDescription()
{
return $this->child_description ;
}
In the Controller class:
public function postChildrenAction(Request $request)
{
$result = new Parent();
$em = $this->get('doctrine.orm.entity_manager');
$form = $this->createForm(ParentType::class, $result, array(
'validation_groups' => array('Creation', 'Default'),
));
$form->submit($request->request->get($form->getName()));
if ($form->isSubmitted() && $form->isValid()) {
//persistance
}
}
In the ParentType class :
class ParentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('children', CollectionType::class,array(
'entry_type' => ChildType::class,
'required'=> true,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'constraints' => array(new Valid()), // __LINE_A__
'entry_options' => array(
'validation_groups' => $options['validation_groups'],
'required'=> true,
),
));
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'Path\NameBundle\Entity\Parent',
'csrf_protection' => false,
'validation_groups' => array('Creation', 'Default'),
'cascade_validation' => true,
'error_bubbling' => false,
]);
}
}
And finally the ChildType:
class ChildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('child_name',TextType::class,array('required'=> true,'validation_groups'=>$options['validation_groups']));
$builder->add('child_description',TextType::class,array('required'=> true,'validation_groups'=>$options['validation_groups']));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => 'Path\NameBundle\Entity\Child',
'csrf_protection' => false,
'validation_groups' => array('Creation', 'Default'),
'cascade_validation' => true,
'error_bubbling' => false,
]);
}
}
*The first problem is in the Parent Entity class: when I remove the Assert\Count() constraint from the children attribute, the validation will succeed. So why the constraints NotBlank and NotNull doesn't work ?
*If I comment the line 'constraints' => array(new Valid()) (__LINE_A__) in the ParentType, the constraint UniqueEntity of ChildType will not work. Why ?
*None of the 'required' => true options in the ParentType and ChildType worked. When I send only the child name without a description (or the inverse), I got an SQL error saying that there is a null value of the description.
*When the form is empty the validation will succeed but I need to get an error when some data is missing (for the child object or the parent object).
*The groups option from the Parent/Child Entity classes doesn't work if the form is sent with a missing variable even when I enable 'cascade_validation' => true.
This is too hard.
And to finish with this post, I want to know :
*The constraints that we define in the Entity classes aren't the ones that validates the form ? Because when I create the same constraints in validation.yml (using NotBlank with child_name and child_description) the validation works fine and fails if there is a missing variable/data.
Thank you even by answering me to one of these questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48143175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Link one model more than once I have a function where a user can request a project. The request has 2 fields for other employees to be added.
It's got a field for a person who is responsible for the project (person_responsible) and the employee who is supposed to attend the opening meeting (person_attending).
What I want to know is, since both these fields (person_responsible and person_attending) will be pulling it's data from hr_employees table, how would I set this up in my Project-Model.
At the moment I have the one field set up like this:
public $belongsTo = array(
'HrEmployee' => array(
'className' => 'HrEmployee',
'foreignKey' => 'responsible_person',
'fields' => 'HrEmployee.employeename',
)
);
How would I set up the other field?
A: What I do in this cases is to make two associations. Since cake allow to customize relations, you can have two relations to the same model with different names.
public $belongsTo = array(
'ResponsibleEmployee' => array(
'className' => 'HrEmployee',
'foreignKey' => 'responsible_person',
'fields' => 'HrEmployee.employeename',
),
'AttendingEmployee' => array(
'className' => 'HrEmployee',
'foreignKey' => 'person_attending',
'fields' => 'HrEmployee.employeename',
)
);
Change the names to adjust your needs. Now, if your model is set as containable and you retrieve the Project model with those models in it, you'll get something like
array('Project' => array(/*data project*/),
'ResponsibleEmployee' => array(/*name*/),
'AttendingEmployee' => array(/*name*/)
)
(or another variation of that array depending on how the query was made).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21875907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why xpath cannot get the target element? I am quite new in scraping with xpath. I am trying to scrape product information on Target. I use selenium and xpath successfully get the price and name. But xpath cannot return any value when scraping for product sizeproduct size and sales locationsales location.
For example, for this url"https://www.target.com/p/pataday-once-daily-relief-extra-strength-drops-0-085-fl-oz/-/A-83775159?preselect=81887758#lnk=sametab", xpath for size is:
//*[@id="pageBodyContainer"]/div[1]/div[2]/div[2]/div/div[3]/div/div[1]/text()
xpath for sales location is:
//*[@id="pageBodyContainer"]/div[1]/div[2]/div[2]/div/div[1]/div[2]/span
I also try to get these two elements by using requests but it also did not work. Do anyone know why it happened? Any help appreciated. Thanks.
Following is my code:
def job_function():
urlList = ['https://www.target.com/p/pataday-once-daily-relief-extra-strength-drops-0-085-fl-oz/-/A-83775159?preselect=81887758#lnk=sametab',
'https://www.target.com/p/kleenex-ultra-soft-facial-tissue/-/A-84780536?preselect=12964744#lnk=sametab',
'https://www.target.com/p/claritin-24-hour-non-drowsy-allergy-relief-tablets-loratadine/-/A-80354268?preselect=14351285#lnk=sametab',
'https://www.target.com/p/opti-free-pure-moist-rewetting-drops-0-4-fl-oz/-/A-14358641#lnk=sametab'
]
def ScrapingTarget(url):
AArray = []
wait_imp = 10
CO = webdriver.ChromeOptions()
CO.add_experimental_option('useAutomationExtension', False)
CO.add_argument('--ignore-certificate-errors')
CO.add_argument('--start-maximized')
wd = webdriver.Chrome(r'D:\chromedriver\chromedriver_win32new\chromedriver_win32 (2)\chromedriver.exe',
options=CO)
wd.get(url)
wd.implicitly_wait(wait_imp)
sleep(1)
#start scraping
name = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[1]/h1/span").text
sleep(0.5)
price = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[2]/div[2]/div/div[1]/div[1]/span").text
sleep(0.5)
try:
size = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[2]/div[2]/div/div[3]/div/div[1]/text()").text
except:
size = "none"
sleep(0.5)
try:
sales location = wd.find_element(by=By.XPATH, value="//*[@id='pageBodyContainer']/div[1]/div[2]/div[2]/div/div[1]/div[2]/span").text
except:
sales location = "none"
tz = pytz.timezone('Etc/GMT-0')
GMT = datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
AArray.append([name, price, size, sales location, GMT])
with open(
r'C:\Users\12987\PycharmProjects\python\Network\priceingAlgoriCoding\export_Target_dataframe.csv',
'a', newline="", encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(AArray)
with concurrent.futures.ThreadPoolExecutor(4) as executor:
executor.map(ScrapingTarget, urlList)
sched = BlockingScheduler()
sched.add_job(job_function,'interval',seconds=60)
sched.start()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72568845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IOS image sizes for buttons I've read the human interface guidelines provided by apple.
Navigation Bar and Toolbar Icon Size:
Target size :
72px × 72px (24pt × 24pt @3x)
48px × 48px (24pt × 24pt @2x)
Max size:
84px × 84px (28pt × 28pt @3x)
56px × 56px (28pt × 28pt @2x)
Does this apply to regular buttons as well?
I have a few regular buttons with images inside them that are set to Max size (above) but I find its still to small.
Can I change the size to anything I see fit?
A: No. You can choose whatever size you want, just make sure the button or other elements are within safeAreaLayoutGuide.
Besides, the guidelines are just Guidelines , they guide you as to what might look most appropriate as per apple, but these are not necessarily restrictions that must be enforced.
A: They are guidelines not rules, go crazy with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47973544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Which namespace (IBM.WMQ vs. IBM.WMQAX) should be used in the .NET library for IBM MQ WebSphere (amqmdnet.dll) I am writing an application that gets data from IBM WebSphere MQ. IBM supplies a DLL with classes to interact with MQ. However, there appear to be two main namespaces; IBM.WMQ and IBM.WMQAX. The latter seems to be a newer addition, but the former appears to be what vague answers on various web sites suggest using for .NET applications. I was hoping someone here might be able to enumerate the real differences and what advantages/disadvantages the classes in each namespace offer.
A: From this thread:
The IBM.WMQ is IBM's version of Neil Kolban's original work of
converting the Java classes for MQ to classes for the .NET framework.
The IBM.WMQAX is IBM's COM component for accessing MQ (ActiveX)
If you're coding in .NET, use IBM.WMQ since it's managed code. If
you're coding in VB6 or VC++ then use the ActiveX com component.
You could use the COM component from .NET using COM Interop, but that
really would only make sense, IF, the classes for .NET were NOT
available. Seeing that they are, use IBM.WMQ.
A: You need to use IBM.WMQ namespace for developing .NET applications to interact with IBM MQ Queue Manager. The other one, IBM.WMQAX namespace is for ActiveX applications.
A: This thread, linked in the answer by @stuartd contains some valuable information. While the part in his quote seems partially incorrect, additional comments in the thread do a better job clarifying. While I never used VB script or ActiveX, and thus don't quite follow the problem that the IBM.WMQAX namespace was looking to solve, I can ascertain from the discussion that the namespace should be avoided when writing a new .NET application from scratch.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27908311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get array element containing '/' in the string array I have a string array which I have split based on the white space. Now, as per my requirements, I have to get the array element which contains '/' in its contents, but I am not able to get it. I don't understand how to achieve it.
Here is the code that I have tried:
string[] arrdate = currentLine.Split(' ');
How do I get the array element consisting of a /?
A: Try this:
string[] arrdate = currentLine.Split(' ');
var dateItems = arrdate.Where(item => item.Contains("/")).ToArray()
A: foreach (string s in arrdate)
{
if (s.contains("/"))
{
//do something with s like add it to an array or if you only look for one string assign it and break out of the loop.
}
}
A: if you want to get only one item then try this
// split on the basis of white space
string[] arrdate = currentLine.Split(' ');
// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();
// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}
A: // split on the basis of white space
string[] arrdate = currentLine.Split(' ');
// now find out element with '/' using lambda
string item = arrdate.Where(item => item.Contains("/")).FirstOrDefault();
// if you don't want to use lambda then try for loop
string item;
for(int i = 0; i < arrdate.Length; i++)
{
if(arrdate[i].Contains("/"))
{
item = arrdate[i]
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25519739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how do i invoke 32 bit gdb installed on Centos 64 I have Centos7 and I see both 32 and 64 bit version of gdb are installed however /usr/bin/gdb is the 64bit version. How can I invoke 32bit gdb version since i need to debug application compiled with -m32 compiler option
A: The 64-bit GDB is perfectly capable of debugging both 64 and 32-bit programs. You don't need to invoke 32-bit GDB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44928596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Npm - fetch vs node-fetch? These package names are pretty confusing, they seem like they do the same thing yet 'fetch' looks to be abandoned yet not marked as deprecated (last commit 3 years ago). Judging from the download counts people are probably downloading 'fetch' when they should get the supported and maintained 'node-fetch' package.
If you're building a Reactjs app, is fetch already built in? If so, is it different than 'node-fetch'?
What is the suggested package npm users should use?
https://www.npmjs.com/package/fetch
https://www.npmjs.com/package/node-fetch
A: A bit of history
Fetch is a standard created in 2015 by the Web Hypertext Application Technology Working Group (WHATWG). It was meant to replace the old and cumbersome XMLHttpRequest as means for issuing web requests. As it was meant to replace XMLHttpRequest the standard was clearly targeted at browsers rather than Node runtime, however due to it's wide adoption and for cross compatibility reasons, it was decided that it should also be implemented in Node.
Nonetheless, it took Node team roughly 3 years to implement experimental fetch in Node v16. Although still experimental it is now enabled by default in Node v18.
Because it took Node dev team so long to implement the Fetch standard, the community took matter in their own hands and created the node-fetch package which implements the Fetch standard.
The fetch package that you have mentioned is just coincidentally named the same as the standard but it has nothing to do with it other than that they both aim to "fetch"/"request" resources from the web.
What should you use?
In the past browsers used XMLHttpRequest API and Node used its own http.request. We now have the opportunity to bring those two ecosystems closer still by having them both use the Fetch API. This increases code interoperability and even allows code sharing between the browser and Node in certain cases.
Now, there are other popular packages out there such as axios or requests that still don't use Fetch under the hood but rather continue using Node's http library. Not using Fetch reduces inter-compatibility and therefore I don't think you should keep using either of them unless they convert, which is unlikely in the near future.
Instead, you should consider using Node's native fetch or node-fetch package . Which one though? Well, my opinion is that the Node's fetch is still in early phases but given it has the support from the core Node team I would bet on that. I suppose node-fetch has a wider adoption of the Fetch standard but I think over time it will become redundant as the Node's native fetch becomes fully implemented.
A: Both does the same thing, only difference what i see is node-fetch is compatible API on Node.js runtime,
fetch is more specific to browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62135839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Javascript ternary operator -- what is the condition? I read a handful of SOF posts on ternary operators but I'm still confused with this example:
var str = "I want to count";
var counts = {};
var ch, index, len, count;
for (index = 0; index < str.length; ++index) {
ch = str.charAt(index);
count = counts[ch];
counts[ch] = count ? count + 1 : 1; // TERNARY
}
I know the syntax is
condition ? expression1 : expression2
But I am trying to practice and break up the ternary into an if-else.
I don't know what the condition is supposed to be
counts[ch] = count // this isn't a condition, it's assigning a value...
A: The ternary
counts[ch] = count ? count + 1 : 1;
The condition in this expression is not counts[ch] = count but just count and is equivalent to
if (count){
counts[ch] = count + 1;
}
else {
counts[ch] = 1;
}
The right hand side of an assignment expression is always evaluated first and the counts[ch] is assigned the result of count ? count + 1 ? 1.
A: You're conflating the ternary with the assignment expression.
The code
counts[ch] = count ? count + 1 : 1;
can also be written as
counts[ch] = (count ? count + 1 : 1);
// but not (counts[ch] = count) ? count + 1 : 1
// that does something entirely different
And then, writing the matching if/else becomes pretty clear
if (count) {
counts[ch] = count + 1;
} else {
counts[ch] = 1;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72608528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: My 3D racing game has some problems like wheels turning y axis and car not going anywhere My car's tires spin but the car doesn't move an inch and the wheels turn into y axis instead of left and right. Here is my code, i added rigidbody and boxcollider onto my car aswell maybe that's a problem causing the car not to move? (i made sure to put the collider above the wheels to make sure that they spin.)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CarController : MonoBehaviour
{
private float horizontalInput;
private float verticalInput;
private float steerAngle;
private bool isBreaking;
public WheelCollider FrontLeftCollider;
public WheelCollider FrontRightCollider;
public WheelCollider BackLeftCollider;
public WheelCollider BackRightCollider;
public Transform FrontLeftTransform;
public Transform FrontRightTransform;
public Transform BackLeftTransform;
public Transform BackRightTransform;
public float maxSteeringAngle = 30f;
public float motorForce = 50f;
public float brakeForce = 0f;
private void FixedUpdate()
{
GetInput();
HandleMotor();
HandleSteering();
UpdateWheels();
}
private void GetInput()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
isBreaking = Input.GetKey(KeyCode.Space);
}
private void HandleSteering()
{
steerAngle = maxSteeringAngle * horizontalInput;
FrontLeftCollider.steerAngle = steerAngle;
FrontRightCollider.steerAngle = steerAngle;
}
private void HandleMotor()
{
FrontLeftCollider.motorTorque = verticalInput * motorForce;
FrontRightCollider.motorTorque = verticalInput * motorForce;
brakeForce = isBreaking ? 3000f : 0f;
FrontLeftCollider.brakeTorque = brakeForce;
FrontRightCollider.brakeTorque = brakeForce;
BackLeftCollider.brakeTorque = brakeForce;
BackRightCollider.brakeTorque = brakeForce;
}
private void UpdateWheels()
{
UpdateWheelPos(FrontLeftCollider, FrontLeftTransform);
UpdateWheelPos(FrontRightCollider, FrontRightTransform);
UpdateWheelPos(BackLeftCollider, BackLeftTransform);
UpdateWheelPos(BackRightCollider, BackRightTransform);
}
private void UpdateWheelPos(WheelCollider wheelCollider, Transform trans)
{
Vector3 pos;
Quaternion rot;
wheelCollider.GetWorldPose(out pos, out rot);
trans.rotation = rot;
trans.position = pos;
}
}
If needed i can send screenshots of things please don't be shy to ask.
I haven't tried anything too afraid to make it worse
A: A rigidbody will not move until some kind of force is applied to it, or you use it's MovePosition method. Here is a link ... https://docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74970425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Embedded database in Java EE application Good day. I'm confused about storing the embedded database in a Java EE application. I've just resolved the problem with the .properties file which can be accessed via getResource method, but where should I put my database to support portability?
A: For portability, the appropriate way is to install the embedded database in the project directory & then specifying the relative path.
In general, you have to extract the content & specifying that path relative to the current directory as database url. Below are some examples.
*
*H2 Database - jdbc:h2:file:relative-database-path
*Apache Derby - By including required jars in classpath & configuring environment variable accordingly.
*HSQLDB - jdbc:hsqldb:file:relative-database-path
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10736528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Incorrect string value: '\xCC_a' for column when inserting I am attempting to run a sql query but get the following error:
Incorrect string value: '\xCC_a' for column
CSV File line that breaks mysql query:
Juan Gordon,GarcÃ_a,[email protected],,,,,,,,,,y,
SQL Error:
<p>Error Number: 1366</p><p>Incorrect string value: '\xCC_a' for column 'last_name' at row 1</p><p>INSERT INTO `phppos_people` (`first_name`, `last_name`, `email`, `phone_number`, `address_1`, `address_2`, `city`, `state`, `zip`, `country`, `comments`) VALUES ('Juan Gordon', 'Garc�_a', '[email protected]', '', '', '', '', '', '', '', '')</p><p>Filename: /Library/WebServer/Documents/phppos/PHP-Point-Of-Sale/models/person.php</p><p>Line Number: 75</p> </div>
last_name is varchar(255) utf8_unicode_ci
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_unicode_ci';
Example CSV code
?>
last_name = GarcÌ_a
UPDATE: I just learned that when saving the file as a .csv in excel the encoding is: Westren (Mac OS Roman) with CR as line breaks.
I think that file encoding might cause the problem. But I need to support it.
A: The only Excel that exports to Mac OS Roman apparently is MS Excel for OSX. Unfortunately I don't have this so I can't check how to export with the correct character set
You now have two choices
a) Convert the CSV to UTF-8 using iconv for example
iconv -f MACROMAN -t UTF8 < yourfile.csv > yourfile-utf8.csv
b) Set the connection charset to the character set of the file before you import
SET NAMES macroman;
In codeigniter this would look like this
$this->db->simple_query('SET NAMES \'macroman\'');
After your import is done, don't forget to set it back
$this->db->simple_query('SET NAMES \'utf8\'');
Explanation:
If your connection charset is UTF-8, your database excepts UTF-8 encoded data. If you set the connection charset to macroman and the columns you write to are UTF-8, MySQL will automatically convert this for you.
From http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html
SET NAMES 'charset_name' [COLLATE 'collation_name']
SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)
On my freeBSD machine, MySQL has the macroman character set compiled in, I suppose you'll also have this.
mysql> SELECT * FROM information_schema.COLLATIONS WHERE CHARACTER_SET_NAME = 'macroman';
+---------------------+--------------------+----+------------+-------------+---------+
| COLLATION_NAME | CHARACTER_SET_NAME | ID | IS_DEFAULT | IS_COMPILED | SORTLEN |
+---------------------+--------------------+----+------------+-------------+---------+
| macroman_general_ci | macroman | 39 | Yes | Yes | 1 |
| macroman_bin | macroman | 53 | | Yes | 1 |
+---------------------+--------------------+----+------------+-------------+---------+
Also see http://dev.mysql.com/doc/refman/5.5/en/charset-charsets.html
Hope this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14183314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: If WPF Richtextbox Highlight word contains hyphen,thin line shown in the word? I am working in WPF RichTextBox.I have highlighted each word,using the below code.its works fine.But the word contains hyphen means,the highlighted word has some thin lines between the hyphen.
string SelectHighlightWord(RichTextBox rtb, int offset, int length)
{
TextRange fullRange = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);
fullRange.ClearAllProperties();
TextPointer startSelect = fullRange.Start.GetPositionAtOffset(offset);
TextPointer endSelect = startSelect.GetPositionAtOffset(length);
TextRange textRange = rtb.Selection;
textRange.Select(startSelect, endSelect);
textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(m_backgroundColor));
textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(m_foregroundColor));
FrameworkContentElement fce = (startSelect.Parent as FrameworkContentElement);
if (fce != null)
{
fce.BringIntoView();
}
return rtb.Selection.Text;
}
Note : I have added images for better understanding.
A: Is your window setting TextOptions.TextFormattingMode on Ideal? If so, try setting Display.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34544153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CSS add seperator after
*-Tag I'm tring to edit the Wordpress homepage of my friend.
He uses a free Template and want to add an seperator "|" after each of his menu items.
I tried it with this one.
#menu-mainmenu li + li:before {
content: " | ";
padding: 0 15px;
}
Format looks like this
<ul id="menu-mainmenu">
<li>...</li>
<li>...</li>
<li>...</li>
<li>...</li>
</ul>
The Pipes appear over the
*-Tag.
This is what I want to do
A: I had to make a lot of guesses here because you didn't include much code or explanation for what you are trying to achieve but I think I have managed to create the overall appearance of what you want.
I have created two ways that this works, one which should work for anyone and another which will work for everyone but work specifically in your case
Number one:
#menu-mainmenu li {
position: relative;
display: inline-block;
float: left;
}
#menu-mainmenu li:not(:first-child):after {
content: " | ";
position: relative;
display: inline-block;
float: left;
margin: 0 15px;
}
<ul id="menu-mainmenu">
<li>HOME</li>
<li>ABOUT</li>
<li>...</li>
<li>...</li>
</ul>
Number two:
#menu-mainmenu li {
position: relative;
display: inline-block;
float: left;
}
#menu-mainmenu li.line {
margin: 0 15px;
}
<ul id="menu-mainmenu">
<li>HOME</li>
<li class="line">|</li>
<li>ABOUT</li>
<li class="line">|</li>
<li>...</li>
<li class="line">|</li>
<li>...</li>
</ul>
A: I would use :after instead of :before
#menu-mainmenu li {
display: inline-block;
}
#menu-mainmenu > li:after {
content: " | ";
padding: 0 15px;
}
#menu-mainmenu > li:last-child:after {
content: "";
}
<ul id="menu-mainmenu">
<li>Link 1</li>
<li>Link 2</li>
<li>Link 3</li>
<li>Link 4</li>
</ul>
A: Using your CSS example , you'll need the follow:
#menu-mainmenu li{
display:inline-block;
}
Run this snippet:
#menu-mainmenu li {
display: inline-block;
}
#menu-mainmenu li + li:before {
content: " | ";
padding: 0 15px;
}
<ul id="menu-mainmenu">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
https://jsfiddle.net/6936pon8/1/
A: So, since you were unable to share the code, I had to simulate the error, and my guess was that the <li> has a fixed width, so in the first example we have the possible error, please verify if that's your case. If it is, the second example will give you the asnwer.
Posible Error
#menu-mainmenu li {
display: inline-block;
width: 40px;
}
#menu-mainmenu li + li:before {
content: " | ";
padding: 0 15px;
}
<ul id="menu-mainmenu">
<li>hola</li>
<li>...</li>
<li>cómo</li>
<li>está</li>
</ul>
Fix
#menu-mainmenu li {
display: inline-block;
width: 50px;
position: relative;
}
#menu-mainmenu li + li:before {
content: " | ";
position: absolute;
left: -10px;
}
<ul id="menu-mainmenu">
<li>hola</li>
<li>.........</li>
<li>cómo</li>
<li>está</li>
</ul>
You can play around with absolute positioned elements as long as its parent is a relative element.
One more time, please submit as much code as you can so we can help you out, otherwise if nobody finds an answer it will be a waste of time.
A: #menu-mainmenu li:after {
content: " | ";
padding: 0 15px;
}
#menu-mainmenu li:last-child:after {
content:"";
}
A:
Hey! check this out :)
* {
margin: 0;
padding: 0;
box-sizing: border-box;
-webkit-box-sizing : border-box;
list-style-type : none;
}
#menu-mainmenu li {
display: inline-block;
padding: 5px 10px;
}
#menu-mainmenu li:after {
content : " | ";
display: inline-block;
width : 10px;
height : 30px;
padding-left : 5px;
margin-left : 10px;
background-color: yellow;
font-size : 25px;
}
<ul id="menu-mainmenu">
<li>first</li>
<li>second</li>
<li>third</li>
<li>forth</li>
</ul>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47206910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: importing converted data using pandas I have a csv file that looks like this:
patient_id age_in_years CENSUS_REGION URBAN_RURAL_STATUS YEAR MONTH DAY_NUMBER_IN_MONTH race
11511 7 Northeast Urban 2011 6 20 Other
9882613 73 South Urban 2011 7 25 Unknown
32190339 49 West Urban 2011 8 13 Caucasian
...
I have converted the categorical data in this file (e.g., race, census region, urban/rural status, etc.) into binary vector objects using the following method:
def URSTATUS_to_numeric(a):
if a == 'Urban':
return [1, 0, 0]
if a == 'Rural':
return [0, 1, 0]
if a == 'NULL':
return [0, 0, 1]
df['URSTATUS_num'] = df['URBAN_RURAL_STATUS'].apply(URSTATUS_to_numeric)
I want to use these vectors for linear regression analysis but I'm unable to call them using the following the code:
def import_data(file_name):
df = pd.read_csv(file_name).drop_duplicates()
X_parameter = []
#Y_parameter = []
for alpha in zip(df['age_in_years']):
X_parameter.append([float(alpha)])
#Y_parameter.append(float(beta))
return X_parameter#, Y_parameter
X = import_data(filename)
Y = df['URSTATUS_num']
The error that I'm getting is this:
TypeError: float() argument must be a string or a number
A: If you're just iterating over that series to build a list of floats, you could instead use astype(float).
It seems like you have some values in that column, though, that cannot be converted to float. For the sake of troubleshooting, maybe just try
for alpha in zip(df['age_in_years']):
try:
X_parameter.append([float(alpha)])
except:
print alpha
You should be able to replace that whole function using
X = pd.read_csv(file_name).drop_duplicates()['age_in_years'].astype(float)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31926454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Incorrect path to S3 flysystem adapter in Laravel 5 I'm having an issue with Laravel 5's filesystem when uploading files to an S3 bucket. The line that is running to the filesystem is:
Storage::disk('s3')->put($slug, $img);
It works as it should for:
Storage::disk('local')->put($slug, $img);
But when I change the disk to S3 it throws the following error:
Class 'League\Flysystem\AwsS3v3\AwsS3Adapter' not found
As per the L5 docs, I have the following requirement in my composer.json
"league/flysystem-aws-s3-v2": "~1.0"
which installed league's aws flysystem adapter under:
League\flysystem-aws-s3-v2\
I have tried updating the path in the fileSystemManager.php in the filesystem vendor folder to the aws flysystem installation path but it still doesn't work. I can't seem to find anyone else who has experienced this behaviour.
A fresh pair of eyes or a knowledgeable head who might know more about Laravel than I would be great. I really can't seem to the issue.
UPDATE
I did a fresh install of the aws flysystem and not I get the following:
ErrorException in Util.php line 250:
fstat() expects parameter 1 to be resource, object given
A: Ok so I fixed the initial issue by removing aws/aws-sdk-php : "^2.8.* that I had in my composer.json and ran a fresh 'composer require league/flysystem-aws-s3-v3 ~1.0'. This fixed the initial error in finding the S3 flysystem.
The second error fstat() expects parameter 1 to be resource, object given related to my attempt to pass an image object to the put method:
Storage::disk('s3')->put($slug, $img);
when it expects a string. This was fixed by stringifying the $img object
Storage::disk('s3')->put($slug, $img->__toString());
Hope this helps somebody else who might encounter this issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31167688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Excel CountIF on date AND time I see lots of examples of how to work with times OR dates, but not a lot seems to be done with date AND time values.
I have the following data:
And would like the sum of some weights between specific date and times (shift patterns):
So
*
*I need all the weights between "17/07/2014 06:00" and "17/07/2014 14:00"
*I need all the weights between "17/07/2014 14:00" and "17/07/2014 22:00"
*I need all the weights between "17/07/2014 22:00" and "18/07/2014 06:00"
Yes, I can split the dates and times and deal with them separately, but there must be an easier way (it gets rather convoluted in the 3rd scenario)
By the way, the date to compare against will be calculated using "=DATE(YEAR(NOW()),MONTH(NOW()),DAY(NOW())-1)" for yesterdays date (stored in F11)
I have an entire page of different variations of attempts at this, which I wont post all of, but mainly:
=SUMIFS(
Last36Hours!$K$2:$K$10000,
Last36Hours!$T$2:$T$10000,">=" &
DATE(YEAR(F11),MONTH(F11),DAY(F11)) &
TIME(6,0,0)
)
should give me everything after yesterday 6am, but i get absolutely squat.
A: Very Close. Excel stores dates and times as days and fractions of days since 1/1/1900 or 1/1/1904. You need to ADD the time to the date, not concatenate. And you can simplify getting the Date portion from F11. Try:
=SUMIFS(
Last36Hours!$K$2:$K$10000,
Last36Hours!$T$2:$T$10000,">=" &
INT(F11)+ TIME(6,0,0))
You could also hard code yesterday at 6AM by replacing
DATE(YEAR(F11),MONTH(F11),DAY(F11)) & TIME(6,0,0)
with
TODAY()-0.75
which is the same as:
TODAY() - 1 + TIME(6,0,0)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24825091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: List to varargs with pre-difined size or without size What is the better way to convert List to varargs to call below 'builder( String... s )' method.
builder( stringList.toArray( new String[stringList.size()] ) );//with pre-difined array size
or
builder( stringList.toArray( new String[0] ) );//without predifined size
for example
void test() {
List<String> stringList = new ArrayList<>();
builder( stringList.toArray( new String[stringList.size()] ) );//call builder method with pre-difining array size
builder( stringList.toArray( new String[0] ) );//call builder method with array size 0
}
void builder( String... s )
{
}
I faced this question in a review and I was suggested that builder( stringList.toArray( new String[0] ) ) is more efficient than
using builder( stringList.toArray( new String[stringList.size()] ) ).
Is there a significant difference between these two?
Thanks
A: To my understanding
stringList.toArray( new String[stringList.size()] ) )
is more efficient. The reason:
The argument is needed to have an actual type (String) for a generic List<String>, where the generic type parameter is erased at run-time.
The argument is used for the resulting array if its size matches the list size.
If the size is 0, the passed array is discarded.
So passing a correct array saves one object creation.
Of course list.size() is called extra. So it might be slower. I doubt it.
Correction
See Arrays of Wisdom of the Ancients.
A correct benchmark shows the inverse: new String[0] being faster.
I just overflew the very interesting analysis, and it seems:
*
*(an extra short lived new String[0] is irrelevant;)
*doing the array copying local in the toArray method allows a different, faster array copy;
*(and then there is the extra call to size.)
Mind, I did not sufficiently thorough read the article; it really is interesting.
Conclusion (counter-intuitively): new T[0] is faster.
Mind that:
*
*code checkers might still think differently and issue a warning;
*this is with warming up: till the hotspot JIT kicks in, it may be the other way around.
A: builder(stringList.toArray(new String[0])) is slightly less efficient since you create an empty array that will be discarded and never used after the method returns. toArray will have to create a new array in order to store the elements of the List.
On the other hand, builder(stringList.toArray(new String[stringList.size()])) passes an array of the required length to the toArray method, and therefore that method will use that array instead of creating a new array.
A: There is a difference and it's mainly outlined by the Alexey Shipilev. Long story short:
toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now
A: I thought that c.toArray(new String[c.size()])) is more efficient, because we define here an array with required size.
BUT!!
IntelliJ IDEA has Collection.toArray() inspection, which is on by default. This is description:
There are two styles to convert a collection to an array: either using
a pre-sized array (like c.toArray(new String[c.size()])) or using an
empty array (like c.toArray(new String[0]).
In older Java versions
using pre-sized array was recommended, as the reflection call which is
necessary to create an array of proper size was quite slow. However
since late updates of OpenJDK 6 this call was intrinsified, making the
performance of the empty array version the same and sometimes even
better, compared to the pre-sized version. Also passing pre-sized
array is dangerous for a concurrent or synchronized collection as a
data race is possible between the size and toArray call which may
result in extra nulls at the end of the array, if the collection was
concurrently shrunk during the operation.
This inspection allows to follow the uniform style: either using an
empty array (which is recommended in modern Java) or using a pre-sized
array (which might be faster in older Java versions or non-HotSpot
based JVMs).
So it seems, that after JDK6, we should use c.toArray(new String[0]). My personal opinion, is that it doesn't matter what aporoach to use this time. Only if profiler says that this is a bottle neck, then we should worry about it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51766615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Console Application - How to access the properties in JSON? I need to access the json properties so that I will be able to filter the result based on registers devices (either AEVL2020 or AEVL2021) but, I can't figure out how to access it. It seems like the RootObject can't access anything. I'm doing this for about 2 days now, so I need help.
Here is my json:
{
"registers":{
"AEVL2020":[
{
"user_id": "1",
"employee_id": "12",
"name": "Juan Dela Cruz",
"privilege": "0"
},
{
"user_id": "2",
"employee_id": "32",
"name": "Pedro Dela Cruz",
"privilege": "0"
}
],
"AEVL2021":[
{
"user_id": "1",
"employee_id": "29",
"name": "Maria Del Mundo",
"privilege": "0"
},
{
"user_id": "2",
"employee_id": "222",
"name": "Jay Del Mundo",
"privilege": "0"
}
]
}
}
my C#:
static void Main(string[] args)
{
using (StreamReader r = new StreamReader("C:\\Users\\Admin\\source\\repos\\Practice1\\Practice1\\company1.json"))
{
string json = r.ReadToEnd();
var root = JsonConvert.DeserializeObject<RootObject>(json);
// This is where the error, I can't access either AEVL2020 or AEVL2021
foreach (var p in root.AEVL2020 || root.AEVL2021)
{
Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);
}
}
}
public class AEVL2020
{
public string user_id { get; set; }
public string employee_id { get; set; }
public string name { get; set; }
public string privilege { get; set; }
}
public class AEVL2021
{
public string user_id { get; set; }
public string employee_id { get; set; }
public string name { get; set; }
public string privilege { get; set; }
}
public class Registers
{
public List<AEVL2020> AEVL2020 { get; set; }
public List<AEVL2021> AEVL2021 { get; set; }
}
public class RootObject
{
public Registers registers { get; set; }
}
A: You can define single AEVL class for both AEVL2020 and AEVL2020 as follow:
public class AEVL
{
public string user_id { get; set; }
public string employee_id { get; set; }
public string name { get; set; }
public string privilege { get; set; }
}
public class Registers
{
public List<AEVL> AEVL2020 { get; set; }
public List<AEVL> AEVL2021 { get; set; }
}
Then your code would be like this and you can get items based on given string:
var aevlProp = root.registers.GetType().GetProperty("AEVL2020");
var values = (aevlProp.GetValue(root.registers, null) as List<AEVL>);
foreach (var p in values)
{
Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);
}
Output for GetProperty("AEVL2020");
1Juan Dela Cruz120
2Pedro Dela Cruz320
Output for GetProperty("AEVL2021");
1Maria Del Mundo290
2Jay Del Mundo2220
A: Something like this i guess
Given
public class SomeObject
{
public string user_id { get; set; }
public string employee_id { get; set; }
public string name { get; set; }
public string privilege { get; set; }
}
public class RootObject
{
public Dictionary<string, List<SomeObject>> registers { get; set; }
}
Usage
var input = "{\r\n\"registers\":{\r\n \"AEVL2020\":[\r\n {\r\n \"user_id\": \"1\",\r\n \"employee_id\": \"12\",\r\n \"name\": \"Juan Dela Cruz\",\r\n \"privilege\": \"0\"\r\n },\r\n {\r\n \"user_id\": \"2\",\r\n \"employee_id\": \"32\",\r\n \"name\": \"Pedro Dela Cruz\",\r\n \"privilege\": \"0\"\r\n }\r\n ],\r\n \"AEVL2021\":[\r\n {\r\n \"user_id\": \"1\",\r\n \"employee_id\": \"29\",\r\n \"name\": \"Maria Del Mundo\",\r\n \"privilege\": \"0\"\r\n },\r\n {\r\n \"user_id\": \"2\",\r\n \"employee_id\": \"222\",\r\n \"name\": \"Jay Del Mundo\",\r\n \"privilege\": \"0\"\r\n }\r\n ]\r\n }\r\n}";
var r= JsonConvert.DeserializeObject<RootObject>(input);
// choose the name you want here
var values = r.registers["<Name>"];
foreach (var p in values )
Console.WriteLine(p.user_id + p.name + p.employee_id + p.privilege);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60648274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: BizTalk | Issue with Logical Existence functoid | source node doesn’t exist, still need output in the target I have a requirement to populate the output field in the destination schema though the source field does not exist in the input XML. If it does not exist, I have different logic to populate the target field. I tried using the 'Logical Existence' functoid but it is not giving me the desired output.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72878305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Interthread communication between producer and consumer threads? I am trying to learn inter thread communication where I am using BlockingQueue.
I have written a producer which generate TaskId and insert it into BlockingQueue.
Now I have 2 consumers threads (name "1" and "0"). If taskId is odd, it is consumed by Thread "1" else "2".
@Override
public void run() {
while (true) {
while (queue.peek() != null && !name.equals(String.valueOf(queue.peek().intValue() % 2 ))) {
try {
System.out.println(name + ",consumed," + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
How can i make that check also here?
A: One way I am thinking, there could be other better ways also:
@Override
public void run() {
String name = Thread.currentThread().getName();
while (true) {
while (queue.peek() == null) {
//some sleep time
}
synchronized (lock) {
while (queue.peek() != null && !name.equals(String.valueOf(queue.peek().intValue() % 2 ))) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(queue.peek() != null) {
try {
System.out.println(name + ",consumed," + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
Another Way: To have anotherLock that will be notified by producer thread whenever element is added to queue.
@Override
public void run() {
String name = Thread.currentThread().getName();
while (true) {
synchronized (anotherLock) {
while (queue.peek() == null) {
anotherLock.wait();
}
}
synchronized (lock) {
while (queue.peek() != null && !name.equals(String.valueOf(queue.peek().intValue() % 2 ))) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(queue.peek() != null) {
try {
System.out.println(name + ",consumed," + queue.take());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lock.notify();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58196336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Charm Down PicturesService not working I'm still having problems getting the Charm Down PicturesService to work.
(I already posted a question regarding the issue).
Now I created a very simple test application and updated the build.gradle file with the latest library versions.
However, the PicturesService is still working very unreliable. Selecting a picture sometimes works, sometimes it doesn't. Taking a picture seems to be working even more unreliable.
buildscript {
repositories {
jcenter()
}
dependencies { classpath 'org.javafxports:jfxmobile-plugin:1.3.5'}
}
apply plugin: 'org.javafxports.jfxmobile'
repositories {
jcenter()
maven {
url 'http://nexus.gluonhq.com/nexus/content/repositories/releases'
}
}
mainClassName = 'com.gluonapplication.GluonApplication'
dependencies {
compile 'com.gluonhq:charm:4.3.4'
compile 'org.javafxports:jfxdvk:8.60.9'
compileNoRetrolambda 'com.airhacks:afterburner.mfx:1.6.2'
}
jfxmobile {
downConfig {
version = '3.3.0'
plugins 'display', 'lifecycle', 'statusbar', 'storage', 'pictures'
}
android {
manifest = 'src/android/AndroidManifest.xml'
compileSdkVersion = '23'
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'license/LICENSE.txt'
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
}
}
}
The necessary permissions are added to the AndroidManifest:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
MobileApplication:
public class GluonApplication extends MobileApplication {
@Override
public void init() {
addViewFactory(HOME_VIEW, () ->
{
PicturesService pictureService = Services.get(PicturesService.class)
.orElseThrow(() -> new IllegalStateException("Failed to get PictureService"));
Button btnLoadImage = new Button("load image");
btnLoadImage.setOnAction(e -> pictureService.loadImageFromGallery().ifPresent(i -> imv.setImage(i)));
CheckBox chkSavePicture = new CheckBox("save picture");
Button btnTakePhoto = new Button("take photo");
btnTakePhoto.setOnAction(e -> pictureService.takePhoto(chkSavePicture.isSelected()).ifPresent(i -> imv.setImage(i)));
ImageView imv= new ImageView();
imv.setFitHeight(300);
imv.setFitWidth(300);
VBox content = new VBox(16, btnLoadImage, btnTakePhoto, chkSavePicture, imv);
content.setAlignment(Pos.CENTER);
return new View(content);
});
}
}
Tested on a Huawei P9 lite, Android 6.0
Logcat take photo succeeded:
05-13 16:08:49.200: V/FXActivity(18796): onActivityResult with requestCode 2 and resultCode = -1 and intent = null
05-13 16:08:50.180: V/FXActivity(18796): onRestart
05-13 16:08:50.187: V/FXActivity(18796): onStart
05-13 16:08:50.187: V/FXActivity(18796): onResume
05-13 16:08:50.196: V/FXEntity(18796): Surface created.
05-13 16:08:50.198: V/FXActivity native(18796): [JVDBG] SURFACE created native android window at 0xe7c9b208, surface = 0xffac4e60
05-13 16:08:50.202: D/mali_winsys(18796): new_window_surface returns 0x3000
05-13 16:08:50.202: I/GLASS(18796): Native code is notified that surface has changed (repaintall)!
05-13 16:08:50.203: V/FXEntity(18796): Called Surface changed [1080, 1740], format 4
05-13 16:08:50.203: V/FXActivity native(18796): [JVDBG] SURFACE created native android window at 0xe7c9b208, surface = 0xffac4e40
05-13 16:08:50.204: I/GLASS(18796): Native code is notified that surface has changed with size provided (repaintall)!
05-13 16:08:50.204: V/FXEntity(18796): Called Surface redraw needed
05-13 16:08:50.205: V/FXEntity(18796): Redraw...
05-13 16:08:50.205: I/GLASS(18796): Call surfaceRedrawNeeded
05-13 16:08:50.205: I/GLASS(18796): Native code is notified that surface needs to be redrawn (repaintall)!
05-13 16:08:50.205: V/FXEntity(18796): Wait a while before doing this again...
05-13 16:08:50.230: I/System.out(18796): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_20
05-13 16:08:50.310: I/System.out(18796): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_28
05-13 16:08:50.408: V/FXEntity(18796): Redraw again...
05-13 16:08:50.408: I/GLASS(18796): Call surfaceRedrawNeeded
05-13 16:08:50.408: I/GLASS(18796): Native code is notified that surface needs to be redrawn (repaintall)!
05-13 16:08:50.416: I/OpenGLRenderer(18796): Initialized EGL, version 1.4
05-13 16:08:50.419: D/mali_winsys(18796): new_window_surface returns 0x3000
Logcat take photo failed:
05-13 22:18:38.264: I/art(9381): Late-enabling -Xcheck:jni
05-13 22:18:38.299: D/ActivityThread(9381): ActivityThread,attachApplication
05-13 16:07:13.229: D/HwCust(18033): Create obj success use class android.content.res.HwCustHwResourcesImpl
05-13 16:07:13.393: I/MultiDex(18033): VM with version 2.1.0 has multidex support
05-13 16:07:13.393: I/MultiDex(18033): install
05-13 16:07:13.393: I/MultiDex(18033): VM has multidex support, MultiDex support library is disabled.
05-13 16:07:13.429: V/FXActivity(18033): Initializing JavaFX Platform, using 8.60.9-SNAPSHOT
05-13 16:07:13.438: V/FXActivity native(18033): Loading JavaFXDalvik library
05-13 16:07:13.452: V/HwPolicyFactory(18033): : success to get AllImpl object and return....
05-13 16:07:13.474: I/HwCust(18033): Constructor found for class android.app.HwCustHwWallpaperManagerImpl
05-13 16:07:13.474: D/HwCust(18033): Create obj success use class android.app.HwCustHwWallpaperManagerImpl
05-13 16:07:13.475: V/ActivityThread(18033): ActivityThread,callActivityOnCreate
05-13 16:07:13.482: I/System.out(18033): usetextureview = false, useswipekeyboard = false
05-13 16:07:13.484: I/HwSecImmHelper(18033): mSecurityInputMethodService is null
05-13 16:07:13.485: V/FXActivity(18033): onCreate called, using 8.60.9-SNAPSHOT
05-13 16:07:13.486: V/FXActivity native(18033): Notification queue instance created.
05-13 16:07:13.486: V/FXActivity native(18033): Notification queue started
05-13 16:07:13.498: V/HwWidgetFactory(18033): : successes to get AllImpl object and return....
05-13 16:07:13.542: V/FXActivity native(18033): appDataDir: /data/user/0/com.gluonapplication
05-13 16:07:13.543: V/FXActivity(18033): onStart
05-13 16:07:13.544: D/ActivityThread(18033): add activity client record, r= ActivityRecord{a0b6377 token=android.os.BinderProxy@a432176 {com.gluonapplication/javafxports.android.FXActivity}} token= android.os.BinderProxy@a432176
05-13 16:07:13.544: V/FXActivity(18033): onActivityResult with requestCode 2 and resultCode = -1 and intent = null
05-13 16:07:13.544: V/FXActivity(18033): onResume
05-13 16:07:13.566: D/OpenGLRenderer(18033): Use EGL_SWAP_BEHAVIOR_PRESERVED: false
05-13 16:07:13.638: I/OpenGLRenderer(18033): Initialized EGL, version 1.4
05-13 16:07:13.655: D/mali_winsys(18033): new_window_surface returns 0x3000
05-13 16:07:13.665: V/FXEntity(18033): Surface created.
05-13 16:07:13.666: V/FXActivity native(18033): [JVDBG] SURFACE created native android window at 0xe7c99d08, surface = 0xffac4f30
05-13 16:07:13.816: I/System.out(18033): user.locale=de-DE
05-13 16:07:13.816: I/System.out(18033): javax.xml.stream.XMLEventFactory=com.sun.xml.stream.events.ZephyrEvent...
05-13 16:07:13.816: I/System.out(18033): prism.text=native
05-13 16:07:13.816: I/System.out(18033): java.vendor.url=http://www.android.com/
05-13 16:07:13.816: I/System.out(18033): java.ext.dirs=
05-13 16:07:13.816: I/System.out(18033): line.separator=
05-13 16:07:13.816: I/System.out(18033): file.encoding=UTF-8
05-13 16:07:13.816: I/System.out(18033): java.runtime.version=0.9
05-13 16:07:13.816: I/System.out(18033): prism.dirtyopts=true
05-13 16:07:13.816: I/System.out(18033): user.name=root
05-13 16:07:13.816: I/System.out(18033): java.compiler=
05-13 16:07:13.816: I/System.out(18033): android.icu.unicode.version=7.0
05-13 16:07:13.816: I/System.out(18033): javax.xml.stream.XMLOutputFactory=com.sun.xml.stream.ZephyrWriterFactory
05-13 16:07:13.816: I/System.out(18033): prism.debugfonts=true
05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.gestures.rotate=true
05-13 16:07:13.816: I/System.out(18033): java.version=0
05-13 16:07:13.816: I/System.out(18033): android.icu.library.version=55.1
05-13 16:07:13.816: I/System.out(18033): use.egl=true
05-13 16:07:13.816: I/System.out(18033): embedded=monocle
05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.gestures.scroll=true
05-13 16:07:13.816: I/System.out(18033): prism.lcdtext=false
05-13 16:07:13.816: I/System.out(18033): os.arch=armv7l
05-13 16:07:13.816: I/System.out(18033): java.io.tmpdir=/data/user/0/com.gluonapplication/cache
05-13 16:07:13.816: I/System.out(18033): glass.platform=Monocle
05-13 16:07:13.816: I/System.out(18033): android.zlib.version=1.2.8
05-13 16:07:13.816: I/System.out(18033): user.language=de
05-13 16:07:13.816: I/System.out(18033): java.vm.version=2.1.0
05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.isEmbedded=true
05-13 16:07:13.816: I/System.out(18033): javax.xml.stream.XMLInputFactory=com.sun.xml.stream.ZephyrParserFactory
05-13 16:07:13.816: I/System.out(18033): prism.glDepthSize=16
05-13 16:07:13.816: I/System.out(18033): path.separator=:
05-13 16:07:13.816: I/System.out(18033): java.runtime.name=Android Runtime
05-13 16:07:13.816: I/System.out(18033): java.specification.version=0.9
05-13 16:07:13.816: I/System.out(18033): user.dir=/
05-13 16:07:13.816: I/System.out(18033): prism.maxTextureSize=2048
05-13 16:07:13.816: I/System.out(18033): java.vm.specification.vendor=The Android Project
05-13 16:07:13.816: I/System.out(18033): com.sun.javafx.gestures.zoom=true
05-13 16:07:13.816: I/System.out(18033): java.vm.name=Dalvik
05-13 16:07:13.816: I/System.out(18033): monocle.platform=Android
05-13 16:07:13.816: I/System.out(18033): log.lens=FINEST
05-13 16:07:13.816: I/System.out(18033): java.vm.specification.version=0.9
05-13 16:07:13.816: I/System.out(18033): user.home=
05-13 16:07:13.816: I/System.out(18033): java.specification.name=Dalvik Core Library
05-13 16:07:13.816: I/System.out(18033): file.separator=/
05-13 16:07:13.816: I/System.out(18033): java.library.path=/vendor/lib:/system/lib
05-13 16:07:13.816: I/System.out(18033): user.variant=
05-13 16:07:13.816: I/System.out(18033): os.version=3.10.90-g033208c
05-13 16:07:13.816: I/System.out(18033): java.boot.class.path=/system/framework/core-libart.jar:/sy...
05-13 16:07:13.816: I/System.out(18033): DALVIK.prism.verbose=true
05-13 16:07:13.816: I/System.out(18033): java.vm.specification.name=Dalvik Virtual Machine Specification
05-13 16:07:13.816: I/System.out(18033): javafx.platform=android
05-13 16:07:13.816: I/System.out(18033): glass.lens=eglfb
05-13 16:07:13.816: I/System.out(18033): os.name=Linux
05-13 16:07:13.816: I/System.out(18033): user.region=DE
05-13 16:07:13.816: I/System.out(18033): java.class.path=.
05-13 16:07:13.816: I/System.out(18033): android.icu.impl.ICUBinary.dataPath=/data/misc/zoneinfo/current/icu:/syst...
05-13 16:07:13.816: I/System.out(18033): prism.verbose=true
05-13 16:07:13.816: I/System.out(18033): prism.vsync=false
05-13 16:07:13.816: I/System.out(18033): java.specification.vendor=The Android Project
05-13 16:07:13.816: I/System.out(18033): java.vm.vendor=The Android Project
05-13 16:07:13.816: I/System.out(18033): prism.allowhidpi=true
05-13 16:07:13.816: I/System.out(18033): java.vendor=The Android Project
05-13 16:07:13.816: I/System.out(18033): http.agent=Dalvik/2.1.0 (Linux; U; Android 6.0; ...
05-13 16:07:13.816: I/System.out(18033): android.icu.cldr.version=27.0.1
05-13 16:07:13.816: I/System.out(18033): android.openssl.version=BoringSSL
05-13 16:07:13.817: I/System.out(18033): java.home=/system
05-13 16:07:13.817: I/System.out(18033): java.vm.vendor.url=http://www.android.com/
05-13 16:07:13.817: I/System.out(18033): java.class.version=50.0
05-13 16:07:13.817: V/DalvikLauncher(18033): Launch JavaFX application on DALVIK vm.
05-13 16:07:13.848: V/DalvikLauncher(18033): We have JavaFX on our current (base) classpath, registered exit listener
05-13 16:07:13.854: V/DalvikLauncher(18033): application class: [class com.gluonapplication.GluonApplication]
05-13 16:07:13.854: V/DalvikLauncher(18033): preloader class: [null]
05-13 16:07:13.854: V/DalvikLauncher(18033): javafx application class: [class javafx.application.Application]
05-13 16:07:13.854: V/DalvikLauncher(18033): javafx launcher class: [class com.sun.javafx.application.LauncherImpl]
05-13 16:07:13.854: V/DalvikLauncher(18033): launch application method: [public static void com.sun.javafx.application.LauncherImpl.launchApplication(java.lang.Class,java.lang.Class,java.lang.String[])]
05-13 16:07:13.871: V/FXEntity(18033): Called Surface changed [1080, 1740], format 4
05-13 16:07:13.871: V/FXActivity native(18033): [JVDBG] SURFACE created native android window at 0xe7c99d08, surface = 0xffac4f10
05-13 16:07:13.871: V/FXEntity(18033): Called Surface redraw needed
05-13 16:07:13.878: V/FXEntity(18033): Called Surface redraw needed
05-13 16:07:13.993: I/System.out(18033): Prism pipeline init order: es2
05-13 16:07:13.993: I/System.out(18033): Using native-based Pisces rasterizer
05-13 16:07:13.993: I/System.out(18033): Using dirty region optimizations
05-13 16:07:13.993: I/System.out(18033): Using system sized mask for primitives
05-13 16:07:13.993: I/System.out(18033): Not forcing power of 2 sizes for textures
05-13 16:07:13.993: I/System.out(18033): Using hardware CLAMP_TO_ZERO mode
05-13 16:07:13.993: I/System.out(18033): Opting in for HiDPI pixel scaling
05-13 16:07:14.000: I/System.out(18033): Prism pipeline name = com.sun.prism.es2.ES2Pipeline
05-13 16:07:14.010: I/System.out(18033): Loading ES2 native library ... prism_es2_monocle
05-13 16:07:14.023: I/System.out(18033): succeeded.
05-13 16:07:14.023: I/System.out(18033): GLFactory using com.sun.prism.es2.MonocleGLFactory
05-13 16:07:14.054: I/GLASS(18033): I have to Call dlopen libGLESv2.so
05-13 16:07:14.055: I/GLASS(18033): handle = 0xf76fcd04
05-13 16:07:14.055: I/GLASS(18033): I have to Call dlopen libEGL.so
05-13 16:07:14.056: I/GLASS(18033): handle = 0xf76fc9c4
05-13 16:07:14.057: I/GLASS(18033): Binding to libactivity.so
05-13 16:07:14.058: I/GLASS(18033): GetNativeWindow = 0xf3762da1, getDensitiy = 0xf3762dad
05-13 16:07:14.058: V/FXEntity(18033): notify_glassHasStarted called in FXActivity. register device now.
05-13 16:07:14.079: D/mali_winsys(18033): new_window_surface returns 0x3000
05-13 16:07:14.089: I/System.out(18033): (X) Got class = class com.sun.prism.es2.ES2Pipeline
05-13 16:07:14.104: I/System.out(18033): Initialized prism pipeline: com.sun.prism.es2.ES2Pipeline
05-13 16:07:14.127: I/DENSITY(18033): GETDENSITY, answer = 3.000000
05-13 16:07:14.185: I/System.out(18033): Maximum supported texture size: 8192
05-13 16:07:14.186: I/System.out(18033): Maximum texture size clamped to 2048
05-13 16:07:14.186: I/System.out(18033): Non power of two texture support = true
05-13 16:07:14.186: I/System.out(18033): Maximum number of vertex attributes = 16
05-13 16:07:14.186: I/System.out(18033): Maximum number of uniform vertex components = 4096
05-13 16:07:14.186: I/System.out(18033): Maximum number of uniform fragment components = 4096
05-13 16:07:14.186: I/System.out(18033): Maximum number of varying components = 60
05-13 16:07:14.186: I/System.out(18033): Maximum number of texture units usable in a vertex shader = 16
05-13 16:07:14.186: I/System.out(18033): Maximum number of texture units usable in a fragment shader = 16
05-13 16:07:14.190: I/System.out(18033): Graphics Vendor: ARM
05-13 16:07:14.191: I/System.out(18033): Renderer: Mali-T830
05-13 16:07:14.192: I/System.out(18033): Version: OpenGL ES 3.1 v1.r8p0-01dev0.bbfc5a14ef62ccdf784a9fff6af72acd
05-13 16:07:14.216: I/System.out(18033): register device done
05-13 16:07:14.227: W/System.err(18033): vsync: false vpipe: true
05-13 16:07:14.227: I/System.out(18033): [MON] Create device
05-13 16:07:14.230: I/System.out(18033): [MON] Create device done, add done
05-13 16:07:14.414: W/System.err(18033): Loading FontFactory com.sun.javafx.font.freetype.FTFactory
05-13 16:07:14.414: W/System.err(18033): Subpixel: enabled
05-13 16:07:14.434: W/System.err(18033): Freetype2 Loaded (version 2.5.0)
05-13 16:07:14.434: W/System.err(18033): LCD support Enabled
05-13 16:07:14.444: W/art(18033): Before Android 4.1, method void com.sun.javafx.scene.transform.TransformUtils$ImmutableTransform.ensureCanTransform2DPoint() would have incorrectly overridden the package-private method in javafx.scene.transform.Transform
05-13 16:07:14.630: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF415078203.tmp
05-13 16:07:14.643: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF1552782793.tmp
05-13 16:07:14.650: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF-728135178.tmp
05-13 16:07:14.657: W/System.err(18033): Temp file created: /data/user/0/com.gluonapplication/cache/+JXF-646868817.tmp
05-13 16:07:14.828: W/art(18033): Before Android 4.1, method double javafx.scene.text.TextFlow.computeChildPrefAreaHeight(javafx.scene.Node, javafx.geometry.Insets) would have incorrectly overridden the package-private method in javafx.scene.layout.Region
05-13 16:07:14.828: W/art(18033): Before Android 4.1, method double javafx.scene.text.TextFlow.computeChildPrefAreaWidth(javafx.scene.Node, javafx.geometry.Insets) would have incorrectly overridden the package-private method in javafx.scene.layout.Region
05-13 16:07:15.067: I/System.out(18033): max rectangle texture cell size = 62
05-13 16:07:15.084: I/System.out(18033): wrap rectangle texture = 2 x 2
05-13 16:07:15.087: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: AlphaTexture_Color.frag
05-13 16:07:15.106: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: Texture_Color.frag
05-13 16:07:15.122: I/System.out(18033): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_20
05-13 16:07:15.133: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: Solid_TextureRGB.frag
05-13 16:07:15.150: I/System.out(18033): ES2ResourceFactory: Prism - createStockShader: FillRoundRect_Color.frag
05-13 16:07:15.154: I/System.out(18033): Loading Prism common native library ...
05-13 16:07:15.163: I/System.out(18033): succeeded.
05-13 16:07:15.177: I/System.out(18033): PPSRenderer: scenario.effect - createShader: LinearConvolveShadow_28
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43954431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "Error calling Driver#connect" using Hibernate This is my cfg.xml file:
<!-- Database connection settings -->
<property name="connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=hiber;</property>
<property name="connection.username">Costi-PC\Costi</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="model.User" />
User class and Main class:
@Entity
public class User {
@Id
private int userId;
private String userName;
public int getUserId() {..}
public void setUserId(int userId) {..}
public String getUserName() {..}
public void setUserName(String userName) {..}
}
public class Main {
public static void main(String[] args) {
User user = new User();
user.setUserId(1);
user.setUserName("Costi");
AnnotationConfiguration configuration = new AnnotationConfiguration();
configuration.configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
When I run the program i get this error:
Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:132)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:118)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at main.Main.main(Main.java:23)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused: connect. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:190)
at com.microsoft.sqlserver.jdbc.SQLServerException.ConvertConnectExceptionToSQLServerException(SQLServerException.java:241)
at com.microsoft.sqlserver.jdbc.SocketFinder.findSocket(IOBuffer.java:2243)
at com.microsoft.sqlserver.jdbc.TDSChannel.open(IOBuffer.java:491)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(SQLServerConnection.java:1309)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.login(SQLServerConnection.java:991)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(SQLServerConnection.java:827)
at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(SQLServerDriver.java:1012)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 14 more
I'm using sql server 2008.
I tried different types of cfg configuration but none seems to work.
I believe the problem is from connection.url. I tried to change the port (1433) but nothing.
Can anyone tell what's the problem ?
A: I have Faced Same issue just i have changed the Version on mysql server connector than works fine
<!-- commented as it was not make to connect
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
-->
added latest version of mysql connector
<!-- added latest version of mysql connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.18</version>
</dependency>
A: I know this post is almost 2 years old, but for me the questions gave me, for me, the right answer. And because people with the same question are getting this post from Google. I thought, lets add my story.
Same thing, same problem. And for me the answer was that SQL Server didn't accept connections from the outside. The tcp/ip network client configuration is standard disabled.
So it was for me a hint in the right direction.
A: I changed the version of MySql like,
From 5.1.8
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.8</version>
</dependency>
To 8.0.19
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
It works for me.
Thank you.
A: Use This with all Permission of DB
<property name="hibernate.connection.url">jdbc:mysql://ip:3306/dbname</property><property name="hibernate.connection.username">*******</property>
<property name="hibernate.connection.password">*******</property>
A: Try going to the command line and see if sqlserver is indeed listening to that port. On windows this would be the command:
netstat -nao | findstr 1433
Then see if the PID is Sql Server as expected in the windows (Ctr+Alt+Delete) process list.
If the server is running, try to connect to it using a SQL client GUI, see here for examples. When you can connect to the database from an external client successfully, try again from the Java program.
Try to see also if your local firewall settings to see if the firewall is the cause for the error, although by default firewalls do not block localhost - have a look at this answer.
A: Check you Sid in
hibernate.cfg.xml file
For Oracle Express Edition:
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
For Oracle Enterprise Edition:
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
A: the error is due to AnnotationConfiguration and making session by it.
you can try this solution:
@Autowired
SessionFactory sessionFactory;
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(ce);
A: I also face same problem due to some dependency issue. i solve my problem to change sql depenedency which is compatible to my current version of sql server in pom.xml file.
A: I had a same error when migrating from jTDS1.2.8 to mssql-jdbc and for me it helped removing the port number and specifying the named instance in the connection URL within hibernate.cfg.xml
From:
<property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME:1433;databaseName=mydbname;instanceName=MYINSTANCENAME;</property>
To:
<property name="hibernate.connection.url">jdbc:sqlserver://MYHOSTNAME;instanceName=MYINSTANCENAME;databaseName=mydbname;</property>
Reference: https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-2017
When using Named and Multiple SQL Server Instances, to use a JDBC URL property, do the following:
jdbc:sqlserver://localhost;instanceName=instance1;integratedSecurity=true;<more properties as required>;
A: if you are using a virtual server or server that is not updated the time zone should update it.
SQL CONSOLE:
SET GLOBAL time_zone = '+3:00';
A: Wrong username or a password in a config hibernate file "hibernate.cfg.xml"
A: Please make sure that the database with which you are trying to connect has already been created in the database with the same name.
A: If you're using Hibernate 4, try switching to Hibernate 5.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
This helped me resolve the error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22441076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Preloading entities with EF4 I have a bunch of classificators which will be used quite often. I wan't to preload those entities when my program starts so that I wouldn't have to do it later when any object references them.
How can this be done in EF4?
A: There's a long-ish walkthrough here:
How to Cache Entity Framework Reference Data
But profile first. Writing good projections may be faster than materializing entire entities with cached references. Even loading single referenced objects is quite fast. Don't "optimize" stuff which isn't slow.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3610427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Redirecting requests over 8443 to 443 One of our applications was previously configured to serve SSL from tomcat over port 8443. We're migrating this application to a new environment and switching to using nginx to handle SSL termination rather than tomcat (which will operate over 8080). I would like the ability for folks to be able to connect to the new environment over 8443 but get redirected to 443 (to support anyone's old bookmarks or links).
Currently have rulesets to redirect 80 to 443, and a full ssl_certificate set defined for listening on 443, but no luck trying a variety of methods to listen on 8443 and redirect to itself over 443.
Any suggestions?
A: Just define a separate server for port 8443, and do a redirect from there. You'd obviously still have to have a proper certificate for your 8443 server, too.
server {
listen 8443 ssl;
server_name example.com;
ssl_...;
return 301 https://example.com$request_uri;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20989018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python hashlib: TypeError: object supporting the buffer API required I am writing a client/server program for class which allows the client to send messages to the server using a variety of different encryption techniques. Right now, I'm in the middle of implementing symmetric encryption, and the server is throwing me an error when I attempt to hash the public key that it receives from the client during the initial key distribution. I am not very familiar with these libraries so I'm not quite sure what the cause of this error is.
My server code:
from Crypto.Random import *
from Crypto.PublicKey import RSA
import hashlib
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))
c = None
addr = None
s.listen(5)
while True:
c, addr = s.accept()
print ('Got connection from', addr)
break
c.send('You have connected to the server.\nPlease select one of the following communication options by entering the corresponding number.\n1. Public Key Encryption\n2. Symmetric Key Encryption\n3. Digital Signature\n4. Hash'.encode('ascii'))
#receive user option, this will get used in code I add in later
option = c.recv(1024).decode()
#receive and process the public key
pKey = RSA.importKey(c.recv(2048).decode())
#receive the original digest
digest = c.recv(2048).decode()
#hash the received key
hash_object = hashlib.sha1(pKey)
newDigest = hash_object.hexdigest()
if newDigest == digest:
print("Success")
else:
print("Failure")
My client code:
from Crypto import Random
from Crypto.PublicKey import RSA
import hashlib
import socket
s = socket.socket()
host = socket.gethostname()
port = 12345
inLoop = True
s.connect((host, port))
print(s.recv(1024).decode())
while(True):
option = input("Select an option: ")
print(option)
s.send(option.encode())
if (option == '1'):
#Begin handshake
random = Random.new().read
key = RSA.generate(1024,random)
pKey = key.publickey().exportKey()
hash_object = hashlib.sha1(pKey)
hex_digest = hash_object.hexdigest()
#send public key
s.send(pKey)
#send digest
s.send(hex_digest.encode())
elif(option == 2):
while(inLoop == True):
""
elif(option == 3):
while(inLoop == True):
""
elif(option == 4):
while(inLoop == True):
""
else:
print("Please enter a valid option.")
s.close()
Right now a great deal of this is unfinished, but the specific problem I am having is that the client creates a public RSA key, and hashes it, and sends the public key and the hex_digest to the server. The server receives the public key and decodes it into a string, and then turns it into an RSA key, but hashlib gives me an error once I attempt to hash the key. When the server reaches the line hash_object = hashlib.sha1(pKey), I receive an error: TypeError: object supporting the buffer API required
I am not sure what this means; I've done a lot of research. I do not know how to fix this, but for some reason the server will not hash the key.
A: I'm an idiot. I was doing hash_object = hashlib.sha1(pKey), but pKey is an RSA key, not a string, so I needed to do hash_object = hashlib.sha1(pKey.exportKey()) instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66177717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Asp.Net Core Web APi and Azure AD auth I have to create a web app with these kinds of requirements:
*
*SPA (Angular 9)
*SPA call to Web API (Asp.net core 3.1)
*I have to use the Azure AD for
the authentication (I created the tenant)
*I have to use Microsoft Graph API
I read different guides and studied the examples at the link
azure ad auth samples
but they do not cover my requirements.
I read this guide a web api that calls a web api that use a desktop application but after changing the code i receive the 401 unouthorized error.
Can anyone help me?
P.S. : Due unsuitable examples, i currently no have exutable code
Thanks a lot
A: You can check the MSAL For Angular document for how to authenticate user and acquire access token . And this code sample is for Angular 9 .
If you want to directly call Microsfot Graph in Angular application , you can directly acquire Microsoft Graph's scopes as the document show , MSAL will help acquiring access token for Microsoft Graph . If you want to call Microsoft Graph from web api application , propagate the delegated user identity and permissions , you can use OAuth 2.0 On-Behalf-Of flow and follow the code sample as your shown , and use fiddler or developer tools to trace the requests and troubleshoot the 401 problem .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61212676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: When to use lib.es2015.d.ts vs @types/core-js? It seems lib.es2015.d.ts that ships with the Typescript compiler conflicts with the @types/core-js package if they are both being referenced.
This post indicates that the solution is either:
*
*Change es6 to es5 in compilerOptions's lib property. This way TypeScript won’t include ES6 type definitions.
*Remove core-js from node_modules. This way TypeScript will use only its internal ES6 type definitions.
What I don't understand is why does @types/core-js then even exist, and when is it useful, since the compiler already ships with these definitions?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40965590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do EDMFunction work? We had a developer who attempted to filter on a numeric ID property using a string:
var student = (from s in dbStudents
where s.StudentId.ToString() == "2"
select s).FirstOrDefault();
This won't work, as ToString() cannot be translated into SQL by the EF Provider.
One solution was provided works, but I honestly am unclear about why it works:
[EdmFunction("SqlServer", "STR")]
public static string ConvertToString(double? number)
{
return number.HasValue ? number.ToString() : null;
}
And the query now looks like:
var student = (from s in Students
where ConvertToString((double) s.LanguageId).Trim() == "2"
select s).FirstOrDefault();
My understanding is this query should be building up an expression tree, but it appears that we have a CLR method being executed in the middle? I had thought that we could only use methods where the provider understood how it could be translated into SQL.
The SQL looks right, can anyone tell me how we got from:
return number.HasValue ? number.ToString() : null;
to
SELECT TOP (1)
[Extent1].[StudentId] AS [StudentId],
[Extent1].[Name] AS [Name]
FROM [dbo].[Student] AS [Extent1]
WHERE N'2' = (LTRIM(RTRIM(STR( CAST( [Extent1].[StudentId] AS float)))))
A: The Entity Framework uses only the information in the attribute to convert the method call to SQL. The implementation is not used in this case.
A: The EdmFunction attribute calls the specified method in SQL. The implementation you have in C# will be ignored. So in your case STR method is called at SQL end.
You can have your method as:
[EdmFunction("SqlServer", "STR")]
public static string ConvertToString(double? number)
{
throw new NotSupportedException("Direct calls not supported");
}
and still it would work.
See: EDM and Store functions exposed in LINQ
How it works
When a method with the EdmFunction attribute is detected within a LINQ
query expression, its treatment is identical to that of a function
within an Entity-SQL query. Overload resolution is performed with
respect to the EDM types (not CLR types) of the function arguments.
Ambiguous overloads, missing functions or lack of overloads result in
an exception. In addition, the return type of the method must be
validated. If the CLR return type does not have an implicit cast to
the appropriate EDM type, the translation will fail.
As a side note, you can also use SqlFunctions.StringConvert like:
var student = (from s in Students
where SqlFunctions.StringConvert((double) s.LanguageId)).Trim() == "2"
select s).FirstOrDefault();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28864569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: unable to itherate through the array perl I have this perl script:
my %perMpPerMercHash;
foreach my $sheet () { #proper ranges specified
foreach my $row ( ) { #proper ranges specified
#required variables declared.
push(@{$perMpPerMercHash{join("-", $mercId, $mpId)}}, $mSku);
}
}
#Finally 'perMpPerMercHash' will be a hash of array`
foreach my $perMpPerMerc ( keys %perMpPerMercHash ) {
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
}
sub genFile {
my ( $outFileName, @skuArr ) = @_;
my $output = new IO::File(">$outFileName");
my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
#mpId is generated.
&prepareMessage($writer, $mpId, @skuArr);
}
sub prepareMessage {
my ( $writer, $mpId, @skuArr ) = @_;
my $count = 1;
print Dumper \@skuArr; #Printing correctly, 8-10 values.
foreach my $sku ( @skuArr ) { #not iterating.
print "loop run" , $sku, "\n"; #printed only once.
}
}
Can somebody please help why this is happening. I am new to perl and could not understand this anomaly.
EDIT:
output of Dumper:
$VAR1 = [
'A',
'B',
'C',
];
A: When you do
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
You're passing a reference to an array.
So in
sub genFile {
my ( $outFileName, @skuArr ) = @_;
You have to do :
sub genFile {
my ( $outFileName, $skuArr ) = @_;
and then use @$skuArr.
Have a look at references
The modified genFile sub will be:
sub genFile {
my ( $outFileName, $skuArr ) = @_;
my $output = new IO::File(">$outFileName");
my $writer = new XML::Writer( OUTPUT => $output, DATA_MODE => 1, DATA_INDENT => 2);
#mpId is generated.
&prepareMessage($writer, $mpId, @$skuArr);
}
And the other sub don't need to be modified.
Or you can pass always skuArr by reference:
&genFile($perMpPerMerc, $perMpPerMercHash{$perMpPerMerc});
...
sub genFile {
my ( $outFileName, $skuArr ) = @_;
...
&prepareMessage($writer, $mpId, $skuArr);
}
sub prepareMessage {
my ( $writer, $mpId, $skuArr ) = @_;
my $count = 1;
print Dumper $skuArr;
foreach my $sku ( @$skuArr ) {
print "loop run" , $sku, "\n";
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19682906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mootools accordion styling problem I just built my first mootools accordion, but it is adding a lot of inline styles which is just ruining my UI. I can set up a inline style with !important keyword but it will just make my css maintenance a nightmare. any ideas how to get rid of the inline styles
It is just this
<script language="javascript">
window.addEvent('domready', function() {
//create our Accordion instance
var myAccordion = new Accordion($('accordion'), 'div.subTreeHeader', 'div.accordionElement', {
opacity: false, fixedHeight:400
});
});
</script>
A: Well this is quite old question, I answer it because I run to it when looking for the same problem.
Actually Mootools Acordion adds this much inline CSS:
padding-top: 0px; border-top-style:
none; padding-bottom: 0px; border-bottom-style: none;
overflow: hidden; opacity: 1;
The solutions I found for this are fixes that have to be applied after calling the new Fx.Accordion. I also agree that feels wrong to fix with !important CSS fixing. So I also looked for other options.
Option 1, set back the css as you want:
$$('.acordion3_content').setStyles({
border: '3px solid #0F0',
'overflow-y': 'auto',
});
Option 2, create one more div inside or outside it. I did this option to get a scroll div I could have events connected to. Like this I could have a scroll inside the accordion's content without it being affected of Fx.Acordion's CSS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2477819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Updating the Jpanel of a class After some advice on using jpanel - I'm new to java and playing around with the GUI elements.
Bascially what I'm curious about is if I can set up a Jpanel in one class, then somehow add labels etc to the that container, but from another class.
Is this possible ? or do i have to set the entire GUI up in one class, but then I guess I would have the same issue, if I wanted to update those fields I had set up in the main class from another class?
Apologies I don't really have any code that's usefull to demostrate here - I'm just trying to get the idea going, working out if its possible before I go ahead. And I'm not even sure if this is possible. Any advice would be greatly appreciated.
Thanks
A: As long as you have a reference to the JPanel, you can add whatever GUI-element you want, by calling add(JComponent comp) on the JPanel.
So, you can do something like this:
class Panel extends JPanel{
...
}
class Main{
public Main(JPanel thePanel){
thePanel.add(new JButton("Hello"));
}
}
Was this what you were looking for?
You can also update the fields added to the panel from another class, if you have a public accessor-method set up, in the class. So in your panel class, you have a method:
public JButton getButton(){
return button;
}
Then you can access the button from whatever class with a reference to your panel class, like this:
panel.getButton().setText("Some text");
Note that the button could just as well be public, then you could simply call the method directly: panel.button.setText("Some text"); but this is not considered good code, as it violates some general good OOP practices, not relevant to mention here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2541574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: F# Split list into sublists based on comparison of adjacent elements I've found this question on hubFS, but that handles a splitting criteria based on individual elements. I'd like to split based on a comparison of adjacent elements, so the type would look like this:
val split = ('T -> 'T -> bool) -> 'T list -> 'T list list
Currently, I am trying to start from Don's imperative solution, but I can't work out how to initialize and use a 'prev' value for comparison. Is fold a better way to go?
//Don's solution for single criteria, copied from hubFS
let SequencesStartingWith n (s:seq<_>) =
seq { use ie = s.GetEnumerator()
let acc = new ResizeArray<_>()
while ie.MoveNext() do
let x = ie.Current
if x = n && acc.Count > 0 then
yield ResizeArray.to_list acc
acc.Clear()
acc.Add x
if acc.Count > 0 then
yield ResizeArray.to_list acc }
A: This is an interesting problem! I needed to implement exactly this in C# just recently for my article about grouping (because the type signature of the function is pretty similar to groupBy, so it can be used in LINQ query as the group by clause). The C# implementation was quite ugly though.
Anyway, there must be a way to express this function using some simple primitives. It just seems that the F# library doesn't provide any functions that fit for this purpose. I was able to come up with two functions that seem to be generally useful and can be combined together to solve this problem, so here they are:
// Splits a list into two lists using the specified function
// The list is split between two elements for which 'f' returns 'true'
let splitAt f list =
let rec splitAtAux acc list =
match list with
| x::y::ys when f x y -> List.rev (x::acc), y::ys
| x::xs -> splitAtAux (x::acc) xs
| [] -> (List.rev acc), []
splitAtAux [] list
val splitAt : ('a -> 'a -> bool) -> 'a list -> 'a list * 'a list
This is similar to what we want to achieve, but it splits the list only in two pieces (which is a simpler case than splitting the list multiple times). Then we'll need to repeat this operation, which can be done using this function:
// Repeatedly uses 'f' to take several elements of the input list and
// aggregate them into value of type 'b until the remaining list
// (second value returned by 'f') is empty
let foldUntilEmpty f list =
let rec foldUntilEmptyAux acc list =
match f list with
| l, [] -> l::acc |> List.rev
| l, rest -> foldUntilEmptyAux (l::acc) rest
foldUntilEmptyAux [] list
val foldUntilEmpty : ('a list -> 'b * 'a list) -> 'a list -> 'b list
Now we can repeatedly apply splitAt (with some predicate specified as the first argument) on the input list using foldUntilEmpty, which gives us the function we wanted:
let splitAtEvery f list = foldUntilEmpty (splitAt f) list
splitAtEvery (<>) [ 1; 1; 1; 2; 2; 3; 3; 3; 3 ];;
val it : int list list = [[1; 1; 1]; [2; 2]; [3; 3; 3; 3]]
I think that the last step is really nice :-). The first two functions are quite straightforward and may be useful for other things, although they are not as general as functions from the F# core library.
A: How about:
let splitOn test lst =
List.foldBack (fun el lst ->
match lst with
| [] -> [[el]]
| (x::xs)::ys when not (test el x) -> (el::(x::xs))::ys
| _ -> [el]::lst
) lst []
the foldBack removes the need to reverse the list.
A: Having thought about this a bit further, I've come up with this solution. I'm not sure that it's very readable (except for me who wrote it).
UPDATE Building on the better matching example in Tomas's answer, here's an improved version which removes the 'code smell' (see edits for previous version), and is slightly more readable (says me).
It still breaks on this (splitOn (<>) []), because of the dreaded value restriction error, but I think that might be inevitable.
(EDIT: Corrected bug spotted by Johan Kullbom, now works correctly for [1;1;2;3]. The problem was eating two elements directly in the first match, this meant I missed a comparison/check.)
//Function for splitting list into list of lists based on comparison of adjacent elements
let splitOn test lst =
let rec loop lst inner outer = //inner=current sublist, outer=list of sublists
match lst with
| x::y::ys when test x y -> loop (y::ys) [] (List.rev (x::inner) :: outer)
| x::xs -> loop xs (x::inner) outer
| _ -> List.rev ((List.rev inner) :: outer)
loop lst [] []
splitOn (fun a b -> b - a > 1) [1]
> val it : [[1]]
splitOn (fun a b -> b - a > 1) [1;3]
> val it : [[1]; [3]]
splitOn (fun a b -> b - a > 1) [1;2;3;4;6;7;8;9;11;12;13;14;15;16;18;19;21]
> val it : [[1; 2; 3; 4]; [6; 7; 8; 9]; [11; 12; 13; 14; 15; 16]; [18; 19]; [21]]
Any thoughts on this, or the partial solution in my question?
A: "adjacent" immediately makes me think of Seq.pairwise.
let splitAt pred xs =
if Seq.isEmpty xs then
[]
else
xs
|> Seq.pairwise
|> Seq.fold (fun (curr :: rest as lists) (i, j) -> if pred i j then [j] :: lists else (j :: curr) :: rest) [[Seq.head xs]]
|> List.rev
|> List.map List.rev
Example:
[1;1;2;3;3;3;2;1;2;2]
|> splitAt (>)
Gives:
[[1; 1; 2; 3; 3; 3]; [2]; [1; 2; 2]]
A: I would prefer using List.fold over explicit recursion.
let splitOn pred = function
| [] -> []
| hd :: tl ->
let (outer, inner, _) =
List.fold (fun (outer, inner, prev) curr ->
if pred prev curr
then (List.rev inner) :: outer, [curr], curr
else outer, curr :: inner, curr)
([], [hd], hd)
tl
List.rev ((List.rev inner) :: outer)
A: I like answers provided by @Joh and @Johan as these solutions seem to be most idiomatic and straightforward. I also like an idea suggested by @Shooton. However, each solution had their own drawbacks.
I was trying to avoid:
*
*Reversing lists
*Unsplitting and joining back the temporary results
*Complex match instructions
*Even Seq.pairwise appeared to be redundant
*Checking list for emptiness can be removed in cost of using Unchecked.defaultof<_> below
Here's my version:
let splitWhen f src =
if List.isEmpty src then [] else
src
|> List.foldBack
(fun el (prev, current, rest) ->
if f el prev
then el , [el] , current :: rest
else el , el :: current , rest
)
<| (List.head src, [], []) // Initial value does not matter, dislike using Unchecked.defaultof<_>
|> fun (_, current, rest) -> current :: rest // Merge temporary lists
|> List.filter (not << List.isEmpty) // Drop tail element
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2279095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: invoking functions defined by flet in another function I have a collection of functions defined in foo that I want to also want to use in bar. I have these functions defined in foo because I want foo to be self-contained -- otherwise I know that I can define these functions externally (globally) to be accessible to foo and bar and other functions, or define both foo and bar within a labels construct in which these functions are defined only for foo and bar. In any case, I would like for foo to be distributable without the external functions or the labels structure. Hence the challenge.
This is what I have so far (I am using Emacs Lisp in this case), but what I have now ends up defining the local functions in foo globally when I invoke bar. Any suggestions how to define local variables/functions in bar "on the fly"?
(defun foo (x)
(flet ((addone (x) (1+ x))
(addtwo (x) (+ 2 x)))
(addtwo x)))
(defun bar (x)
(let* ((fnlist (car (cdaddr (symbol-function 'foo))))
(nfn (length fnlist))
(ifn nil)
(bar-body '(addone x))
(i 0))
(eval (append
;; local symbol names
;; to which function definitions will be set
(list 'let (mapcar 'car fnlist))
;; set function definitions
(list '(while (< i nfn)
(setq ifn (nth i fnlist))
(eval `(fset ',(car ifn) ,(append (list 'lambda) (cdr ifn))))
(setq i (1+ i))))
;; function invocation
(list bar-body)))))
Function application:
(foo 1) ;;=> 3
(bar 1) ;;=> 2
(addone 1) ;;=> 2 ?should not be defined outside of bar?
A: This isn't self-contained, so it's not really an answer; but it's different to the other options you mentioned, so I'll add it anyway.
(defmacro with-foo-functions (&rest forms)
`(flet ((addone (x) (1+ x))
(addtwo (x) (+ 2 x)))
,@forms))
(defun foo (x)
(with-foo-functions
(addtwo x)))
(defun bar (x)
(with-foo-functions
(addone x)))
A: Emacs Lisp has dynamic binding. This is different from the lexical binding used by pretty much all other Lisps. For example, if you try to do the following in Common Lisp, you will get an error message saying that FOO is not defined:
(defun bar ()
(foo 10))
(flet ((foo (x) (1+ x)))
(bar))
In Emacs Lisp, however, since FOO is dynamically bound this will return 11 as the binding of FOO is available in BAR.
Emacs Lisp does not provide lexical bindings for functions, so in order to achieve the same thing in Emacs Lisp you'll have to fake it by binding a lambda to a lexical variable and then use a macro to hide the FUNCALL:
(lexical-let ((foo #'(lambda (x) (1+ x))))
(macrolet ((foo (x) `(funcall foo ,x)))
(foo 10)))
The other answer to this question suggests the use of a macro instead of the flet. This works, but it results in unnecessary code duplication. My solution prevents this at the expense of having to either write the macrolet part, or using funcall every time you want to call the function. One could write a macro to wrap all of this inside a lexical flet version if this is something that is needed often.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6887903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does HashSet not implement ICollection? I am going to write a library to traverse an object graph (like some kind of serialization).
You will need to judge if an object is a collection in the traverse, so the ICollection came out of my mind. (string has also implemented IEnumerable)
But it is really weird that almost all containers in Collections have implemented ICollection except HashSet only implemented ICollection<T>...
I have checked out almost all common containers in System.Collections namespace:
ArrayList : IList, ICollection, IEnumerable, ICloneable
BitArray : ICollection, IEnumerable, ICloneable
Hashtable : IDictionary, ICollection, IEnumerable, ISerializable, IDeserializationCallback, ICloneable
Queue : ICollection, IEnumerable, ICloneable
SortedList : IDictionary, ICollection, IEnumerable, ICloneable
Stack : ICollection, IEnumerable, ICloneable
Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback
HashSet<T> : ISerializable, IDeserializationCallback, ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable
LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
Queue<T> : IEnumerable<T>, ICollection, IEnumerable
SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
SortedSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
Stack<T> : IEnumerable<T>, ICollection, IEnumerable
Is this a bug? Or there are some reason behind?
A: ICollection isn't anywhere near as useful now as it was with .NET 1.1 when there was no ICollection<T> offering greater type safety. There's very little one can usefully do with ICollection that one can't do with ICollection<T>, often with greater efficiency and/or type safety, especially if one writes generic methods for those cases where one might want to do something with collections of different element types.
This though begs the question of why the likes of List<T> did implement ICollection. But when List<T> was introduced with .NET 2.0 all legacy code was using ICollection and ArrayList, not ICollection<T> and List<T>. Upgrading code to use List<T> rather than ArrayList can be a pain, especially if it means having to either immediately change all uses of ICollection it would hit to use ICollection<T> or, even worse, double up because a method was being hit with the List<T> that was also being hit with other non-generic collections and so versions of the method would be needed for each. Implementing ICollection eased the upgrade path by allowing people to be more piecemeal in how they took advantage of generic collections.
When HashSet<T> came out generics had been in use for three years already, and there was not a previous non-generic hash-set type provided by the framework, so there was less of an upgrade pain, and hence less of a motivation for supporting ICollection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31273003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Why mangled names found within an exe? I have an MS C/C++ statically linked release exe (no debug info on it), that does not export any symbol, but when browsing it with a hex viewer I see things like
.?AVElxInterface@@
.?AV?$CBufferRefT@H@@
.?AV?$CBufferT@H@@
.?AV?$CBufferRefT@PAVElxInterface@@@@
of course they are the mangled names of certain classes/members provided by the internal C++ modules.
why are they there? how can avoid exposing them?
A: Personally, I don't see any reason to over-hide this data, as it supplies no clue to people who view it on how to utilize these symbols to do something "bad". However, if that's really a huge problem for you, i.e. you are afraid of being sort of reverse-engineered somehow, then you may opt to code obfuscation. For example, Semantic Designs offer a product for these purposes and claim that it's of high quality. I've never had a chance to try that stuff myself. Keep in mind that it's commercial.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15359696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: EF Core: Column with ValueGeneratedOnAdd trows "Cannot insert explicit value for identity column..." I have ASP.NET MVC 5 application that uses Entity Framework 6.2. This app creates some records in MS SQL server.
I have to process this records in AWS lambda function. For this purpose, I created c# .NET Core v2.0 lambda function. There I generate models from existed DB as described in the next article - Getting Started with EF Core on ASP.NET Core with an Existing Database.
Generated models look like:
public partial class Request
{
public int EntityId { get; set; }
public Result Result { get; set; }
}
public partial class Result
{
public int EntityId { get; set; }
public Request Entity { get; set; }
}
And OnModelCreating:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Request>(entity =>
{
entity.HasKey(e => e.EntityId);
entity.ToTable("Request", "mySchema");
});
modelBuilder.Entity<Result>(entity =>
{
entity.HasKey(e => e.EntityId);
entity.ToTable("Result", "mySchema");
entity.HasIndex(e => e.EntityId).HasName("IX_EntityId");
entity.Property(e => e.EntityId).ValueGeneratedOnAdd();
entity.HasOne(d => d.Entity)
.WithOne(p => p.Result)
.HasForeignKey<Result>(d => d.EntityId)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_mySchema.Result_mySchema.Request_EntityId");
});
}
In the lambda function, I am processing a request and setting result:
using (var db = new DataContext(connection))
{
var request = db.Request.First();
request.Result = new Result();
db.SaveChanges();
}
On the save operation I got the exception:
Cannot insert explicit value for identity column in table 'Result' when IDENTITY_INSERT is set to OFF.
I checked different way to solve this issue. But there are already set ValueGeneratedOnAdd function in model creating method.
Also, I tried to add [DatabaseGenerated(DatabaseGeneratedOption.Identity)] to Result.EntityId - without any success.
What did I miss in my implementation?
A: You are trying to initialize request.Result with new Result() which has no values. That may cause this error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49264548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Win32 ToolTip disappears never to re-appear with Commctl 6 I'm creating a ToolTip window and adding tools to it using the flags
TTF_IDISHWND | TTF_SUBCLASS. (c++, win32)
I have a manifest file such that my program uses the new WindowsXP themes
(comctrl32 version 6).
When I hover over a registered tool, the tip appears.
Good.
When I click the mouse, the tip disappears.
Ok.
However, moving away from the tool and back
again does not make the tip re-appear. I need to hover over a different tool
and then come back to my tool to get the tip to come back.
When I remove my manifest file (to use the older non-XP comctrl32), the
problem goes away.
After doing some experimentation, I discovered the following differences
between ToolTips in Comctl32 version 5 (old) and Comctl32 version 6 (new):
*
*New TTF_TRANSPARENT ToolTips (when used In-Place) actually return
HTCLIENT from WM_NCITTEST if a mouse button is down, thus getting
WM_LBUTTONDOWN and stealing focus for a moment before vanishing. This causes
the application's border to flash.
*Old TTF_TRANSPARENT ToolTips always return HTTRANSPARENT from WM_NCHITTEST,
and thus never get WM_LBUTTONDOWN themselves and never steal focus. (This seems to be just aesthetic, but may impact the next point...)
*New ToolTips seem not to get WM_TIMER events after a mouse-click, and
only resume getting (a bunch of) timer events after being de-activated and
re-activated. Thus, they do not re-display their tip window after a mouse
click and release.
*Old ToolTips get a WM_TIMER message as soon as the mouse is moved again
after click/release, so they are ready to re-display their tip.
Thus, as a comctl32 workaround, I had to:
*
*subclass the TOOLTIPS_CLASS window and always return HTTRANSPARENT from
WM_NCHITTEST if the tool asked for transparency.
*avoid using TTF_SUBCLASS and rather process the mouse messages myself so
I could de-activate/re-activate upon receiving WM_xBUTTONUP.
I assume that the change in internal behavior was to accommodate the new "clickable" features in ToolTips like hyperlinks, but the hover behavior appears to be thus broken.
Does anyone know of a better solution than my subclass workaround? Am I missing some other point?
A: You're not the only one who has hit compatablity issues with tooltips between these DLLS.
I too have had nothing but trouble with the new tooltips in the themable common controls. We have already been monkeying with mouse messages and active/deactivating the tips before adding the manifest and theming our application - so it sounds like what your doing isn't too crazy.
We're still living with problems with TTN_NEEDTEXT messages being send constantly as the mouse moves (not just when hovering), positioning problems with large tips (maybe not something new), and odd unicode messages being sent instead of the ANSI versions (which I plan to post as a question at some point).
A: I don't know, but this sounds like a really "hard" problem (in the sense that all real-world) problems are really hard. I bet the underlying problem is something to do with the setting of the focus. Windows that manually do that are evil and generally suffer from all manner of bugs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Can't import modules I've searched for this problem and tried different solutions but can't fix it.
In my Django project I have different apps and a non-app directory called 'testing_utils' with modules which serve for a testing purposes. In particular I want to import all available models to file dummy_factory.py. However when I simply import modules from my apps like so:
from abc import ABC
from datetime import date
from users.models import User
I get the error message
ModuleNotFoundError: No module named 'users'
Which is strange since I definetley can import models to some_app.views.py and access them.
Here's an example of my project's directory:
/home/user/dev/project/
▸ project/
▾ testing_utils/
dummy_factory.py
▾ users/
▸ __pycache__/
▸ migrations/
▸ templates/
▸ tests/
__init__.py
admin.py
apps.py
models.py
views.py
manage.py*
A: /home/user/dev/project/ needs to be in your PYTHONPATH to be able to be imported.
If your testing_utils is meant to be local only, the easiest way to accomplish this is to add:
import sys
sys.path.append('/home/user/dev/project/')
... in dummy_factory.py before importing the module.
Solutions that would be more proper would be to install users (how exactly you'd make your package installable depends on your system and what version of Python and Pip you need to support), or to use a virtualenv that automatically adds the right directories to PYTHONPATH.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72714734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call specific method of portlet.java class rather then overide serveResource method? I want some help in liferay with ajax.
Right now I am calling the ajax method from my view.jsp page to submit some data.
Here is sample code I am using in view.jsp:
<%@ include file="/init.jsp"%>
<portlet:actionURL name="AddTest" var="add1" />
<portlet:resourceURL id="AddTest" var="AddTest"></portlet:resourceURL>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function addToDo(addToDo){
var todo =document.getElementById('toDo').value;
$.ajax({
url :addToDo,
data: {"todo":todo,"CMD":"addToDo"},
type: "GET",
dataType: "text",
success: function(data) {
$("#toDoList").html(data);
}
});
}
</script>
</head>
<body>
<portlet:resourceURL var="addToDo" id="addToDo"></portlet:resourceURL>
<form>
<input type="text" name="toDo" id="toDo">
<button name="Add" type="button" onclick="addToDo('<%=addToDo%>')">Add</button>
<div id="toDoList">
</div>
</form>
</body>
</html>
and in my portlet.java class there is one method which is called by this ajax call:
@Override
public void serveResource(ResourceRequest request, ResourceResponse response){
if(request.getParameter("CMD").equals("addToDo")) {
System.out.println("came here for add");
mediatype userToDo = new mediatypeImpl();
//userToDo.setMediaId(12345);
try {
userToDo.setPrimaryKey((CounterLocalServiceUtil.increment()));
userToDo.setMedianame(request.getParameter("todo"));
mediatypeLocalServiceUtil.addmediatype(userToDo);
}
catch (SystemException e) {
e.printStackTrace();
}
}
}
So my question is that right now it is just caling by default @override method from any ajax class.
But how can I call specific method of portlet.java class on ajax call?
I am new bee in ajax. So please guide me anyways u can.....
I got following error when calling ajax with url of following
<portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>"> </portlet:actionURL>
06:47:03,705 ERROR [http-bio-8080-exec-23][render_portlet_jsp:154] java.lang.NoSuchMethodException: emenu.advertise.portlet.RestaurantPortlet.ajax_AddAdvertise(javax.portlet.ActionRequest, javax.portlet.ActionResponse)
at java.lang.Class.getMethod(Class.java:1605)
my process action method as follows
@ProcessAction(name = "ajax_AddAdvertise")
public void ajax_AddAdvertise(ResourceRequest request,ResourceResponse response) {
}
A:
how can I call specific method of portlet.java class on ajax call?
I think we can't have two different versions of serveResource methods like we do for action methods atleast not with the default implementation.
If you want different methods you would have to go the Spring MVC (@ResourceMapping) way to have that.
Still, you can define different logic in your serveResource method using the resourceId as follows (a full example):
In the JSP:
<portlet:resourceURL var="myResourceURL" id="myResourceID01" />
In the portlet class the serveResource method will contain the following code:
String resourceID = request.getResourceID();
if(resoureID.equals("myResourceID01")) {
// do myResourceID01 specific logic
} else {
// else do whatever you want
}
Please keep in mind [Important]
In a portlet you should not use <html>, <head>, <body> tags since portlets generate fragment of the page and not the whole page. Even if it is allowed your resultant page will not be well-formed and will behave differently on different browsers. And moreover the javascript which modifies DOM element will be totally useless.
Edit after this comment:
You can also use ajax with action methods:
People use <portlet:actionURL> with ajax generally for <form>-POST.
For this the actionURL is generated in a slightly different way in your jsp like this:
<portlet:actionURL name="ajax_AddAdvertise" var="addToDo" windowState="<%= LiferayWindowState.EXCLUSIVE.toString()%>">
</portlet:actionURL>
And in your portlet you can have (as in the question):
@ProcessAction(name = "ajax_AddAdvertise")
public void ajax_AddAdvertise(ActionRequest request, ActionResponse response) {
// ... your code
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13246870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Vue Material - Triggering MdTableAlternateHeader visibility I'm looking for a way to trigger the MdAlternateHeader visibility - or maybe to reset its count state.
The app in question has this multi-selection MdTable in which I implemented a delete function per row. But on data erasing, the alternate header still hold the md-selected class set to true (refeered to the deleted and previously selected element/row). As well as the related computed props (isInSelectedItems and isMultipleSelected).
How can I change these state? I was thinking about to trigger a "selected" or "clicked" event on the row befote its deletion, but I'm missing something on the way.
Thanks in advance for the help.
A: Ok, I got it.
I inspected the framework data and noticed this md-selected-value prop, contained in MdTable component. After declaring the prop in my component:
props: [
// ...
'mdSelectedValue'
],
I update its value through a second array, delegated to track what elements are being selected for deletion:
data: () => ({
selezionato = []
})
then I listen for any change in selection:
<md-table v-model="cercato" @md-selected="onSelezionato" md-sort="codice" md-sort-order="asc" md-card md-fixed-header :md-selected-value="selezionato">
In my delete function, after every deletion I reset the the new selezionato value, in order to disable the alternate header:
this.selezionato = []
That's it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51321156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Item not showing in list view after added to database After I add the items in database they show only after I restart the app. How to fix this? I have tried using notifyDataSetChanged() but not sure if i did good.
Fragment showing ListView and Button which calls Add Item Activity:
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
Button button = (Button)v.findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), NewData.class);
startActivityForResult(intent, 0);}});
listView = (ListView)v.findViewById(R.id.listView);
listDataAdapter = new ListDataAdapter(getActivity().getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdapter);
userDbHelper = new UserDbHelper (getActivity().getApplicationContext());
sqLiteDatabase = userDbHelper.getReadableDatabase();
cursor = userDbHelper.getInformations(sqLiteDatabase);
if(cursor.moveToFirst()){
do {
String nr1, nr2, nr3;
nr1 = cursor.getString(0);
nr2 = cursor.getString(1);
nr3 = cursor.getString(2);
DataProvider dataProvider = new DataProvider(nr1, nr2, nr3);
listDataAdapter.add(dataProvider);}
while (cursor.moveToNext());}
Add item Activity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.additemactivity);
number_1 = (EditText)findViewById(R.id.number11);
number_2 = (EditText)findViewById(R.id.number12);
number_3 = (EditText)findViewById(R.id.number13);
Button button1=(Button)findViewById(R.id.shtobtn);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String number1 = number_1.getText().toString();
String number2 = number_2.getText().toString();
String number3 = number_3.getText().toString();
userDbHelper = new UserDbHelper(context);
sqLiteDatabase = userDbHelper.getWritableDatabase();
userDbHelper.addInformations(number1, number2, number3, sqLiteDatabase);
Toast.makeText(getBaseContext(),"Data Saved",Toast.LENGTH_SHORT).show();
userDbHelper.close();
Intent intent=new Intent();
setResult(RESULT_OK, intent);
finish();}});
List Data Adapter:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null){
LayoutInflater layoutInflater =(LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.NUMER1=(TextView)row.findViewById(R.id.number11);
layoutHandler.NUMER2=(TextView)row.findViewById(R.id.number12);
layoutHandler.NUMER3=(TextView)row.findViewById(R.id.number13);
row.setTag(layoutHandler);}
else { layoutHandler = (LayoutHandler)row.getTag();}
DataProvider dataProvider = (DataProvider)this.getItem(position);
layoutHandler.NUMER1.setText(dataProvider.getNum1());
layoutHandler.NUMER2.setText(dataProvider.getNum2());
layoutHandler.NUMER3.setText(dataProvider.getNum3()); return row;
A: Add listView.notifyDataSetChanged(); after list is updated.
A: Create one public method in adapter class which is notifyDataSetChanged()
A: If you are using SQLite DB then to automatically populated the updated database values into your list view, you should extend your custom adapter with CursorAdapter. Once you fetch data in cursor it will automatically show you the updated values;
public class CustomAdapter extends CursorAdapter {
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.your_list_item, parent, false);
// return null;
}
@Override
public Object getItem(int position) {
return super.getItem(position);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
}
}
A: In your Fragment
private SharedPreferences.Editor editor;
private SharedPreferences sharedpreferences;
UpdatingReceiver updatingReceiver;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
editor = sharedpreferences.edit();
editor.putString("some unique key", name);
String name = "Inside";
}
@Override
protected void onPause() {
super.onPause();
editor = sharedpreferences.edit();
String name = "Outside";
editor.putString("some unique key", name);
editor.commit();
}
@Override
protected void onStart() {
super.onStart();
updatingReceiver = new UpdatingReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("updating receiver unique key");
registerReceiver(updatingReceiver, intentFilter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(updatingReceiver);
}
class UpdatingReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//list all the data
//set adapter
//notifyDataSetChanged
}
}
So you can come to know if you are in inside the fragment or outside the fragment. Based on that you should trigger from your activity.
In your Activity, after you added the code in db just call the receiver based on inside or outside. So it will update immediately.
private SharedPreferences.Editor editor;
private SharedPreferences sharedpreferences;
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
String prefsString = sharedpreferences.getString("some unique key", "");
if (prefsString=="Inside")
{
Intent broadCast = new Intent();
broadCast.setAction("updating receiver unique key");
sendBroadcast(broadCast);
}
A: The solution:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {adapter.notifyDataSetChanged();}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32353478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django App - Ajax Auto-complete After 2 Characters and 1s Delay I have this piece of code in my Django app to create simple auto-complete search suggestion box. How do I limit the Ajax to at least 2 characters and how can I add lets say 1sec delay for the Ajax to execute the search query?
$(function(){
$('#search').keyup(function() {
$.ajax({
type: "POST",
url: "/search/",
data: {
'search_text' : $('#search').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#search-results').html(data);
}
A: Assuming that #search is probably a text input field, you can add the following code right before your ajax request:
// get the value that the user has typed
var v = $(this).val();
// don\'t go on if less than 3 chars or
// some other key was pressed that did not change the data
if (v.length < 3 || v == $(this).data('prev-val')) return;
// set the old value as the new one
$(this).data('prev-val', v);
// now call ajax
Following a comment in the question, this does not deal with any time delay. A timer could easily be used to trigger the ajax request, and cancel any previous timer before setting a new one. But this would probably make matters more complicated for no good reason.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30314000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: $.each is looping over each character in my json and displaying undefined i need to loop over the below json but the below code is looping over each character in my json and displaying "undefined": (is there anything wrong with the below json??? Any help is appreciated)
{"news_id":"1","news_title":"News Title One","news_date":"2012-03-20","news_pic":"album-bb[6].jpg","news_desc":"Here goes the news title one Here goes the news title one Here goes the news title one Here goes the news title one.","gallid":"3"}
{"news_id":"2","news_title":"News Title Two","news_date":"2012-04-14","news_pic":"174863_163190093755777_2032987021_q.jpg","news_desc":"News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two News Title Two.","gallid":"0"}
This is my code which is being fired on click event:
var phpNews;
var NewsObject;
$(document).ready(function () {
$("#btnNewsPage").click(function()
{
$.post("server/news.php",null,function(e){
NewsObject = e;
$.mobile.changePage("#NewsPage");
});
});
$('#NewsPage').live('pagebeforeshow',function(event, ui){
var list;
$.each(NewsObject, function(k,v){
list = v.news_title;
});
$("#displayNews").html(list);
});
})
A: Looks like, your NewsObject isn't a JSON object but string. It could happen because JQuery can't guess the response type, so you, probably, need to specify dataType for your $.post request (documentation):
$.post("server/news.php", null, function(e){ ... }, 'json');
P.S. Also your JSON not looks valid, i expect to see something like {'a':'b'}, but you have {'a':'b'} {'c':'d'}.
Updated. Based on the comments below, i would suggest you to use next PHP code for your server/news.php:
<?php
require "../includes/config.php";
require "../includes/h.conn.php";
require "../includes/admin.id.php";
$strSQL = "select * from news where admin_id=" .$admin_id;
$objRS = mysql_query($strSQL);
$News_Obj = array();
while ($row = mysql_fetch_assoc($objRS)) {
$record = array (
"news_id" => $row['news_id'],
"news_title" => $row['news_title'],
"news_date" => $row['news_date']
);
$News_Obj[] = $record;
}
// don't forget to clear after yourself: mysql_free_result, disconnect
header("Content-type: application/json");
echo json_encode($News_Obj);
?>
Also you can use Firebug to see what exactly returns the script and which HTTP or Javascript errors happen when you do a request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10143269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF Site Blocked by McAfee, how to unblock without turning off firewall McAfee's firewall was blocking me from using a WCF client I made in C# .NET over a local network until I disabled it. How can I keep the firewall up and add an exception or something for my stie hosted in IIS? Like when the firewall is up, navigating to http://mark-pc from the other computers comes up with nothing but if you turn off the firewall it comes up with my locally hosted IIS site (which is what I want). I dont want to turn off the whole firewall so how can I just let that connection go out?
Even when I allow Port 80 though McAfee, it doesn't work. They can view it in a browser but trying to ping mark-pc fails.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7127437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Xamarin.Forms navigation stack flow I'm trying to work out the correct way of structuring the navigation for my Xamarin.Forms application.
Please note the LoginPage is currently set as the application's MainPage.
The intended (visual) structure is as follows:
CheckPermissionsPage ➜ LoginPage ➜ HomePage
I am following a MVVM structure, so my LoginPageViewModel is displaying a modal of CheckPermissionsPage within it's constructor as so:
await Application.Current.MainPage.Navigation.PushModalAsync(new CheckPermissionsPage());
The idea is that the check permissions page validates the application has permissions to specific services and if it does, the page automatically closes. The user must then login to the application, after which the HomePage is displayed.
How would I structure the LoginPage so that the CheckPermissionsPage modal can be displayed/hidden based on permissions state. Consequently, after a successful login, the HomePage is displayed (without an option to return to the LoginPage). Thanks!
A: I ended up changing the application MainPage to navigate throughout the pages. So my initial application main page is now the CheckPermissionsPage. Should permissions be granted I then run Application.Current.MainPage = new NavigationPage(new LoginPage());. After logging in, the HomePage is displayed with Application.Current.MainPage = new NavigationPage(new HomePage());. This probably isn't the most ideal solution, but it does allow me to prevent back navigation for my LoginPage.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65799114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delaying events in a game loop with Android? If you have a game loop thread in Android that draws to a surfaceview and you require a couple of seconds delay to perform animation, how do you go about doing this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21362461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Control the iterations of triple nested loop in list comprehension, Python I have 2 lists which I need to iterate through:
hits_idx2 = [ 0, 1, 2]
common_b = [ [835,1234,2345] , [223,544] , [423,1234] ]
in order to produce the following output:
0, 835
0, 1234
0, 2345
1, 223
1, 544
2, 423
2, 1234
I created a nested loop using list comprehensions and a check to see if the element returned at the each iteration if the last element in each sublist, if it not the loop should continue, if it is it should go to the next element of hits_idx2 and iterate through the second sublist in common_b:
for x,y in [(x,y) for x in hits_idx2 for ind in hits_idx2 for y in common_b[ind] if y!=common_b[ind][-1]]:
print (x,y)
but unfortunately I am getting the following:
0 835
0 1234
0 223
0 423
1 835
1 1234
1 223
1 423
2 835
2 1234
2 223
2 423
I am kinda stuck, any help more than welcome. thanks!
I solved it as follows:
for h,y in [ (h,common) for h, common in [(h, common) for h, commons in zip(hits_idx2, common_b) for common in commons] ]:
print(h,y)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53997698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I run a single test in Scala? I'm going through the scala labs and I can't seem to figure out how to run a single test.
I run test in sbt and I get 23 failing tests for me to fix. I want to run just the HelloWorldExercise.scala. How would I do this?
A: sbt "testOnly HelloWorldExercise"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23462593",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Angular2 input data getting lost on button click I have created Angular2 code like this to get the data on button click
<div class="field-panel">
<div>
<span>
<input #newData [(ngModel)]="data.id" type="text" >
<select #newCategory [(ngModel)]="i.index" class="input-bars">
<option *ngFor="let data of field" [value]="data.value">{{data.value}}</option>
</select>
</span>
<button class="btn btn-success (click)="addData(newData.value, newCategory.value)">ADD</button>
</div>
</div>
addData(value, dropValue){
this.Data[index] = value;
}
But when the button is clicked the data on the input field is getting lost in ui. How to keep it when the button is clicked and display on the ui as well??
A: I'll hazard a guess that you're working in a form, so add type="button" to the button <button class="btn btn-success" (click)="addData(newData.value)">ADD</button>. That should prevent it from thinking the form is submitting and clearing the data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40406409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: reading lines of text in a nonblocking way In a C program I want to read text lines from stdin.
At the same time I want to handle data coming from another file descriptor.
I tried to use poll to wait for any of the two source to become readable and handle them accordingly. However poll needs bare file descriptors and for reading whole lines with something like fgets I need a FILE handle.
I can use fileno or fdopen to "convert" them, but using both in a mixed way does not seem to be a good idea.
Therefore, is there a good way to wait for lines of text without blocking or threading?
A: You can use whatever you want for multiplexing (select(), poll(), epoll_wait()). But you shouldn't read from stdin with fgets() because multiplexing knows nothing about if we've got complete line or no. So it may block in some cases. You should write custom line reading function, that will indicate that there is no complete line yet and return immediately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38240602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Decimal Module in Python Why does this code output 25 although I used the decimal module. I tried it on the calculator and it outputted 26.28.
from decimal import *
getcontext().prec = 2
targetPrice = 40
currentPrice = 56.5
winChance = 0.9
stopLoss = 23
lossChance = 0.1
expectancy =100 * abs(((Decimal(targetPrice) - Decimal(currentPrice)) / Decimal( currentPrice))) * Decimal(winChance)
print(expectancy)
A: You're getting inexact results because you're rounding down to two decimal places after every calculation. Your calculator isn't doing that.
With no rounding.
>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.2920353982300884955752212389')
With rounding:
>>> (Decimal(40) - Decimal(56.5)) / Decimal(56.5)
Decimal('-0.28')
It only gets worse after that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69469363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unable to build c++ application using nw-gyp build. Error: error MSB6006: "CL.exe" exited with code -1073741515 I have tried to set up nw-gyp on Windows 8.1 x64 by following the following link:
nw-gyp installation guide
For this I installed:
*
*Python v2.7
*Node v4.2.2 (Setted its path too in environment variable)
*npm v2.14.7
*node-webkit v0.12.3
*Microsoft Visual Studio C++ 2012 for Windows Desktop Express version From Here
after this I installed nw-gyp using the following command.
*
*npm install -g nw-gyp
Now I tried to run the demo app provided here nw-gyp Example
Now I configure the app using command:
*
*nw-gyp configure --target=0.12.3
0.12.3 is my node webkit version. The configuration is successful and I am able to get the build folder. But further when I try to build the addon using command
*
*nw-gyp build
I get the following error
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x64.targets(146,5): error MSB6006: "CL.exe" exited with code -1073741515. [E:\PacificCX\testSecond\build\binding.vcxproj]
Here is the full log:
E:\PacificCX\testSecond>nw-gyp build
gyp info it worked if it ends with ok
gyp info using [email protected]
gyp info using [email protected] | win32 | x64
(node) child_process: options.customFds option is deprecated. Use options.stdio
instead.
gyp info spawn C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
gyp info spawn args [ 'build/binding.sln',
gyp info spawn args '/clp:Verbosity=minimal',
gyp info spawn args '/nologo',
gyp info spawn args '/p:Configuration=Release;Platform=x64' ]
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Microsoft.CppBuild.targets(29
7,5): warning MSB8003: Could not find WindowsSDKDir variable from the registry.
TargetFrameworkVersion or PlatformToolset may be set to an invalid version nu
mber. [E:\PacificCX\testSecond\build\binding.vcxproj]
C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\Microsoft.Cpp.x
64.targets(146,5): error MSB6006: "CL.exe" exited with code -1073741515. [E:\Pa
cificCX\testSecond\build\binding.vcxproj]
gyp ERR! build error
gyp ERR! stack Error: `C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe
` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Users\kamaldeep.singh\AppData\Roam
ing\npm\node_modules\nw-gyp\lib\build.js:267:23)
gyp ERR! stack at emitTwo (events.js:87:13)
gyp ERR! stack at ChildProcess.emit (events.js:172:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:200:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\kamaldeep.sin
gh\\AppData\\Roaming\\npm\\node_modules\\nw-gyp\\bin\\nw-gyp.js" "build"
gyp ERR! cwd E:\PacificCX\testSecond
gyp ERR! node -v v4.2.2
gyp ERR! nw-gyp -v v0.12.4
gyp ERR! not ok
Someone please help me solve this out. Thanks in advance.
Here is the link to my complete sample program. Download Sample
A: solved this problem by updating Visual Studio 2012.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33841221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting text after URL in asp.net / URL Rewriting (sort of!) My app is a very simple "one page" type app-
It has Default.aspx
I'm basically trying to get, for example:
www.myappurl.com/this is my text
I want to get hold of "this is my text" from the above example.
This will be displayed on the page (for now)
I didn't really want to have to use any complext url rewriting things for this...
(My hosting provider uses IIS6)
I tried using a 404 handler, but this is a bit long winded, and i'm using shared hosting, that can't set the "execute url" on custom 404 pages.
Any other ideas?
A: You can add a mapping for all requests with the * extension to the ASP.NET isapi dll (GET/POST) verbs. You will need to uncheck the "verify file is on disk" checkbox when mapping the extension in IIS. (In IIS7 integrated mode, you map the extension in the web.config as well). Note that this will caause everything to be served by asp.net, even images and script files, which can slow things down.
Then create a handler mapping in your web.config to a http handler you create.
From there, in the ProcessRequest() method of the handler, you have access to the HttpContext that spawned the request and can manipulate the URL from there.
That is the easiest option, you could also create a HttpModule, or have the default page at root redirect to http://www.domain.com/default.aspx/this is my text, in the code-behind of default.aspx, you will be able to get the text following the page and slash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2997372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: docker push to nexus 3 - invalid checksum digest format Though I am able to successfully push a newly pulled docker image to Nexus 3 docker hosted repo, an error like "invalid checksum digest format" is thrown at the end. I pulled "jenkins:latest" from dockerhub, then tagged it and then pushed it to a nexus docker hosted repo.
f3e4e0468545: Pushed
656120ad8c56: Pushed
30f9a83f20f3: Pushed
78dbfa5b7cbc: Pushed
invalid checksum digest format
I know Nexus 3 is not LTS yet, but want to be sure that its not my environment settings. I have an insecure docker registry on 18443
docker info
Containers: 1
Running: 0
Paused: 0
Stopped: 1
Images: 53
Server Version: 1.10.1
Storage Driver: aufs
Root Dir: /var/lib/docker/aufs
Backing Filesystem: extfs
Dirs: 89
Dirperm1 Supported: true
Execution Driver: native-0.2
Logging Driver: json-file
Plugins:
Volume: local
Network: bridge null host
Kernel Version: 3.16.0-53-generic
Operating System: Ubuntu 14.04.3 LTS
OSType: linux
Architecture: x86_64
CPUs: 2
Total Memory: 3.86 GiB
Client:
Version: 1.10.1
API version: 1.22
Go version: go1.5.3
Git commit: 9e83765
Built: Thu Feb 11 19:27:08 2016
OS/Arch: linux/amd64
Server:
Version: 1.10.1
API version: 1.22
Go version: go1.5.3
Git commit: 9e83765
Built: Thu Feb 11 19:27:08 2016
OS/Arch: linux/amd64
A: Docker version 1.10 was not out when Nexus 3.0m7 was released. We are working on adding support for it now. This specific issue is being tracked here:
https://issues.sonatype.org/browse/NEXUS-9766
UPDATE: This issue/ticket is resolved now in Nexus Repository Manager 3.0.0-03. For upgrade instructions see https://support.sonatype.com/hc/en-us/articles/217967608-How-to-Upgrade-Nexus-3-Milestone-m7-to-3-0-0-Final.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35399864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iPhone didreceivememorywarning strategy If i have a array of employees for example in my viewcontroller. Then I get the notification of low memory and the app is also not the active one.
At this point I should save the list of employees in a DB right ? so that when the user reactivate the app again, it will go through the viewDidLoad and from here I can reload the data from the DB?
Is this a good strategy?
I'm fairly new into iPhone dev.
A: You should save any unsaved changes as soon as your app enters the background. Your app could be terminated at any point in the background without ever receiving any notifications of any kind. If your data isn't saved, it will be lost when the user restarts the app.
With regard to memory warnings, these are more likely to happen in the foreground. Once your app is in the background, it is suspended and won't get any notifications. If your app is running under iOS 5 or earlier then a memory warning could result in a view controller's viewWillUnload method being called. When that view controller needs to be displayed again, its viewDidLoad will be called again. Under iOS 6, this doesn't happen anymore. viewWillUnload is deprecated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12874596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Eigen::SparseTriangularView I am trying to switch some code from Eigen 3.2.10 to 3.3. I am running into compile errors with this method declaration
/// \brief Returns template expression for the lower triangular part of A.
Eigen::SparseTriangularView < SystemMatrixType, Eigen::Lower >
getLowerTriangular() const;
producing error C2143: syntax error : missing ';' before '<'.
It looks like SparseTriangularView has been renamed or replaced. What should SparseTriangularView or this whole declaration be replaced by?
A: Just use TriangularView < SystemMatrixType, Eigen::Lower >. Triangular and Selfadjoint views of dense and sparse expressions have been unified in 3.3.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43125221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I get the body in a SOAP response when I have a ClientTransportException In SoapUI/Postman I am sending this request
Notice how I am getting a 401 Unauthorized, but I am getting a response body. The 401 is expected.
Now I am trying to send this message with jax-ws. I intercept the messageresponse with a handler.
My handler looks like this:
public class SHandler implements SOAPHandler<SOAPMessageContext> {
@Override
public Set<QName> getHeaders() {
System.out.println(">>>>>>>>>>> GetHeaders");
return null;
}
@Override
public boolean handleMessage(SOAPMessageContext soapMessageContext) {
boolean isRequest = (Boolean) soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!isRequest) {
try {
System.out.println(soapMessageContext.getMessage().getSOAPBody().getValue(););
} catch (SOAPException e) {
e.printStackTrace();
}
}
System.out.println(">>>>>>>>> Message");
return true;
}
@Override
public boolean handleFault(SOAPMessageContext soapMessageContext) {
try {
System.out.println(soapMessageContext.getMessage().getSOAPBody().getValue());
} catch (SOAPException e) {
e.printStackTrace();
}
System.out.println(">>>>>>>>>>> HandleFault");
return true;
}
@Override
public void close(MessageContext messageContext) {
System.out.println(">>>>>>>>>>> Close");
}
}
I would expect to get a return value from the request, but I get null. I only see this response in my console:
com.sun.xml.ws.client.ClientTransportException: The server sent HTTP status code 401: Unauthorized
How do I get the body that is shown in the Postman request?
Some more context information:
The jax-ws service that makes requests to the blurred out endpoint
@WebServiceClient(
name = "LIReceiveMessageService",
targetNamespace = "http://uic.cc.org/UICMessage",
wsdlLocation = "src/main/java/nl/rls/ci/soapinterface/UICCCMessageProcessingInboundWS.wsdl"
)
public class LIReceiveMessageService
extends Service {
....
}
The messageResolver I added using this oracle guide.
LIReceiveMessageService service = new LIReceiveMessageService();
service.setHandlerResolver(new MyHandlerResolver());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61763119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Write to MySQL on mouseover After months of testing, I'm not succeeding to create a script that writes a logtext to the MySQL when a div gets a mouseover.
I think I have to use $.ajax, the only problem is, is that ajax (still) is the language which I'm not very good at.
One of the 100 things i've tried:
<?
echo "<div id='div0' rel=".$someid.">Some dynamic text</div>";
?>
<script>
$('.div0').mouseover(function() {
$('#result').load('../../../system/molog.php?cid='+$(this).attr('rel');
});
</script>
Who can help?
A: Ok, there's a much better way to do this, but since I'm on a phone that's dying and you have been waiting a year...
var info = $("#div0").html();
// if Js in a php file you can do var info = <?php echo $logtext ?>; To bring it to JS
$.get("phpfilehere.php", {info:info}, function(data){
alert(data);
});
The mouseover function...
$("#div0").on("mouseover", function(){
// my JS code above goes here
});
PHP file:
if(isset($_GET['info'])){
$log = $_GET['info'];
// Put ur stuff here, make sure u only echo when u want ur php script to stop and be sent back to Ajax function as data var.
// insert $log
echo "test";
} else {
echo "no get info supplied":
}
And here is a tool I made to teach people how to write prepared statements for SQL queries :) if you need it...
http://wbr.bz/QueryPro/index.php?query_type=prepared_insert
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49787278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Basic Javascript Variable Scoping So I'm trying to make an app that would return whether each of these twich users
["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]
is streaming. This is my code:
var users= ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var progress =0;
var streaming = [];
$(document).ready( function() {
console.log(window.progress);
while (window.progress<8) {
var url = 'https://api.twitch.tv/kraken/streams/' + window.users[window.progress] + '?callback=?';
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
if (data.stream) {
window.streaming[window.progress]="streaming";
}
//if closed
else {
window.streaming[window.progress]="not streaming";
};
//else closed
console.log(window.progress);
console.log(window.users[window.progress]);
var html = "<p> <a href=\" https://www.twitch.tv/"+window.users[window.progress] +" \" >"+window.users[window.progress]+ "</a> is currently " +window.streaming[window.progress] + "</p>";
$("body").append(html);
}});
// getjson closed
window.progress +=1;
};
// for loop closed
});
//document ready closed
and this is what I'm getting:
"undefined is currently streaming"
so it doesn't seem to pull the users. Thanks
A: Your streaming array isn't initialized, so this can't be done due there's no 0,1,... element on it
window.streaming[window.progress]="streaming"; //streaming.length == 0, streaming[0] == 'undefined'
maybe you would like to clone the users.length on it to have a index
streaming = []; // length == 0
streaming.length = users.length; // length == users.length
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37478688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to properly plot a ratio I am trying to plot a ratio but my problem is that when the dividend is larger than the divisor my quotient can be as high as possible. When the divisor is larger than the dividend the quotient is between 0 and 1. That is fine, but when I plot out the results the ratios with the larger dividend take up a huge portion of the plot and the smaller dividend ratios are limited to a much smaller area. Is there a way to show ratios on a plot (hopefully using base plots) where the dividend is five times greater than the divisor will take up the same amount of space as when the divisor is five times greater than the dividend.
Here is some sample data:
x=1:10
y=10:1
ratioxy=x/y
The data is:
x
[1] 1 2 3 4 5 6 7 8 9 10
y
[1] 10 9 8 7 6 5 4 3 2 1
ratioxy
[1] 0.1000000 0.2222222 0.3750000 0.5714286 0.8333333 1.2000000 1.7500000 2.6666667
[9] 4.5000000 10.0000000
When I do this:
plot(ratioxy,type='l',col='blue')
abline(h=1)
I get this:
All I can think of is somehow playing around with the quotients in ratioxy that are less than one, but nothing is coming to me right now.
A: Try using a logarithmic scale.
plot(ratioxy,type='l',col='blue')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9233784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting False with my Def, What is wrong with my code? def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(n, n+1):
if n % i ==0:
nb.append(i)
sum1 = sum(nb) - nb[-1]
if sum1 > n:
return True
else:
return False
n = int(input("n:"))
print(richNumber(n))
I have 5 Test Cases:
n = 4
n = 12
n = 6
n = 20
n = 100
With n = 4 and 6 the output is false ,with n = 12,20,100 is supposed to be true but its showing false.
This function used to get all divisor of n in a list, if the sum of all divisor of n (not N) is larger than N is true, smaller is False
A: for i in (n, n+1)
Iterates over two numbers, n and n + 1, not all divisors. You need to use range to iterate from 1 to n
for i in range(1, n + 1)
A: Your current richNumber function will always return False because sum1 will
always be 0. Try the following code:
def richNumber(n):
nb = []
n = int(n)
sum1 = 0
for i in range(1, n):
if n % i == 0:
nb.append(i)
sum1 = sum(nb)
if sum1 > n:
return True
else:
return False
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73762313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to make display to console text I am beginner at C# and I am trying like welcome message like as
Console.WriteLine(" Enter Your Name:");
Console.Write(new string(' ', Console.WindowWidth));
Console.Write("first name:");
string name = Console.ReadLine();
I need after entering the first name to clear the window and go for next output like:
Console.Write("last name:");
string lastname = Console.ReadLine();
How do I do this?
A: You can clear the console window with
Console.Clear()
If you put this in between your two blocks of code you should have what you need.
You can also make a blank line by doing
Console.Writeline();
Instead of
Console.Write(new string(' ', Console.WindowWidth));
A: Did you try this...
Console.WriteLine(" Enter Your Name:");
Console.WriteLine("first name:");
string firstName = Console.ReadLine();
Console.WriteLine("last name:");
string lastName = Console.ReadLine();
Please feel free to use Console.Clear() to clear the console.
You may further print/see the values using
Consile.WriteLine("Your First Name is " + firstName + " and last name is " + lastName);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32650108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Match and replace string in text using regular expressions I have a large string and it might have the following:
<div id="Specs" class="plinks">
<div id="Specs" class="plinks2">
<div id="Specs" class="sdfsf">
<div id="Specs" class="ANY-OTHER_NAME">
How can I replace values in the string from anything above to:
<div id="Specs" class="">
this is what I came up with, but it does not work:
string source = "bunch of text";
string regex = "<div id=\"Specs\" class=[\"']([^\"']*)[\"']>";
string regexReplaceTo = "<div id=\"Specs\" class=\"\">";
string output = Regex.Replace(source, regex, regexReplaceTo);
A: What about...
*
*Regex to match : class=\"[A-Za-z0-9_\-]+\"
*Replace with : class=\"\"
This way, we ignore the first part (id="Specs", etc) and
just replace the class name... with nothing.
A: Looks like another case of http://www.codinghorror.com/blog/2008/06/regular-expressions-now-you-have-two-problems.html. What happens to the following valid tags with a Regex?
<div class="reversed" id="Specs">
<div id="Specs" class="additionalSpaces" >
<div id="Specs" class="additionalAttributes" style="" >
I don't see a how using Linq2Xml wouldn't work with any combination:
XElement root = XElement.Parse(xml); // XDocument.Load(xmlFile).Root
var specsDivs = root.Descendants()
.Where(e => e.Name == "div"
&& e.Attributes.Any(a => a.Name == "id")
&& e.Attributes.First(a => a.Name == "id").Value == "Specs"
&& e.Attributes.Any(a => a.Name == "class"));
foreach(var div in specsDivs)
{
div.Attributes.First(a => a.Name == "class").value = string.Empty;
}
string newXml = root.ToString()
A: If your input isn't XML compliant, which most HTML isn't, then you can use the HTML Agility Pack to parse the HTML and manipulate the contents. With the HTML Agility PAck, combined with Linq or Xpath, the order of your attributes no longer matters (which it does when you use Regex) and the overall stability of your solution increases a lot.
Using the HTML Agility Pack (project page, nuget), this does the trick:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml("your html here");
// or doc.Load(stream);
var nodes = doc.DocumentNode.DescendantNodes("div").Where(div => div.Id == "Specs");
foreach (var node in nodes)
{
var classAttribute = node.Attributes["class"];
if (classAttribute != null)
{
classAttribute.Value = string.Empty;
}
}
var fixedText = doc.DocumentNode.OuterHtml;
//doc.Save(/* stream */);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9780470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Testing Exceptions in Nunit 3.0 and above I am trying to test an exception, NUnit 3.11 is giving me the error, and the unit test is failing. I want Nunit to green pass if it receives this exception, not error out. How would I resolve this?
Feel free to improve code if you want, just started learning programming few months ago.
When running it gives the exception itself, does not pass.
Test errors out- Message: System.ArgumentException : Too much data
public class ParseVendorSupply
{
public VendorSupply FromCsv(string csvLine)
{
string[] values = csvLine.Split(',');
if (values.Length > 3)
{
throw new System.ArgumentException("Too much data");
}
VendorSupply vendorsupply = new VendorSupply();
vendorsupply.VendorId = Convert.ToInt16(values[0]);
vendorsupply.ProductId = Convert.ToInt16(values[1]);
vendorsupply.Quantity = Convert.ToInt16(values[2]);
return vendorsupply;
}
}
Test:
public class ParseVendorSupplyNunit
{
ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply();
[Test]
public void FromCsv_ParseCorrectly_Extradata()
{
string csvLineTest = "5,8,3,9,5";
//VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
Assert.That(parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
}
A: You need to pass the method you are testing as an Action. You can then use the Assert.Throws<> method:
Assert.Throws<ArgumentException>(() => parseVendorSupplytest.FromCsv(csvLineTest));
There is also an async version if you are using async/await
Assert.ThrowsAsync<ArgumentException>(async () => await parseVendorSupplytest.FromCsv(csvLineTest));
A: The answers that suggest using an Action work, but the Action is not necessary for NUnit. I'm creating this one because I think it's important that you understand why your existing code doesn't work.
Problem is that the first argument of your assert calls the method before calling the assert. Your Assert.That never gets called since the exception is thrown while evaluating the argument.
Defining an Action avoids this problem because it specifies a method call that won't be made immediately.
However, a more colloquial way to specify this in NUnit is by using a lambda directly...
Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
A: Wrap method you are testing into an Action
Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
Assert.That(parseFromCsv, Throws.ArgumentException)
And when testing for common exceptions, such as ArgumentException, always test for exception message as well.
Because common exception can occur in some other places and test will pass for a wrong reason.
I prefer to use FluentAssertions, which I found little bid more readable.
Action parseFromCsv = () => parseVendorSupplytest.FromCsv(csvLineTest);
parseFromCsv.Should().Throw<ArgumentException>().WithMessage("Too much data");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53255946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Count number of records in lmdb databse with python I open a lmdb database using this code:
lmdb_env = lmdb.open(source_path, readonly=True)
How can I count the number of records in this database?
A: I think it should be like this:
lmdb_env = lmdb.open(lmdb_file_name, readonly=True)
print lmdb_env.stat()
Then it prints the directory that Jaco pasted here.
A: env = lmdb.open('db file path', max_dbs = ' > 0')
with env.begin() as tx:
db = env.open_db(b'db name', txn=tx)
print(env.stat())
print(tx.stat(db)) # this gives stats about one specific db
env.stat() gives entries of the main database. tx.stat(db) gives entries of one named database.
A: You can use event.stat(). It will return the following dictionary with entries detailing the number of records in this database:
{'branch_pages': 1040L,
'depth': 4L,
'entries': 3761848L,
'leaf_pages': 73658L,
'overflow_pages': 0L,
'psize': 4096L}
A: I found a simple solution using for loop. Here it is:
count = 0
for key, value in lmdb_env.cursor():
count = count + 1
However, I think there should be a better way using pre-defined function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34420375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Why am I getting Interceptor attempted to ‘Proceed’ for a method without a target error? In my case I have main project and test project. I was getting proper results on the test project where I have only one Installer class and register everything in one place. In my main project I had several installers (one for service, one for interceptors, one for common libraries, one for data persistence). For the main project I was getting the error specified:
This is a DynamicProxy2 error: the interceptor attempted to ‘Proceed’ for a method without a target, for example, an interface method or an abstract method
I was struggling to find out what was wrong. I plugged into my constructor that accepts interface of a data persistence layer and saw that it only receives a proxy object.
A: Also, see here: Manually Loading the Factory Extension into the Ninject Kernel
Under some circumstances it may be necessary to manually load the extension. The solution in my case was to add the following code during kernel construction:
if (!kernel.HasModule("Ninject.Extensions.Factory.FuncModule"))
{
kernel.Load(new FuncModule());
}
A: Why this was happening is specified here: http://kozmic.net/2009/03/20/castle-dynamic-proxy-tutorial-part-viii-interface-proxy-without-target/
Krzysztof explains that you Castle can resolve even an interface, and Windsor will create a class for you. However if you want to use an interceptor and call a invocation.Proceed() method you need to specify what happens inside that method (for ex. using lambda expression)
Solution:
In my case solution was to put all installers into one, except of the interceptor installer. That one could stay alone, and eveything was fine.
A: If you have this problem by Update method so change it like this :
var myObj = _dbContext.Set<T>().Find(entity.Id);
_dbContext.Entry(myObj).CurrentValues.SetValues(entity);
_dbContext.SaveChanges();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19000466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Generic class factory or method of hierarchy objects I have hierarchy class and generic class:
public class Form
{
public string Name { get; set; }
public string Producer { get; set; }
}
public class Book : Form
{
public string Topic { get; set; }
public string Autor { get; set; }
}
public class Copybook : Form
{
public string Topic { get; set; }
public int CountPages { get; set; }
}
public class Notebook : Form
{
public int Cost { get; set; }
}
public class Request<T> where T : Form
{
public T Form { get; set; }
}
I want to make factory or method, which will create objects of generic class in depend of logic and params. How it make? I tried to do this, but the code did not work:
public enum FormParams
{
Book,
Copybook,
Notebook
}
public static class RequestFactory
{
public static Request<Form> Create(FormParams formParams)
{
if (formParams == FormParams.Book)
{
return new Request<Book>();
}
if (formParams == FormParams.Copybook)
{
return new Request<Copybook>();
}
return new Request<Notebook>();
}
}
A: If you think carefully, what you're asking for doesn't really make sense. What if you did this?
var request = RequestFactory.Create(FormParams.CopyBook);
request.Form = new Book();
If the underlying type of request was Request<CopyBook>, then its Form property would have the type of CopyBook, and trying to set its value to a Book wouldn't make sense.
If you determine that the above use-case should never happen, you can formalize that fact by using an interface that doesn't allow the Form property to be set. Then you can make that interface covariant.
public class Request<T> : IRequest<T>
where T : Form
{
public T Form { get; set; }
}
public interface IRequest<out T> where T : Form
{
T Form { get; }
}
...
public static IRequest<Form> Create(FormParams formParams)
But in that case you may find there's no reason to have IRequest be generic at all.
public class Request<T> : IRequest
where T : Form
{
public T Form { get; set; }
Form IRequest.Form => this.Form;
}
public interface IRequest
{
Form Form { get; }
}
...
public static IRequest Create(FormParams formParams)
A: You need to add an Interface to your hierarchy so you can flag the generic parameter as covariant.
public class Request<T> : IRequest<T> where T : Form
{
public T Form { get; set; }
}
public interface IRequest<out T>
{
public T Form
{
get;
}
}
And then you need to change the return type of your Create method to an IRequest<Form>.
public static class RequestFactory
{
public static IRequest<Form> Create(FormParams formParams)
{
if (formParams == FormParams.Book)
{
return new Request<Book>();
}
if (formParams == FormParams.Copybook)
{
return new Request<Copybook>();
}
return new Request<Notebook>();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60103509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Varnish VCL "Symbol not found: std.querysort" I am copying some VCL rules from this handy template and running on the latest stable Varnish4. However this section of the VCL:
vcl 4.0;
sub vcl_init {
# ...
# Normalize query arguments
set req.url = std.querysort(req.url);
}
^
Returns this error:
-- Logs begin at Tue 2016-03-15 10:44:31 UTC, end at Tue 2016-03-15 13:02:10 UTC. --
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: Message from VCC-compiler:
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: Symbol not found: 'std.querysort' (expected type STRING_LIST):
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: ('/etc/varnish/test.vcl' Line 55 Pos 23)
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: set req.url = std.querysort(req.url);
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: ----------------------#############----------
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: Running VCC-compiler failed, exited with 2
Mar 15 13:02:10 ip-172-31-10-46 reload-vcl[18044]: VCL compilation failed
Should I include a mod or define std somehow?
A: Yes! I stumbled on the answer inside another answer. Adding import std; at the top of the script stopped the error.
vcl 4.0;
import std;
sub vcl_init {
# ...
# Normalize query arguments
set req.url = std.querysort(req.url);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36012266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Declare Variable Character Length My table is shown below:
Name
Depth
IsFile
GMES9604U 1.10 770 CFM-2135.csv
1
1
When I declare my variable, only part of the Name is stored:
declare @filename222 varchar(max)
SET @filename222 = CAST((
SELECT Top 1 Name
FROM #MyFiles
) AS Varchar)
print(@filename222)
Result Messages:
GMES9604U 1.10 770 CFM-2135.cs
I was wondering how can I get the entire Name as my variable. Thanks!
A: Why are you casing to a varchar? In SQL Server, you should never use string declarations without a length. But the explicit cast is unnecessary.
Just use:
SELECT Top 1 @filename222 = Name
FROM #MyFiles ;
The default length of varchar -- when used without a length -- depends on the context. You could use an explicit cast(), but you would use varchar(max).
A: What is the name column in your table defined as? Is it also VARCHAR(MAX) or is it defined as VARCHAR(<some number>)
If you already have the value in a table then the variable should be declared as the same data type and then you will never have a truncation issue.
Your issue is likely to be stemming from the fact that the default when no value is added for a VARCHAR declaration will be either 1 or 30 (see https://sqlblog.org/2009/10/09/bad-habits-to-kick-declaring-varchar-without-length)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66002193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Vue component Data not working in bootstrap modal I have a Vue Component which I reuse on the same page. I use a bootstrap 4 modal in the component. My problem is when I update the component data in the bootstrap modal, the data bind is not working properly when I reuse the same component in the view page.
Here is my component:
<template>
<div class="container-fluid" id="pageContent">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#test">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="test" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button @click="filterHistory">Add</button>
<button @click="closeFilter">Remove</button>
</div>
</div>
</div>
</div>
<!-- Headline -->
<h1>{{filter}}</h1>
</div>
</template>
<script>
export default {
name: "Table",
data() {
return {
filter: false
}
},
methods: {
filterHistory() {
this.filter = true
},
closeFilter() {
this.filter = false
},
}
}
</script>
And here I reuse it in a view page:
<template>
<div id="userInfo" v-bind:class="myval.theme">
<Test></Test>
<Test></Test>
</div>
</template>
The value of filter, which is a boolean expression, is only updated in the component declared first. So the data binding fails... Has anyone come across this? Or know how to resolve it?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68589220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.