text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: RTF to PDF format convert using java in linux I created a Java code to convert RTF format documents to PDF format. Program works properly in windows. But it gives error in linux. Can someone please show me the issue with this code ?
Java code:
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
public class Main {
public static void main(String[] args) {
File inputWord = new File("sample.rtf");
File outputFile = new File("sample.pdf");
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.RTF).to(outputStream).as(DocumentType.PDF).execute();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I used documents4j version 1.1.3 to implement this code.
Below error gives in linux environment:
ERROR com.documents4j.conversion.msoffice.MicrosoftWordBridge - Unable to run script: /tmp/1595252529799-0/word_start1195732765.vbs
org.zeroturnaround.exec.ProcessInitException: Could not execute [cmd, /S, /C, ""/tmp/1595252529799-0/word_start1195732765.vbs""] in /tmp/1595252529799-0. Error=2, No such file or directory
at org.zeroturnaround.exec.ProcessInitException.newInstance(ProcessInitException.java:80)
at org.zeroturnaround.exec.ProcessExecutor.invokeStart(ProcessExecutor.java:1002)
at org.zeroturnaround.exec.ProcessExecutor.startInternal(ProcessExecutor.java:970)
at org.zeroturnaround.exec.ProcessExecutor.execute(ProcessExecutor.java:906)
at com.documents4j.conversion.AbstractExternalConverter.runNoArgumentScript(AbstractExternalConverter.java:72)
at com.documents4j.conversion.msoffice.AbstractMicrosoftOfficeBridge.runNoArgumentScript(AbstractMicrosoftOfficeBridge.java:51)
at com.documents4j.conversion.msoffice.AbstractMicrosoftOfficeBridge.tryStart(AbstractMicrosoftOfficeBridge.java:34)
at com.documents4j.conversion.msoffice.MicrosoftWordBridge.startUp(MicrosoftWordBridge.java:46)
at com.documents4j.conversion.msoffice.MicrosoftWordBridge.<init>(MicrosoftWordBridge.java:41)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.documents4j.conversion.ExternalConverterDiscovery.make(ExternalConverterDiscovery.java:30)
at com.documents4j.conversion.ExternalConverterDiscovery.makeAll(ExternalConverterDiscovery.java:42)
at com.documents4j.conversion.ExternalConverterDiscovery.loadConfiguration(ExternalConverterDiscovery.java:85)
at com.documents4j.conversion.DefaultConversionManager.<init>(DefaultConversionManager.java:22)
at com.documents4j.job.LocalConverter.makeConversionManager(LocalConverter.java:79)
at com.documents4j.job.LocalConverter.<init>(LocalConverter.java:51)
at com.documents4j.job.LocalConverter$Builder.build(LocalConverter.java:186)
at Main.main(Main.java:13)
A: You are using a com.documents4j.LocalConverter object to perform the conversion. According to the documentation:
A LocalConverter can only be run if:
*
*The JVM is run on a MS Windows platform that ships with the Microsoft Scripting Host for VBS (this is true for all contemporary
versions of MS Windows.
*MS Word is installed in version 2007 or higher. PDF conversion is only supported when the PDF plugin is installed. The plugin is
included into MS Word from Word 2010 and higher.
*etcetera
Obviously, neither of these prerequisites can be met on a Linux machine.
Your options would appear to be:
*
*Use RemoteConverter to get a remote Windows machine to do the conversion.
*Look for alternative RTF to PDF converter that will run on Linux.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62997073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "From ubuntu" in docker container I am very new to Docker and confused with some things first of which is
FROM ubuntu:14.04
RUN apt-get update
RUN apt-get install -y curl nginx
above statement , does this statement mean we are installing ubuntu OS in a docker container which is already running on a OS e.g DC/OS in my case.
A: The statment FROM ubuntu:14.04 means use the ubuntu image as a base image.
The ubuntu image is not an OS. This image "mimics" an Ubuntu OS, in the sense that it has a very similar filesystem structure to an Ubuntu os and has many tools available that are typically found on Ubuntu.
The main and fundamental difference is that the Docker Ubuntu image does not have it own linux kernel. It uses the kernel of the host machine where the container is running.
Moreover, the size difference between the Docker image (73MB) and an Ubuntu iso(around 1Gb) is very significant.
A: It seems you have a misunderstanding of the docker concept.
What you are doing is pulling an image with the operating system of Ubuntu 14 and creating an instance of it (a container) that has nginx installed on it.
This does not make your os change it gives you a workspace not unlike a vm to run what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47977735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does an int variable change after being declared in a result of a statement as a double? Let us say you have 2 declared variables, each being an integer.
result = variable1 / variable2;
result is a double.
What would be the values of each of the variables after the previous statement executes? Let's say variable1 is 10 and variable2 is 6
A: You would get the result 10 / 6 = 1 (integer division). Then that result would be converted to a double and assigned to result. The variables would remain what they are, of course.
A: Nothing changes about variable1 and variable2. They remain ints and hold their values.
Also, because both the operands of the divison are ints, the integer division will take place.
The result of the integer division is (implicitly) converted to a double and stored into result.
A: variable1 will continue to be 10, and variable2 will continue to be 6. The only expressions that change variables are assignment and compound-assignment expressions (=, +=, etc., and as a special shorthand ++ for += 1 and -- for -= 1).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39398151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Mongodb collection update patterns I have a collection in db(e.g. merchants) which gets updated regularly in prod.
What we have is a db population script that we run every time.
This removes configuration collections and inserts them again based on data in script e.g. includes the update to a merchant config.
db.merchants.remove({});
db.merchants.insert(themerchant);
Is there a better pattern/procedure that people use to do this?
I cant seem to find guidance on how people are doing this in production. Links to methods people use would be great.
E.g. In SQL Server we create patches
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43278342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Should I use a single piece of code that works for all situations or multiple pieces of code that work for specific situations? I am working on a game that has Upgrades for the player, such as Health Regeneration and Max Health. In an Upgrades screen, for each upgrade, I list the name and level and have increase and decrease buttons to increase and decrease the level. Upgrades are bought with a currency called gems. 1 gem can increase the level of an upgrade by 1.
The requirements for increasing the level of a certain upgrade are that the number of gems the player has is greater than 0 and the upgrade's level is not equal to the max level.
The requirement for decreasing the level of a certain upgrade is that the upgrade's level is not 0.
When an upgrade level increase or decrease is available, I want the increase button or decrease button to be green. When it is not available, I want it to be red.
I have enable and disable functions for the increase and decrease buttons in the Upgrade class which turn the buttons green/red. The enable/disable functions can be called even if the button was already enabled or disabled, or if the button was not made yet (it only removes/adds the green button/red image if that action has not been done yet).
I do not know which strategy I should use for calling the button enabling/disabling functions. I will explain 2 strategies here.
Strategy 1
This is the strategy of using a single piece of code that works for all situations. Every time an upgrade button is pressed, or when the reset button is pressed, both buttons on all upgrades are checked and enabled or disabled depending on the conditions I mentioned above, regardless of whether doing certain checks were necessary or not.
Pros: easy to code, simple, and the code is all together.
Strategy 2
This is the strategy of writing multiple pieces of code that work for specific situations. Code that only applies to one upgrade would be written in the Upgrade class, not in the Main class. For example, when the level on a certain upgrade is increased, I would only check that one upgrade to see if it is maxed, and then check in the Main class if we have gems. If we didn't, all upgrade increase buttons would be disabled.
Pros: Buttons are checked only when they need to be checked.
At this point what I would choose to do is mostly Strategy 1, except I would use 2 functions instead of one. One function would be for when an upgrade is increased, and then I would check if upgrade increase buttons need to be disabled and if upgrade decrease buttons need to be enabled. The other function would be for the opposite scenario. Right now I am a little worried about each strategy. Strategy 1 seems like it requires more run time work than is necessary (it checks buttons that don't need to be checked), although the actual performance impact would be negligible. However, Strategy 2 seems like it requires much more coding work than is necessary. For example, when I press the reset button, Strategy 1 would handle it just fine with the same code, but in Strategy 2 I would have to explicitly enable all upgrade increase buttons and disable all upgrade decrease buttons, which seems unnatural. I would like to know what I should do: Strategy 1, Strategy 2, or my combination that I mentioned in the beginning of this paragraph?
A: The over-arching strategy (including in deciding when to apply either of your strategies needs) to be "Avoid coding the same thing multiple times". If you code something more than once, it is an opportunity to have several unintended variations (e.g. a set of errors in one version and not in another) and a maintenance burden (if you change one, it is necessary to go through all the other places where the same logic is coded, and update each).
Use strategy 1 to handle actions that - according to your design - are applicable to all situations.
Use strategy 2 to handle actions that - according to your design - are specific to only a few situations.
You can also combine the strategies, and collect meaningful sets of actions (meaningful in the sense that code which employs one action will probably need to employ other particular actions) at various points.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28389454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel queryBuilder (5.6) Hello I'm trying to replicate this SQL code into Laravel qBuilder but I'm not getting the result I want in the collection:
select chars.name, class.name, specs.name
FROM characters as chars
JOIN charclasses as class
JOIN charspecs as specs
WHERE chars.class_id = class.id
AND chars.spec_id = specs.id
I get the following output:
Then I tried this in Laravel:
$charData = DB::table('characters')
->select('characters.*', 'charclasses.name', 'charspecs.name')
->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
->orderBy('user_id', 'ASC')
->get();
dd($charData);
and the result is:
A: The problem is that you are selecting three fields with the same name. These fields are added to an array in the php code, but the array field is being overwritten twice because there can be no duplicate keys in an associative array. If you want to select the three names you will have to give them another name.
$charData = DB::table('characters')
->select('characters.*', 'charclasses.name as charclassname', 'charspecs.name as charspecname')
->join('charclasses', 'characters.class_id', '=', 'charclasses.id')
->join('charspecs', 'characters.spec_id', '=', 'charspecs.id')
->orderBy('user_id', 'ASC')
->get();
dd($charData);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51980698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I identify the exact lines within a diff patch that the hunk range is referring to? So I have a diff patch that I want to overlay on the original snippet of code line-by-line, but the issue I am having is matching the correct original line number with the lines within the diff patch.
For instance, say I have the following patch:
> @diff_lines
=> ["@@ -1827,7 +1827,7 @@ def has_and_belongs_to_many(name, scope = nil, **options, &extension)\n",
" \n",
" builder = Builder::HasAndBelongsToMany.new name, self, options\n",
" \n",
"- join_model = builder.through_model\n",
"+ join_model = ActiveSupport::Deprecation.silence { builder.through_model }\n",
" \n",
" const_set join_model.name, join_model\n",
" private_constant join_model.name\n"]
The line I need to look for in the original code is join_model = builder.through_model\n",.
Per the hunk range info, I looked at line 1830 (i.e. 1827 + 3) because typically 3 lines (before and after) the change are included in the patch.
However, if you count the lines from the top of the patch, including the first line, the newlines & the deleted line, there are 5 lines...but after the newline has been added, there are 4 lines including the newline added before the end of the patch.
So I haven't figured out a mathematical way to look within the patch and go directly to the lines that correspond to the hunk range info.
Or even more tricky is this diff, where the changes are space related and the hunk range doesn't seem to specify which lines each of the changes are at.
Here is the code snippet from that:
> d2.first.patch.lines
=> ["@@ -158,33 +158,33 @@ def synchronize(&block)\n",
" @lock.synchronize(&block)\n",
" end\n",
" \n",
"- # Test if the queue currently contains any elements.\n",
"+ # Test if the queue currently contains any elements.\n",
" def any?\n",
" !@queue.empty?\n",
" end\n",
" \n",
"- # A thread can remove an element from the queue without\n",
"- # waiting if and only if the number of currently available\n",
"- # connections is strictly greater than the number of waiting\n",
"- # threads.\n",
"+ # A thread can remove an element from the queue without\n",
"+ # waiting if and only if the number of currently available\n",
"+ # connections is strictly greater than the number of waiting\n",
"+ # threads.\n",
" def can_remove_no_wait?\n",
" @queue.size > @num_waiting\n",
" end\n",
" \n",
"- # Removes and returns the head of the queue if possible, or nil.\n",
"+ # Removes and returns the head of the queue if possible, or nil.\n",
" def remove\n",
" @queue.shift\n",
" end\n",
" \n",
"- # Remove and return the head the queue if the number of\n",
"- # available elements is strictly greater than the number of\n",
"- # threads currently waiting. Otherwise, return nil.\n",
"+ # Remove and return the head the queue if the number of\n",
"+ # available elements is strictly greater than the number of\n",
"+ # threads currently waiting. Otherwise, return nil.\n",
" def no_wait_poll\n",
" remove if can_remove_no_wait?\n",
" end\n",
" \n",
"- # Waits on the queue up to +timeout+ seconds, then removes and\n",
"- # returns the head of the queue.\n",
"+ # Waits on the queue up to +timeout+ seconds, then removes and\n",
"+ # returns the head of the queue.\n",
" def wait_poll(timeout)\n",
" @num_waiting += 1\n",
" \n",
"@@ -582,8 +582,8 @@ def num_waiting_in_queue # :nodoc:\n",
" end\n",
" \n",
" private\n",
"- #--\n",
"- # this is unfortunately not concurrent\n",
"+ #--\n",
"+ # this is unfortunately not concurrent\n",
" def bulk_make_new_connections(num_new_conns_needed)\n",
" num_new_conns_needed.times do\n",
" # try_to_checkout_new_connection will not exceed pool's @size limit\n",
"@@ -594,19 +594,19 @@ def bulk_make_new_connections(num_new_conns_needed)\n",
" end\n",
" end\n",
" \n",
"- #--\n",
"- # From the discussion on GitHub:\n",
"- # https://github.com/rails/rails/pull/14938#commitcomment-6601951\n",
"- # This hook-in method allows for easier monkey-patching fixes needed by\n",
"- # JRuby users that use Fibers.\n",
"+ #--\n",
"+ # From the discussion on GitHub:\n",
"+ # https://github.com/rails/rails/pull/14938#commitcomment-6601951\n",
"+ # This hook-in method allows for easier monkey-patching fixes needed by\n",
"+ # JRuby users that use Fibers.\n",
" def connection_cache_key(thread)\n",
" thread\n",
" end\n",
" \n",
"- # Take control of all existing connections so a \"group\" action such as\n",
"- # reload/disconnect can be performed safely. It is no longer enough to\n",
"- # wrap it in +synchronize+ because some pool's actions are allowed\n",
"- # to be performed outside of the main +synchronize+ block.\n",
"+ # Take control of all existing connections so a \"group\" action such as\n",
"+ # reload/disconnect can be performed safely. It is no longer enough to\n",
"+ # wrap it in +synchronize+ because some pool's actions are allowed\n",
"+ # to be performed outside of the main +synchronize+ block.\n",
" def with_exclusively_acquired_all_connections(raise_on_acquisition_timeout = true)\n",
" with_new_connections_blocked do\n",
" attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout)\n",
"@@ -658,8 +658,8 @@ def attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout =\n",
" end\n",
" end\n",
" \n",
"- #--\n",
"- # Must be called in a synchronize block.\n",
"+ #--\n",
"+ # Must be called in a synchronize block.\n",
" def checkout_for_exclusive_access(checkout_timeout)\n",
" checkout(checkout_timeout)\n",
" rescue ConnectionTimeoutError\n",
"@@ -690,17 +690,17 @@ def with_new_connections_blocked\n",
" synchronize { @new_cons_enabled = previous_value }\n",
" end\n",
" \n",
"- # Acquire a connection by one of 1) immediately removing one\n",
"- # from the queue of available connections, 2) creating a new\n",
"- # connection if the pool is not at capacity, 3) waiting on the\n",
"- # queue for a connection to become available.\n",
"- #\n",
"- # Raises:\n",
"- # - ActiveRecord::ConnectionTimeoutError if a connection could not be acquired\n",
"- #\n",
"- #--\n",
"- # Implementation detail: the connection returned by +acquire_connection+\n",
"- # will already be \"+connection.lease+ -ed\" to the current thread.\n",
"+ # Acquire a connection by one of 1) immediately removing one\n",
"+ # from the queue of available connections, 2) creating a new\n",
"+ # connection if the pool is not at capacity, 3) waiting on the\n",
"+ # queue for a connection to become available.\n",
"+ #\n",
"+ # Raises:\n",
"+ # - ActiveRecord::ConnectionTimeoutError if a connection could not be acquired\n",
"+ #\n",
"+ #--\n",
"+ # Implementation detail: the connection returned by +acquire_connection+\n",
"+ # will already be \"+connection.lease+ -ed\" to the current thread.\n",
" def acquire_connection(checkout_timeout)\n",
" # NOTE: we rely on +@available.poll+ and +try_to_checkout_new_connection+ to\n",
" # +conn.lease+ the returned connection (and to do this in a +synchronized+\n",
"@@ -716,8 +716,8 @@ def acquire_connection(checkout_timeout)\n",
" end\n",
" end\n",
" \n",
"- #--\n",
"- # if owner_thread param is omitted, this must be called in synchronize block\n",
"+ #--\n",
"+ # if owner_thread param is omitted, this must be called in synchronize block\n",
" def remove_connection_from_thread_cache(conn, owner_thread = conn.owner)\n",
" @thread_cached_conns.delete_pair(connection_cache_key(owner_thread), conn)\n",
" end\n",
"@@ -729,11 +729,11 @@ def new_connection\n",
" end\n",
" end\n",
" \n",
"- # If the pool is not at a +@size+ limit, establish new connection. Connecting\n",
"- # to the DB is done outside main synchronized section.\n",
"- #--\n",
"- # Implementation constraint: a newly established connection returned by this\n",
"- # method must be in the +.leased+ state.\n",
"+ # If the pool is not at a +@size+ limit, establish new connection. Connecting\n",
"+ # to the DB is done outside main synchronized section.\n",
"+ #--\n",
"+ # Implementation constraint: a newly established connection returned by this\n",
"+ # method must be in the +.leased+ state.\n",
" def try_to_checkout_new_connection\n",
" # first in synchronized section check if establishing new conns is allowed\n",
" # and increment @now_connecting, to prevent overstepping this pool's @size"]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42601625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: I have two ids for a project it's a tribute page the two ids are needed to pass but when i go to center the title it doesn't center I tried to center the title but it doesn't center i used css grid on images but shouldn't that not affect the id
this has not worked and I can't figure out why
#main{
text-align: center;
}
<div id="main">
<h1 id="title"> Dr.Norman Borlaug</h1>
</div>
but when I run it it shows the text should be centered but when i refresh the page on chrome it doesn't move to the center.
<div id="main">
<h1 id="title"> Dr.Norman Borlaug</h1>
</div>
<div id="img-div">
<div class="row">
<img src="img/normanwithpeople.png" alt="Norman Borlaug having a conversion with colleuges">
<img src="img/norman-borlaug.png" alt="Norman Borlaug in a field smiling" id ="image">
<p id="img-caption"></p>
</div>
<div class="column">
<img src="img/normanatconference.png" alt="Norman Borlaug at a confrence">
<img src="img/normanwithjimmy.png" alt="Norman_Borlaug with former President Jimmy Carter">
</div>
<div class="column">
<img src="img/norman.png" alt="Norman Borlaug and his wife">
<img src="img/normangetsaward.png" alt="Norman Borlaug receives an award from president George W Bush">
</div>
<div class="column">
<img src="img/normanwithgranddaughter.png" alt="Norman Borlaug with his granddaughter who is carrying his great grandchild">
<img src="img/normaninmexico.jpg" alt=" A painting of Norman Borlaug in a field in Mexico">
</div>
this the code before where the title is located but the rest is images i don't know how this helps.
A: Since you didn't include adequate code, I'm unable to guess what your issue is. Make sure you put CSS inside a <style> HTML tag, or inside a stylesheet, neither of which are visible inside your included code.
This seemed to work for me:
<!DOCTYPE html>
<html>
<head>
<style>
#main{text-align: center;}
</style>
</head>
<body>
<div id="main">
<h1 id="title"> Dr.Norman Borlaug</h1>
</div>
<div id="img-div">
<div class="row">
<img src="img/normanwithpeople.png" alt="Norman Borlaug having a conversion with colleuges">
<img src="img/norman-borlaug.png" alt="Norman Borlaug in a field smiling" id ="image">
<p id="img-caption"></p>
</div>
<div class="column">
<img src="img/normanatconference.png" alt="Norman Borlaug at a confrence">
<img src="img/normanwithjimmy.png" alt="Norman_Borlaug with former President Jimmy Carter">
</div>
<div class="column">
<img src="img/norman.png" alt="Norman Borlaug and his wife">
<img src="img/normangetsaward.png" alt="Norman Borlaug receives an award from president George W Bush">
</div>
<div class="column">
<img src="img/normanwithgranddaughter.png" alt="Norman Borlaug with his granddaughter who is carrying his great grandchild">
<img src="img/normaninmexico.jpg" alt=" A painting of Norman Borlaug in a field in Mexico">
</body>
</div>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65079145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Return first available row if initial SELECT finds nothing, in a single statement I am trying to put together a SQL query that will return data based on a simple WHERE condition but will also return the first available record if the condition is not met.
author_id
post_id
publish_date
1
31
2021-07-23
2
432
2021-06-22
2
555
2020-07-23
Using the data above my basic query would look like this
select *
from posts
where author_id = 1
and publish_date > '2021-07-01'
order by publish_date
Results, ie posts by the author published after a specified date
author_id
post_id
publish_date
1
31
2021-07-23
Since author 2 has no posts after this date I would like it to return the most recent post of the specified author.
I want to be able to output "<author> hasn't posted since <search_date>, the most recent post was on <publish_date>" without querying the database multiple times.
Desired result for author_id 2 (who doesn't have any posts where publish_date > '2021-07-01')
author_id
post_id
publish_date
2
432
2021-06-22
Is it possible to query for the first available record if the date condition is not met in a single statement?
A: You can create a function for this and get exactly what you want implementing conditions:
create or replace function some_func(input_author_id integer, input_date date)
returns setof posts
as
$$
declare
selected_posts posts%rowtype;
begin
select * from posts p into selected_posts where p.author_id = input_author_id and p.publish_date > input_date;
if not found then
return query
select * from posts p where p.author_id = input_author_id order by publish_date desc limit 1;
else
return query
select * from posts p where p.author_id = input_author_id and p.publish_date > input_date;
end if;
end
$$
language plpgsql;
After that, just pass the values of the parameters you want:
select * from some_func(2,'2021-07-01');
And this will give you the below result:
author_id
post_id
publish_date
2
432
2021-06-22
A: Possible with a single query:
WITH cte AS (
SELECT *
FROM posts
WHERE author_id = 1
AND publish_date > '2021-07-01'
ORDER BY publish_date
)
TABLE cte
UNION ALL
( -- parentheses required
SELECT *
FROM posts
WHERE NOT EXISTS (SELECT FROM cte)
AND author_id = 1
AND publish_date <= '2021-07-01'
ORDER BY publish_date DESC NULLS LAST
LIMIT 1
);
Related:
*
*Combining 3 SELECT statements to output 1 table
Or with a PL/pgSQL function:
CREATE OR REPLACE FUNCTION my_func(_author_id int, _publish_date date)
RETURNS SETOF posts
LANGUAGE plpgsql aS
$$
BEGIN
RETURN QUERY
SELECT *
FROM posts
WHERE author_id = _author_id
AND publish_date > _publish_date
ORDER BY publish_date;
IF NOT FOUND THEN
RETURN QUERY
SELECT *
FROM posts
WHERE author_id = _author_id
AND publish_date <= _publish_date
ORDER BY publish_date DESC NULLS LAST
LIMIT 1;
END IF;
END
$func$;
Call:
SELECT * FROM my_func(2,'2021-07-01');
Related:
*
*PLpgSQL function not returning matching titles
*How to return result of a SELECT inside a function in PostgreSQL?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68433597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make Visual Studio Code stop underlining names of imported jupyter files? I am using import_ipynb module in VS Code to use variables defined in another Jupyter notebook. However, when using the names of these files to import them, they become underlined with yellow color and with error messages: "Import "filename" could not be resolved". Everything seems to work fine, except for these underlines. Here is an example of how it goes:
import import_ipynb
import VsS_30
"VsS_30" is underlined with yellow.
Is there any way to solve this minor issue?
I have no clue on what to try in this matter, I don't have deep knowledge of visual studio code mechanics.
A: You can disable/suppress the warnings for imports as suggested in this answer: How to disable pylint warnings and messages on Visual Studio Code?
Use --disable=reportMissingImports to disable only this kind of warnings. You can find the list of Warnings here.
This comes with the downside that VS Code won't underline other packages (e.g. pandas) if it's not installed in the environment.
A: First, you have to check whether you have selected the correct interpreter.(Ctrl+Shift+P then type Python:Select Interpreter).
When you confirm that there is no problem, but there are still errors. If you want to disable the reminder, you can add the following codes to your settings.json:
"python.analysis.diagnosticSeverityOverrides": {
"reportMissingImports": "none"
},
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75581710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Grouping a data.frame and filtering based on several conditions I have a data.frame with several columns:
df <- data.frame(sgid = c("sg1","sg1","sg2","sg3"), stid = c(NA,"st1",NA,NA), spid = c(NA,NA,NA,"sp3"), sch = c("sch1","sch1","sch2","sch2"), sst = c(11,11,32,21), snd = c(21,21,46,34),
qgid = c("qg1","qg1","qg1","qg1"), qtid = c("qt1","qt1","qt1","qt1"), qpid = c("qp1","qp1","qp1","qp1"), qch = c("qch1","qch1","qch1","qch1"), qst = c(111,111,234,21), qnd = c(211,211,267,34))
This data.frame describes mapping one sequence (i.e. query) onto a database of other sequences (i.e. search).
Search and query sequences are identified by three sets of ids:
gid, tid, and pid (prefixed by s and q for search and query, respectively), and the coordinates of the matches are described by a string: ch and two integers: st and nd (again, prefixed by s and q for search and query, respectively).
tid and pid are subsets of gid in the case of the search, hence in the search database they are kept as separate rows. So, it is possible that the query will 'hit' both gid and either tid and/or pid in different coordinates.
However, as in the case of rows 1 and 2 in df, the query is hitting the search inside the tid and hence the search and query coordinates of rows 1 and 2 are identical.
So I'm looking for is a function (probably through dplyr::group and dplyr::filter) that will return a unique df based on the definition above.
This is my crude way of achieving this:
tmp.df <- df %>% dplyr::select(-stid,-spid) %>% unique()
uniq.df <- do.call(rbind,lapply(1:nrow(tmp.df),function(i){
tmp.df.i <- tmp.df[i,,drop=F] %>% dplyr::left_join(df)
if(!(all(is.na(tmp.df.i$stid) & is.na(tmp.df.i$spid)))){
tmp.df.i <- tmp.df.i[which(!is.na(tmp.df.i$stid) | !is.na(tmp.df.i$spid)),,drop=F]
} else{
tmp.df.i <- tmp.df.i %>%
dplyr::select(-stid,-spid) %>%
dplyr::mutate(stid=NA,spid=NA)
}
return(tmp.df.i)
}))
#organize the columns of uniq.df to the order of df:
uniq.df <- uniq.df %>% dplyr::select_(.dots = colnames(df))
> uniq.df
sgid stid spid sch sst snd qgid qtid qpid qch qst qnd
2 sg1 st1 <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211
1 sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267
11 sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34
Looking for something more elegant.
A: data.table solution
sample data
# sgid stid spid sch sst snd qgid qtid qpid qch qst qnd
# 1: sg1 <NA> <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211
# 2: sg1 st1 <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211
# 3: sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267
# 4: sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34
code
library( data.table )
setDT( df )
#get columns you wish to exclude from duplication-check
cols <- c( "stid", "spid" )
#keep non-duplicated rows, based on a subset of df (without the columns in `cols`)
df[ !duplicated( df[, !..cols] ), ][]
# sgid stid spid sch sst snd qgid qtid qpid qch qst qnd
# 1: sg1 <NA> <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211
# 2: sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267
# 3: sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34
alternative
if you do not wish to keep the first row of a duplicate, but the last, use:
df[ !duplicated( df[, !..cols], fromLast = TRUE ), ][] #<-- note fromlast-argument!
# sgid stid spid sch sst snd qgid qtid qpid qch qst qnd
# 1: sg1 st1 <NA> sch1 11 21 qg1 qt1 qp1 qch1 111 211
# 2: sg2 <NA> <NA> sch2 32 46 qg1 qt1 qp1 qch1 234 267
# 3: sg3 <NA> sp3 sch2 21 34 qg1 qt1 qp1 qch1 21 34
A: How about something like this with dplyr:
cols <- setdiff(names(df), c("stid", "spid"))
df %>% group_by_at(cols) %>%
summarise(stid = ifelse(length(unique(stid)) == 1,
unique(stid),
unique(stid)[! is.na(unique(stid))]),
spid = ifelse(length(unique(spid)) == 1,
unique(spid),
unique(spid)[! is.na(unique(spid))]))
Or you can use the function Coalesce from the package DescTools (or even define you own function to select the first non NA value):
df %>% group_by_at(cols) %>%
summarise(stid = DescTools::Coalesce(stid),
spid = DescTools::Coalesce(spid))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54512851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Erro A secret key is required to use CSRF. Python/Flask I am getting the error A secret key is required to use CSRF., In my production environment, when I am in the development environment my application normally.
The message is direct and says what is needed, except that I already have a SECRET_KEY defined.
def __create_env(env_file: str):
if not os.path.isfile(env_file):
context = "FLASK_ENV=production" + "\n"
context += "ENV=production" + "\n"
context += "SERVER_NAME=127.0.0.1:8080" + "\n"
context += "DEBUG=False" + "\n"
context += "TESTING=False" + "\n"
context += "PROPAGATE_EXCEPTIONS=False" + "\n"
context += "SECRET_KEY=my SECRET KEY"+ "\n"
context += "JWT_SECRET_KEY=....." + "\n"
with open(env_file, "w") as reader:
reader.write(context)
My __init__.py looks like this:
from flask import (Flask, jsonify, make_response, request)
from flask_jwt_extended import JWTManager
from flask_minify import minify
from flask_wtf import CSRFProtect
from src import (autenticacao, config, util)
from src.views import (vw_estatistica)
app = Flask(__name__)
csrf = CSRFProtect(app)
app.url_map.strict_slashes = False
app.jinja_env.lstrip_blocks = True
app.jinja_env.trim_blocks = True
app.jinja_env.cache = {}
app.config['SESSION_COOKIE_DOMAIN'] = '...com.br'
app.config['SESSION_COOKIE_SECURE'] = True
cache.init_app(app=app, config={
"CACHE_TYPE": "simple",
"CACHE_DEFAULT_TIMEOUT": 300
})
minify(app=app, html=True, js=False, cssless=False)
jwt = JWTManager(app)
vw_estatistica.configure(app)
csrf.init_app(app)
The error I'm getting is:
Traceback (most recent call last): File
"/var/www/.../principal/src/views/vw_estatistica.py", line 25, in
loginestatistica form = estatistica_model.LoginEstatisticaForm() File
"/usr/local/lib/python3.8/site-packages/wtforms/form.py", line 208, in
call return type.call(cls, *args, **kwargs) File
"/usr/local/lib/python3.8/site-packages/flask_wtf/form.py", line 87,
in init super(FlaskForm, self).init(formdata=formdata, **kwargs) File
"/usr/local/lib/python3.8/site-packages/wtforms/form.py", line 274, in
init self.process(formdata, obj, data=data, **kwargs) File
"/usr/local/lib/python3.8/site-packages/wtforms/form.py", line 131, in
process field.process(formdata) File
"/usr/local/lib/python3.8/site-packages/wtforms/csrf/core.py", line
43, in process self.current_token =
self.csrf_impl.generate_csrf_token(self) File
"/usr/local/lib/python3.8/site-packages/flask_wtf/csrf.py", line 139,
in generate_csrf_token return generate_csrf( File
"/usr/local/lib/python3.8/site-packages/flask_wtf/csrf.py", line 33,
in generate_csrf secret_key = _get_config( File
"/usr/local/lib/python3.8/site-packages/flask_wtf/csrf.py", line 128,
in _get_config raise RuntimeError(message) RuntimeError: A secret key
is required to use CSRF.
The vw_estatistica.py ", line 25, in loginestatistica form = estatistica_model.LoginEstatisticaForm () is as follows.
import json
import traceback
import flask
from flask import Blueprint, jsonify, render_template, redirect, abort, url_for, flash, request
from flask_restful import Api, Resource
from datetime import timedelta, datetime
from src import util, config
from src.models import (log_model, estatistica_model, menu_model)
mod: Blueprint = Blueprint('vw_estatisitca', __name__, template_folder='templates', static_folder='static')
def configure(app):
api = Api(mod)
api.add_resource(ObterTopoEstatistica, '/obterTopoEstatistica', '/obterTopoEstatistica/<string:pagina>')
app.register_blueprint(mod)
@mod.route("/estatistica/login", methods=["GET", "POST"])
def loginestatistica():
try:
form = estatistica_model.LoginEstatisticaForm() # line 25
if request.method == 'POST' and form.validate():
senha_cript = util.encrypt(form.password.data, config.CHAVE_CRIPTOGRAFIA)
usuario_estatistica = estatistica_model.get_usuario_estatistica(form.login.data, senha_cript)
if usuario_estatistica is not None:
response = flask.make_response(redirect('https://estatistica....com.br'))
data_expiracao = (datetime.now() + timedelta(days=1))
id_usuario = util.encrypt(str(usuario_estatistica.id), config.CHAVE_CRIPTOGRAFIA)
json_usuario_estatistica = json.dumps({'IdUsuario': id_usuario,
'NomeUsuario': usuario_estatistica.Usuario,
'DataUltimoAcesso': usuario_estatistica.UltimoAcesso}
, indent=4, sort_keys=True, default=str)
response.set_cookie(value=json_usuario_estatistica,
key='estatistica',
max_age=None,
expires=data_expiracao,
path='/',
domain='....com.br',
secure=True,
httponly=False,
samesite='Lax')
return response
else:
flash("Credênciais incorretas", "danger")
return redirect(url_for(".loginestatistica"))
menus: list = menu_model.get_menu(request.host_url)
return render_template("login-estatistica.html",
form=form,
menus=menus
)
except Exception as error:
log_model.Salvar('Site www', 'vw_estatistica.py', f'{traceback.format_exc()}', 'estatistica',
log_model.Severidade.High)
abort(502, description=error)
finally:
pass
And my HTML page looks like this.
{% extends "layout.html" %}
{%- block dataLayer -%}
{{ dataLayer | safe }}
{%- endblock -%}
{% block content %}
<div class="container-fluid">
<br />
<form action=" {{url_for('.loginestatistica')}}" method="POST">
{{ form.csrf_token }}
<div class="row justify-content-center">
<div class="col-md-4">
<div class="modal-content">
<div class="modal-header text-center">
<h1 class=" text-primary text-block h2 font-weight-bold mb-0">Kalunga - Estatística</h1>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text font-weight-bold"><i
class="fas fa-user mr-1"></i>Login</span>
</div>
{{ form.login(class_="form-control") }}
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text font-weight-bold"><i
class="fas fa-key mr-1"></i>Senha</span>
</div>
{{ form.password(class_="form-control") }}
</div>
<div class="input-group mb-12">
<div class="col-md-4">
<button type="submit" class="btn btn-primary btn-lg">Login</button>
</div>
<div class="col-md-6 text-center">
<a href="{{url_for('.recuperaracessoestatistica')}}">Recupera acesso</a>
</div>
</div>
<div class="input-group mb-12">
{% include 'partials/notification.html' %}
{% include 'partials/form-erros.html' %}
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<br />
{% endblock %}
I've seen some issues related to the error like this, but I couldn't find the problem, I also tried to follow the steps in the documentation and it didn't work.
A: Define the secret_key like
app = Flask(__name__)
app.secret_key = settings.SECRET_KEY
or
app.config['SECRET_KEY'] = settings.SECRET_KEY
Look for details here https://flask.palletsprojects.com/en/1.1.x/config
You should load environment for flask app manually as specified here https://flask.palletsprojects.com/en/1.1.x/api/#configuration
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65393359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ActionController::Metal How to catch all exceptions to send notification email? I am using ActionController::Metal inherted controllers for for rails services, I want to catch all exceptions , So that I can notify myself through email
rescue_from Exception is not working
I have used above code in another app in application controller it is working good But not in this case
Which module should be included in to base controller in order to use it any help?
Code:
rescue_from Exception do |exception|
Rails.logger.warn "\n-EXCEPTION OCCURE IN APPLICATION-\n============\n-On\n-#{Time.now}\n======\nRequest-refer\n#{request.referer}\n=====\nrequest.xhr?\n#{request.xhr?}\n=======\nRequest environment\n#{request.env["HTTP_USER_AGENT"]}\n====\n-MESSAGE\n-#{exception.message}\n======\n-Url\n-#{request.url} \n============\n-Backtrace\n-#{exception.backtrace}"
end
A: I'm not sure if this speaks to your exact problem, or whether you really need to create this yourself, but if you're open to additional dependencies I use the exception_notifier gem for this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41369290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to allow user to change password in BrowserCMS? I have generated normal reset password portlet for non-admin users and inserted it to the page, but it seems not to be working. It just does nothing while submitted.
The code of portlet is the standard:
<% if flash_scope = flash[:reset_password] -%>
<% if flash_scope[:error] -%>
<span class="reset-password-error"><%= flash_scope[:error] %></span>
<% end -%>
<% if flash_scope[:notice] -%>
<span class="reset-password-notice"><%= flash_scope[:notice] %></span>
<% end -%>
<% end -%>
<%= form_tag '' do %>
<% if params[:token] -%>
<%= hidden_field_tag "token", params[:token] %>
<% end -%>
<label for="password">New Password:</label>
<%= password_field_tag "password" %><br>
<label for="password_confirmation">Confirm New Password:</label>
<%= password_field_tag "password_confirmation" %><br>
<%= submit_tag "Reset Password" %>
<% end %>
Am I missing something?
A: Thank you thisfeller for push to the right direction!
The problem was that the default password change portlet is mentioned to be used only with password reset portlet that sends email to user etc. So I wrote my own portlet based on that reset password portlet but removed the finding of wanted user by token and instead just check who is logged in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15571488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Odd behaviour for Tkinter Canvas STATE with time.sleep I have a Canvas called _their_grid, which has many associated events tied to mouse clicks. I am disabling it upon a certain condition for 10 seconds. Below is the relevant code.
print "not your turn"
# disable opponent's grid during their turn
self._their_grid.config(state=DISABLED)
time.sleep(10)
self._their_grid.config(state=NORMAL)
print "now you can go"
However, during the ten-second sleep, I still manage to trigger the events. This should not be the case, as state=DISABLED should shut off all the events. The code below, with sleep commented out, stops all events.
print "not your turn"
# disable opponent's grid during their turn
self._their_grid.config(state=DISABLED)
#time.sleep(10)
#self._their_grid.config(state=NORMAL)
#print "now you can go"
Why do I get this odd behaviour with time.sleep?
A: time.sleep() doesn't prevent events from being accepted, it simply prevents them from being processed. Every time you click while your app is sleeping the events are simply added to the queue, and processed when the sleep is done sleeping.
You should almost never call sleep in a GUI. What you should do instead is set the state to disabled, then schedule resetting the state for ten seconds later:
def re_enable(self):
self._their_grid.config(state=NORMAL)
...
self.after(10000, self.re_enable)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15180140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Unable to set Application.ScreenUpdating to false I have some VBA code as follows:
Sub copyData(fromRange as Range, toRange as Range)
Application.ScreenUpdating = False
<copy paste code here>
Application.ScreenUpdating = True
End Sub
Even though I am setting Application.ScreenUpdating to False, it remains at True. I have verified this using F8 and hovering over Application.ScreenUpdating (it shows True).
My copy paste code works. It switches worksheets but since ScreenUpdating remains at True, I can see the screen flicker.
Is there a way to set Application.ScreenUpdating to False?
P.S. I saw a similar question in this forum but there was no concrete resolution to it.
Any help will be greatly appreciated!
A: I've had the same issue for quite a while, and I figured out something: Application.screenUpdating only stays FALSE for how ever long a macro runs. When any macro running stops, it turns True. You can try this:
Sub testApplicationScreenUpdating()
Application.ScreenUpdating = False
Debug.Print "Application screen updating is:" & Application.ScreenUpdating
Application.ScreenUpdating = True
End Sub
*
*if you just run this, it will return in the Immediate window: "Application screen updating is:False"
*if you run it step by step, and hover over Applicaiton.ScreenUpdating with your mouse, it will show as "True", even if the Immediate window will show "False".
*if you comment out the [Application.ScreenUpdating = True] at the end, and then run [Debug.Print "Application screen updating is:" & Application.ScreenUpdating] separately, it will return true, even if it was not switched to true.
A: Try this code and see the values for each in the Immediate Window Ctrl+G:
Sub copyData()
Dim r As Boolean
r = Application.ScreenUpdating = False
Debug.Print "'Application.ScreenUpdating' is set to " & r
r = Application.ScreenUpdating = True
Debug.Print "'Application.ScreenUpdating' is set to " & r
End Sub
A: I use Excel as part of Microsoft 365. I too fought with the screen flickering problem. Although my macro worked, the flickering was very annoying. I tried several approaches and stumbled upon this:
Minimize the second workbook before initiating the macro from the first workbook. For my situation, the screen no longer flickered. I also tried the following code to minimize the second workbook from within VBA. If the second workbook was already minimized, there was no effect. If the second workbook was not minimized, the screen flickered only once - to enable me to minimize the second workbook. Subsequent switching back and forth between workbooks did not introduce any screen flickering.
‘
Filename = "SecondWorkbookName.xlsx"
Windows(Filename).Activate
Application.WindowState = xlMinimized ' Minimize workbook to prevent flickering.
Application.ScreenUpdating = False
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38896046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I load content in specific DIV after the page loads? I am wondering how I would load another PHP page into a DIV container after the parent page has loaded. I need to design facebook/twitter share links that will show people my page with certain content loaded into a DIV.
I have a function working for clicking links, but I need it to work on page load rather than click (#results is the ID of the DIV I need content loaded into):
$(".Display a").click(function() {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
return false;
});
A: You can use jQuery's .ready() event on the document:
$(document).ready(function () {
// Whatever you want to run
});
This will run as soon as the DOM is ready.
If you need your javascript to run after everything is loaded (including images) than use the .load() event instead:
$(window).load(function () {
// Whatever you want to run
});
A: I'd suggest keeping your original click-handler, and triggering it with:
$(".Display a").click(function() {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
return false;
});
$(document).ready(
function(){
$('.Display a').trigger('click');
});
A: Have you tried just using the $.ajax() outside of the click event?
Instead of --
$(".Display a").click(function() {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
return false;
});
Try this --
$(document).ready(function () {
$.ajax({
url: $(this).attr("href"),
success: function(msg){
$("#results").html(msg);
}
});
});
A: $(function(){ //jQuery dom ready event
$(".Display a").click(function() {
///you code
}).click(); //trigger it at the page load
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4708999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ObservableCollection populated by thread from ThreadPool This is my approach to add items to ObservableCollection in a separate thread taken from ThreadPool.
As we know it will raise exception:
This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.
I know that this subject is quite popular here but I haven't found any solution that suits the situation described in the code below:
namespace WpfApplication1
{
class Item
{
public string name
{
get;
set;
}
}
class Container
{
public ObservableCollection<Item> internalList = new ObservableCollection<Item>();
}
public partial class MainWindow : Window
{
Container container = new Container();
void addItems()
{
Item item = new Item() { name = "jack" };
container.internalList.Add(item);
}
public MainWindow()
{
InitializeComponent();
ThreadPool.QueueUserWorkItem(delegate { this.addItems(); });
MyDataGrid.ItemsSource = container.internalList;
}
}
}
What is the best solution for this problem here?
Thank you!
A: Replace
container.internalList.Add(item);
by
Dispatcher.BeginInvoke(new Action(() => container.internalList.Add(item)));
This way the Add is executed on the Dispatcher thread.
A: You can just get your data from a background thread as a List and then cast this list to an ObservableCollection as follows
List<SomeViewModel> someViewModelList = await GetYourDataAsListAsync();
ObservableCollection<SomeViewModel> Resources = new TypedListObservableCollection<SomeViewModel>(someViewModelList);
I hope this helps.
A: Make sure that you set the properties of UI objects on the UI thread:
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate()
{
MyDataGrid.ItemsSource = container.internalList;
});
This will add the code within the curly braces onto the work items queue of the UI thread Dispatcher.
A: The problem is not in the Collection on your class but in the Control that is binding to this collection from UI Thread.
There is something new in WPF 4.5:
http://www.jonathanantoine.com/2011/09/24/wpf-4-5-part-7-accessing-collections-on-non-ui-threads/
//Creates the lock object somewhere
private static object _lock = new object();
//Enable the cross acces to this collection elsewhere
BindingOperations.EnableCollectionSynchronization(_persons, _lock);
MSDN:
http://msdn.microsoft.com/en-us/library/hh198845(v=vs.110).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18696629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Driver doesn't return proper page source I'm trying to load one web page. Then scroll to the very bottom of this page (there is an infinite scroll) and get a page source code.
Scrolling and loading seems to work correct but driver.page_source returns very short html which is just a little part of the whole page source.
def scroll_to_the_bottom(driver):
old_html = ''
new_html = driver.page_source
while old_html != new_html:
print 'SCROLL'
old_html = driver.page_source
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
new_html = driver.page_source
driver.get("http://www.citypaper.com/music/short-list/bcpnews-the-short-list-weird-al-the-heartless-bastards-chastity-belt-more-20150609-story.html")
scroll_to_the_bottom(driver)
print driver.page_source
CONSOLE:
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" lang="en-US" data-role="base navhead resizescroll imgsize metrics oopadloader socialshare panelmod transporter"><head><script type="text/javascript" async="" src="//ml314.com/tag.aspx?2972015"></script><script type="text/javascript" async="" src="//ml314.com/tag.aspx?2972015"></script><script async="" src="http://b.scorecardresearch.com/beacon.js"></script><script async="" src="//www.google-analytics.com/analytics.js"></script><script type="text/javascript" src="http://beacon.krxd.net/optout_check?callback=Krux.ns._default.kxjsonp_optOutCheck"></script><script charset="UTF-8" type="text/javascript" src="http://cdn.taboola.com/libtrc/impl.174-RELEASE.js"></script><script async="" src="//widget.perfectmarket.com/tribunedigital-network/load.js"></script><script async="" src="http://b.scorecardresearch.com/beacon.js"></script>
<title>Music Boxes - Baltimore City Paper</title>
<link rel="dns-prefetch" href="//www.trbimg.com" /><link rel="dns-prefetch" href="//static.chartbeat.com" /><link rel="dns-prefetch" href="//loggingservices.tribune.com" /><link rel="dns-prefetch" href="//m.trb.com" /><link rel="dns-prefetch" href="//b.scorecardresearch.com" /><link rel="dns-prefetch" href="//www.google-analytics.com" /><link rel="dns-prefetch" href="http://pubads.g.doubleclick.net" /><link rel="dns-prefetch" href="https://securepubads.g.doubleclick.net" /><link rel="dns-prefetch" href="//secure-us.imrworldwide.com" /><link rel="dns-prefetch" href="//www.googletagservices.com" /><link rel="dns-prefetch" href="http://ssor.tribdss.com" /><link rel="dns-prefetch" href="//cdn.krxd.net" /><link rel="dns-prefetch" href="//cdn.gigya.com" /><link rel="dns-prefetch" href="//cdn.taboola.com" /><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no" />
<meta charset="utf-8" />
<meta name="x-servername" content="i10latisrapp02" />
<meta name="robots" content="noodp, noydir" />
I use chromedriver so I can clearly see that it scrolls to the bottom. Where could be the problem please?
EDIT:
I've added a web page scraped.
A: You cannot rely on page_source to get the current state of the page. The Python docs do not point it out but if you look at the Java docs of Selenium for getPageSource you'll see:
If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page.
What you can do is ask the browser to serialize the DOM. This will produce HTML that represents the DOM at the time you make the call:
driver.execute_script("return document.documentElement.outerHTML")
A: I had similar problem. I used time.sleep(5) after get.page_source so that the contents can be read.
A: Are you aware that the page content loads/unloads as you scroll down? The page is unloading previous sections as you scroll down. For instance, scroll all the way down to the bottom of the page and start scrolling back up. You will see that it's loading previous sections.
To prove this... when you first load the page, the first article title is, "The Short List: Weird Al, the Heartless Bastards, Chastity Belt, more". Scroll to the bottom of the page, pull the HTML source (manually), and search for that title. It's not there.
So, I don't know what you are trying to do but if all you want to do is to load the last section you can navigate directly to the last section using the URL, http://www.citypaper.com/music/music-boxes/
The different sections are:
Main article
http://www.citypaper.com/music/music-features/
http://www.citypaper.com/music/listening-party/
http://www.citypaper.com/music/music-boxes/
Why are you wanting the HTML source of the page anyway? What are you trying to accomplish? One of the main points of using Selenium is so you can find HTML tags using locators so you don't have to parse source, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32285070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to write a shell script counting all lines in all files in a given folder? I have a somewhat complicated task at hand, and - I have to admit to my shame - am not very skilled at all with shell scripting or the linux terminal in general, as I tend to just work in R.
So, what I want to do is to have write a shell script that does the following things, in chronological order:
1: ascertain today's date the following format YYYY-MM-DD and store it as a local variable or some equivalent. I tried the following:
todays-date=$(date '+%F')
2: move to the correct directory in which the data to be counted is located - this directory is the same as todays-date, and is all within the same parent directory structure. So, first of all, I do this:
cd /home/user/docs/parent/data
Then, I encounter my first issue when I try to access the directory with today's data:
cd echo $todays-date
This gives me an error, along the lines of 'no such file or directory'. So yeah, this is problem number 1.
3: Now I want the script to count all the lines in all the files located in this directory (let's assume I was able to access it). There should be 24 json files in this folder.
wc -l *
This works great. Now I'd like to save this information into a text file that is saved into my current working directory and named as follows: 'todays-date'_wordcount.txt, so something like 2015-11-10_wordcount.txt. I'm afraid I really don't know how to do this either.
The reason I want the date in there as a variable and not just written out is that I intend to run this shell script as a cron job once every day, as I have set up an automated data collection script and this shell script is there to count how many data were collected in the last iteration. It would be awesome if you guys could help me out! Thanks a lot in advance.
A: A dash is not a valid character in variable name. Use underscore instead.
todays_date=$(date '+%F')
You can use the variable directly with cd, no echo needed:
cd "$todays_date"
To save the output of a command to a file, use redirection:
wc -l * > ~/"$todays_date"_wordcount.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33706445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Applying operations on groups without aggregating I want to apply an operation on multiple groups of a data frame and then fill all values of that group by the result. Lets take mean and np.cumsum as an example and the following dataframe:
df=pd.DataFrame({"a":[1,3,2,4],"b":[1,1,2,2]})
which looks like this
a b
0 1 1
1 3 1
2 2 2
3 4 2
Now I want to group the dataframe by b, then take the mean of a in each group, then apply np.cumsum to the means, and then replace all values of a by the (group dependent) result.
For the first three steps, I would start like this
df.groupby("b").mean().apply(np.cumsum)
which gives
a
b
1 2
2 5
But what I want to get is
a b
0 2 1
1 2 1
2 5 2
3 5 2
Any ideas how this can be solved in a nice way?
A: You can use map by Series:
df1 = df.groupby("b").mean().cumsum()
print (df1)
a
b
1 2
2 5
df['a'] = df['b'].map(df1['a'])
print (df)
a b
0 2 1
1 2 1
2 5 2
3 5 2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45151072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to call Delphi method with variable number of arguments from IActiveScript? I'm using Delphi 2006 and psvActiveScript.
Example:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls,
ObjComAuto, ComObj, psvActiveScript;
type
TForm1 = class(TForm)
btnExecute: TButton;
procedure btnExecuteClick(Sender: TObject);
procedure ASWError(Sender: TObject; Line, Pos: Integer; ASrc, ADescription: String);
end;
var
Form1: TForm1;
ASW: TpsvActiveScriptWindow;
implementation
{$R *.DFM}
type
{$METHODINFO ON}
TMySriptableClass = class(TObjectDispatch)
public
constructor Create;
procedure Alert(msg: string);
// THIS OR SOMETHING SIMILAR NOT POSSIBLE? **********************
function FnWithVarNumOfArgs(const args: array of string): string;
// **************************************************************
end;
{$METHODINFO OFF}
constructor TMySriptableClass.Create;
begin inherited Create(Self, False); end;
procedure TMySriptableClass.Alert(msg: string);
begin ShowMessage(msg); end;
function TMySriptableClass.FnWithVarNumOfArgs(const args: array of string): string;
begin Result := 'OK'; end;
procedure TForm1.btnExecuteClick(Sender: TObject);
var
MyObj: TMySriptableClass;
begin
ASW := TpsvActiveScriptWindow.Create(self);
ASW.ScriptLanguage := 'JScript';
ASW.OnError := ASWError;
MyObj := TMySriptableClass.Create;
ASW.AddNamedItem('MyObj', MyObj);
try
ASW.Execute(
'MyObj.Alert("Warning: Here comes Error");'+
'MyObj.FnWithVarNumOfArgs("1","2","3")'
);
finally
ASW.Free;
end;
end;
procedure TForm1.ASWError(Sender: TObject; Line, Pos: Integer; ASrc, ADescription: String);
begin Showmessage(ADescription + ': ' + ASrc); end;
end.
A: [...]
uses
activex, objcomauto, comobj;
type
{$METHODINFO ON}
TMySriptableClass = class(TObjectDispatch)
public
[...]
function FnWithVarNumOfArgs(const args: OleVariant): string;
[...]
function TMySriptableClass.FnWithVarNumOfArgs(const args: OleVariant): string;
var
dispParams: activex.DISPPARAMS;
vtRet, Element: OleVariant;
Enum: IEnumVARIANT;
Fetched: LongWord;
begin
if TVarData(args).VType = varDispatch then begin
OleCheck(IDispatch(args).Invoke(DISPID_NEWENUM, GUID_NULL,
LOCALE_USER_DEFAULT, DISPATCH_PROPERTYGET,
dispParams, @vtRet, nil, nil));
Enum := IUnknown(vtRet) as IEnumVARIANT;
while (Enum.Next(1, Element, Fetched) = S_OK) do
ShowMessage(Element);
end;
Result := 'OK';
end;
[...]
ASW.Execute('var myArray=["myarg1", 5, true];' +
'MyObj.FnWithVarNumOfArgs(myArray);');
[...]
A: The way you have set it up now, you would need to pass in an array of string since you declared the parameter as such. In Delphi itself that could be done using
MyObj.FnWithVarNumOfArgs(Array("1","2","3"))
Which would create a dynamic arry with the given values and then pass it to FnWithVarNumOfArgs.
From a scripting language Delphi's Array function certainly won't be available and you would need to do something clever with pointers, and I have no clue whether you could even get that to work.
Possibly your best bet is to use what is known as Variant Open Array Parameters.
From the help: http://docwiki.embarcadero.com/RADStudio/en/Parameters_(Delphi)#Variant_Open_Array_Parameters
Variant open array parameters allow
you to pass an array of differently
typed expressions to a single
procedure or function. To define a
routine with a variant open array
parameter, specify array of const as
the parameter's type. Thus
procedure DoSomething(A: array of
const);
declares a procedure called
DoSomething that can operate on
heterogeneous arrays.
The array of const construction is
equivalent to array ofTVarRec.
TVarRec, declared in the System unit,
represents a record with a variant
part that can hold values of integer,
Boolean, character, real, string,
pointer, class, class reference,
interface, and variant types.
TVarRec's VType field indicates the
type of each element in the array.
Some types are passed as pointers
rather than values; in particular,
strings are passed as Pointer and must
be typecast to string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5210839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: C# function that takes pointer to function as an in parameter without declaring any specific delegate types? I want to implement a method that will find stuff in my custom class. It should work like generic collections work - i pass a pointer to a function, and the method will iterate through all it has to look in, apply this function, and if it returns true return the found item.
I'd like to pass function pointer as a parameter, but i dont want to declare delegate types.
I know i can do something like:
delegate bool Foo(MyClass)
MyClass MyMethod(Foo x)
{...}
And i know i can do something like this:
MyClass MyMethod(Func<MyClass,bool> x)
But can i do it without declaring a delegate type and without using built in stuff like Func<> which has limits on how many parameters i can have (in case of Func, one...)
A: You can allways pass in a Delegate and call DynamicInvoke on it:
MyClass MyMethod(Delegate x) {
// ...
x.DynamicInvoke(....);
// ...
}
A: You can just use delegate if you want, although it's a bit old school :)
public void TestInvokeDelegate()
{
InvokeDelegate( new TestDelegate(ShowMessage), "hello" );
}
public void InvokeDelegate(TestDelegate del, string message)
{
del(message);
}
public delegate void TestDelegate(string message);
public void ShowMessage(string message)
{
Debug.WriteLine(message);
}
A: It looks like you are trying to implement the Visitor pattern. In this case visiting methods usually have only one parameter - the instance to visit. Having additional arguments passed around conceals the use of the pattern and makes it harder to reason about. This article shows you one way to implement it in C#.
The key is to create a visitor class that will encapsulate all the parameters that affect the visiting process. This way you don't need to pass anythnig other than an object in question in the visiting method - everything else lives in instance fields.
However, if you really want to pass some additional parameters in the method and don't know what type they can have, there are ways to do that. More or less standard approach in .NET world is to use a delegate without return value and with single parameter of type object, the example would be ParameterizedThreadStart delegate:
public delegate void ParameterizedThreadStart(
Object obj
)
This way you get to pass only one parameter in the delegate, but it could be anything - an instance of a class, an array or null, if you end up not needing additional arguments after all. The downside of this approach is that it requires type casting which can lead to runtime errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10052380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .NET: Read a Text file wihtout locking it I need to read a text file while another application is writing to it.
In this scenario I've programmed:
Dim _fs_ As FileStream = File.Open("c:\log.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
Dim _sr_ As New StreamReader(_fs_)
What I can see is that the other application cannot write to the file until I close the file with
_sr_.Close()
Is FileShare.ReadWrite really working? Any other way to get this file sharing working?
Thank you in advance
EDIT:
I tried to investigate further and coded a small application by my self that writes to the log file I need to read: in that application I open the file as follows
Dim _fs_ As FileStream = File.Open("c:\log.txt", FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
Dim tw As New StreamWriter(_fs_)
My small test application can write to the log while the other is reading: so FileShare flag does work.
Maybe the "official" logger application (which I didn't personally write) asks for an exclusive lock on the file to be able to write to it (as one of you already suggested). I will ask the programmer!
Thank you all
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23681749",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery Cookie plugin, check to see if cookie is unset So Im using the jquery cookie plugin and I need to check if a cookie is unset. I set it up something like this:
if ($.cookie('language')==null) {
}
This doesn't seem to work. Any ideas why?
A: Use simply:
if($.cookie("language")){}
A: To see what the plugin is returning, do a console.log() call:
console.log($.cookie("language"));
This should tell you what is being returned from the plugin if you monitor your Inspector / Firebug console.
I think you can get away with just doing if($.cookie("language")) but you'll have to test that.
A: Line #90 in the source looks like that SHOULD be the result you want. Check for any errors and test what happens if the cookie is set.
https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6026611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Angularjs http post request - params are not reaching to server I am trying to create post request with angularjs. This is my code for adding an supplier to server.
SupplierService.addNewSupplier = function(supplier) {
alert (supplier.name);
alert (supplier.mobile);
var Indata = {'name': supplier.name, 'mobile': supplier.mobile};
//var Indata = {'product': $scope.product, 'product2': $scope.product2 };
var req = {
url: SupplierURL,
method: 'POST',
params: Indata,
headers: {'Content-Type': 'application/json'}
};
//$http.post(SupplierURL, Indata)
$http(req)
.then(function(success){
console.log(success);
//SupplierList.push({id: data, name: supplier.name, mobile: supplier.mobile});
supplier.name = "";
supplier.mobile = "";
},function (error){
console.log(error);
alert ('Supplier add error.');
});
};
After making the request, callback is coming to error part and in console log i can see.
{error: true, message: "Failed to create supplier. Please try again", name: null, mobile: null}
Why name and mobile is not reaching to server. Same request works fine with postman(api testing tool). So i don't thing there can be anu issue in server side code. Any help will be appreciated.
A: From the $http documentation you can clearly see request parameters:
https://docs.angularjs.org/api/ng/service/$http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
So, in your case you need to switch params with data:
var req = {
url: SupplierURL,
method: 'POST',
data: Indata,
headers: {'Content-Type': 'application/json'}
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47054793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ValueError: expected a dict or pandas.DataFrame I am trying to create a categorical vBar that will show the total number of migrants picked up for various operations, however, when I pass the 'groupby' pandas object into the column data source, I keep getting an error and I'm not quite sure what I'm doing wrong.
I have looked in a few places for similar problems, but I can't seem to find any answers.
Can anyone point me in the right direction?
#Imports
import pandas as pd
from bokeh.io import curdoc
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.models.tools import HoverTool
from bokeh.models import Button
from bokeh.layouts import row
#Global variables
viewFilter='Operation'
#Data
df = pd.read_csv('data.csv')
grouped = df.groupby(viewFilter)['Total Migrants']
source = ColumnDataSource(grouped)
#grouped = df.groupby(viewFilter)['Total Migrants'].sum()
#source = ColumnDataSource(pd.DataFrame(grouped))
operations = source.data[viewFilter].tolist()
# Fig Creation Function
def create_figure():
global viewFilter
p=figure(x_range=operations)
p.vbar(x=viewFilter, top='Total Migrants',
source=source, width=0.70)
p.title.text='Demo Chart'
p.xaxis.axis_label = viewFilter
p.yaxis.axis_label = 'Total Migrants'
#Hover took
hover = HoverTool()
hover.tooltips=[
("Total Migrants Rescued", "@{Total Migrants}")]
hover.mode='vline'
p.add_tools(hover)
return p
#Update Data with Ship-level aggregation
def shipUpdate():
print("Ship Button was Pushed")
#Widgets
shipButton = Button(label='Ship Level')
shipButton.on_click(shipUpdate)
#Implement Layout
layout = row(shipButton, create_figure())
#Add Layout to Document
curdoc().add_root(layout)
A: It seems that if I explicitly pass in a pandas dataframe object, it solves this error:
source = ColumnDataSource(pd.DataFrame(grouped))
A: Looks like wrong parameter value has passed in groupby() method or in ColumnDataSource()
Syntax:
DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=False, observed=False, **kwargs)
Parameter by-> list, str, dict
And the code snippet of the constructer of ColumnDataSource is below -
def __init__(self, *args, **kw):
''' If called with a single argument that is a dict or
pandas.DataFrame, treat that implicitly as the "data" attribute.
'''
if len(args) == 1 and "data" not in kw:
kw["data"] = args[0]
# TODO (bev) invalid to pass args and "data", check and raise exception
raw_data = kw.pop("data", {})
if not isinstance(raw_data, dict):
if pd and isinstance(raw_data, pd.DataFrame):
raw_data = self._data_from_df(raw_data)
elif pd and isinstance(raw_data, pd.core.groupby.GroupBy):
raw_data = self._data_from_groupby(raw_data)
else:
raise ValueError("expected a dict or pandas.DataFrame, got %s" % raw_data)
super(ColumnDataSource, self).__init__(**kw)
self.data.update(raw_data)
A: Your version of Bokeh is too old. Support for passing Pandas GroupBy objects was added in version 0.12.7. If you want to be able to pass GroupBy objects directly to initialize a CDS (e.g. to access all the automatic summary statistics that creates), you will need to upgrade to a newer release.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52953857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Parsing a JSON string in C# like javascript or python do I am trying to make a program that needs to read JSON data from a give file. But the JSON files may be very complex. Here is the code i am using
static void Main(string[] args)
{
//step one: get a correct file path
string filepath = getFilePath("Please write here the path to your file");
//getFilePath is just a function I wrote to read user entry and automatically sanitize the string.
while (!File.Exists(filepath)) { filepath = getFilePath("The file path appears to be wrong, please correct."); }
//Setep 2: read the text of the file
string fileJSONString = File.ReadAllText(filepath);
//step 3: parse
object myDictionaryFromJSON = (new JavaScriptSerializer().DeserializeObject(fileJSONString));
object question1 = myDictionaryFromJSON.questions[0];
}
The thing is that Visual Studio gives me a lot of erros. I have tried using Dictionary instead of object, but it still doesnt work the way I need it to work. For example, this would actually work on python.
myDictionaryFromJSON = json.loads(JSONtext);
question1 = myDictionaryFromJSON['questions'][0];
question1text = question1["theQuestion"];
question1options = question1["options"];
question1correctAnswer = question1["correctAnswer"];
This is just an example. The thing is that Python and javascript can work with json perfectly, and are really good at converting JSON strings to dictionaries and objects. But C# is not working. I don't know what to do. What could I do?
A: I am assuming you are not using Json.NET. If this the case, then you should try it.
It has the following features:
*
*LINQ to JSON
*The JsonSerializer for quickly converting your .NET objects to JSON
and back again
*Json.NET can optionally produce well formatted, indented JSON for
debugging or display
Look how fast Json.NET compared to JavaScriptSerializer:http://i.stack.imgur.com/T77y2.png
Example code for load json file in C#:
JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32928474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to read the results of a LoadRunner test? I'm using LoadRunner but I do not wish to use the Analysis tool of LoadRunner to do the results analysis.
I've found out that the results are stored in the *.eve.gzl files (in the Result folder), but the *.eve files doesn't seem to be readable even after unzipping *.eve.gzl via 7-zip.
What format are *.eve files based on?
A: You cannot read the eve files as this is a proprietary format. Actually there are many more files that need to be read in order to decipher the eve files. What you can do is to open a new session with your results in Analysis tool that comes with LoadRunner. It will create a database file for you from the eve files based on the database you configured in the tool. You can then try to use this database to do your own analysis.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25151589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Restructure a csv file into a txt file I have a csv file with multiple rows with this structure
name lastname group password
john smith sales abc1
liza jones hr abc2
The list is around 500 rows long, and I would like to create a txt file with this structure
- name: j.smith
password: abc1
groups: admins
I want to reproduce spacing, so before the "-" character you will see there are 2 spaces, and five spaces before password as this is needed in the final txt file.
A: While in general you should not use pandas iterrows, because it is very slow, I am going to use it in my answer in part because you do not need to use pandas at all: you just want to iterate over the rows in your CSV:
import pandas as pd
df = pd.DataFrame.from_dict({'name': {0: 'john', 1: 'liza'}, 'lastname': {0: 'smith', 1: 'jones'}, 'group': {0: 'sales', 1: 'hr'}, 'password': {0: 'abc1', 1: 'abc2'}})
template = """- name: {fname[0]}. {lname}
password: {pword}
groups: {groups}
"""
with open('output.txt', 'w') as fp:
# iterrows returns the index, which we ignore with _
for _, (name, lastname, group, password) in df.iterrows():
fp.write(template.format(fname = name, lname = lastname, pword = password, groups = group))
Here we use a template string that we will substitute the values into using keyword arguments in the string format method. This will write the output to output.txt. Notice the keywords correspond directly to the keywords used in the template. The resulting text file appears as:
- name: j. smith
password: abc1
groups: sales
- name: l. jones
password: abc2
groups: hr
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70854326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: insert user's data from FQL into MySQL I'm trying to get user's data from my PHP app and then store those data into my database. Before i upload my app into Facebook i wanted to know if this form of code is written okay.
Below is the code that i used.
<head>
<?php
require_once('php-sdk/facebook.php');
$config = array(
'appId' => 'xxxx',
'secret' => 'xxxxxx',
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
?>
</head>
<body>
<?php
if($user_id) {
// We have a user ID, so probably a logged in user.
// If not, we'll get an exception, which we handle below.
try {
$fql = 'SELECT name, first_name, last_name, birthday_date, sex,
education, locale, activities from user where uid = ' . $user_id;
$ret_obj = $facebook->api(array(
'method' => 'fql.query',
'query' => $fql,
));
mysql_query("INSERT INTO table(firstname, lastname, birthday, sex,
education, local, activities) VALUES($ret_obj['first_name'], $ret_obj['last_name'],
$ret_obj['birthday_date'], $ret_obj['sex'], $ret_obj['education'],
$ret_obj['locale'], $ret_obj['activities']) ");
// FQL queries return the results in an array, so we have
// to get the user's name from the first element in the array.
echo '<pre>Name: ' . $ret_obj[0]['name'] . '</pre>';
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, so print a link for the user to login
$login_url = $facebook->getLoginUrl();
echo 'Please <a href="' . $login_url . '">login.</a>';
}
?>
</body>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21811493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Group events by day with has_many :dates association in rails I have a Events model which has many Dates.
I am listing the next weeks events and would like to group the events by day and only show the published events. I have the following code and it works but it still includes the unpublished events.
Date.all.group_by {|d| d.date.at_beginning_of_day }.each do |datestr, dates|
Ideally I would like to have something like this...
@events = Event.find(:all, :conditions => {:published => true})
@events.group_all_dates_by_day.each do |datestr, dates|
How would I do this?
EDIT
This is what I would like to do but I don't like the code.
@events = Event.find(:all, :conditions => {:published => true})
ids = @events.map { |event| event.dates.map { |date| date.id }.join.to_i}
Date.find(ids).group_by {|date| date.date.at_beginning_of_day }
A: Do something like this:
@published_events = Event.select("events.*, dates.date AS date_of_event")
.joins(:dates) # you join dates table to sort the events by date
.where(:published => true) # here you take only published events
.order("dates.date ASC") # here you order them
In your views you'll do something like
@published_events.each do |event|
<p><%= event.id %></p>
<p><%= event.name %></p>
<p><%= event.date_of_event %></p>
end
Caution -> You did not specify the exact name of your columns so I'm guessing that you event has a name, or your dates table has a column call date.
I hope this is useful!
Edit:
If you want to group them by date, after you retrieve them from the database (this is very important ), you could indeed use group_by ( group by is located in Enumerable/group_by ) like this
@published_events.all.group_by(&:date_of_event)
If you do like this you will end up with a hash where every key is a date, and the coresponding value for that key is an array of events
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8481415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: If statement, first condition's value is within range of second conditional but it returns first conditional I'm creating a QA sampling calculator using a C=0 sampling plan.
Whenever I input any number and try it, the result I'm provided corresponds to that of a different range.
const sample = parseFloat(this.sampleSize)
const lot = parseFloat(this.lotSize)
if (aqlSelector.value == 0.010) {
if (this.sampleSize > 0 || this.sampleSize <= 1200) {
lotQty.innerText = 'All'
console.log(sample)
console.log(lot)
} else if (this.sampleSize >= 1201) {
lotQty.innerText = '1250'
}
}
Code after trying different approach
Results I'm getting
Codepen of whole project: https://codepen.io/cesar-higashi/pen/LYbPwaJ
A: You have used wrong logical operator
if (this.sampleSize > 0 || this.sampleSize <= 1200)
it should be
if (this.sampleSize > 0 && this.sampleSize <= 1200)
With your || (or) it returns first for every value greater than 0
A: Solved it!
Turns out, a certain section in the code added a comma (',') to long numbers to make them easier to read, which in turn made them NaN.
I will update the codepen once the project is concluded. To all who took the time, thanks a lot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65958353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I implement "op" in terms of "op=" in a CRTP base class? Herb Sutter's Guru of the Week #4, "Class Mechanics", teaches that the "a op b" form of an overloaded operator should be implemented in terms of the "a op= b" form (see point #4 in the solutions).
As an example, he shows how do to this for the + operator:
T& T::operator+=( const T& other ) {
//...
return *this;
}
T operator+( T a, const T& b ) {
a += b;
return a;
}
He points out that first parameter in operator+ is intentionally being passed by value, so that it can be moved if the caller passes a temporary.
Notice that this requires that the operator+ be a non-member function.
My question is, how can I apply this technique to an overloaded operator in a CRTP base class?
So say this is my CRTP base class with its operator+=:
template <typename Derived>
struct Base
{
//...
Derived operator+=(const Derived& other)
{
//...
return static_cast<Derived&>(*this);
}
};
I can see how to implement operator+ in terms of operator+= as a member function if I dispense with the "pass the first argument by value" optimization:
template <typename Derived>
struct Base
{
//...
Derived operator+(const Derived& other) const
{
Derived result(static_cast<const Derived&>(*this);
result += other;
return result;
}
};
but is there a way to do this while using that optimization (and therefore making the operator+ a nonmember)?
A: The normal way to implement Herb's advice is as follows:
struct A {
A& operator+=(cosnt A& rhs)
{
...
return *this;
}
friend A operator+(A lhs, cosnt A& rhs)
{
return lhs += rhs;
}
};
Extending this to CRTP:
template <typename Derived>
struct Base
{
Derived& operator+=(const Derived& other)
{
//....
return *self();
}
friend Derived operator+(Derived left, const Derived& other)
{
return left += other;
}
private:
Derived* self() {return static_cast<Derived*>(this);}
};
If you try to avoid the use of friend here, you realize it's almost this:
template<class T>
T operator+(T left, const T& right)
{return left += right;}
But is only valid for things derived from Base<T>, which is tricky and ugly to do.
template<class T, class valid=typename std::enable_if<std::is_base_of<Base<T>,T>::value,T>::type>
T operator+(T left, const T& right)
{return left+=right;}
Additionally, if it's a friend internal to the class, then it's not technically in the global namespace. So if someone writes an invalid a+b where neither is a Base, then your overload won't contribute to the 1000 line error message. The free type-trait version does.
As for why that signature: Values for mutable, const& for immutable. && is really only for move constructors and a few other special cases.
T operator+(T&&, T) //left side can't bind to lvalues, unnecessary copy of right hand side ALWAYS
T operator+(T&&, T&&) //neither left nor right can bind to lvalues
T operator+(T&&, const T&) //left side can't bind to lvalues
T operator+(const T&, T) //unnecessary copies of left sometimes and right ALWAYS
T operator+(const T&, T&&) //unnecessary copy of left sometimes and right cant bind to rvalues
T operator+(const T&, const T&) //unnecessary copy of left sometimes
T operator+(T, T) //unnecessary copy of right hand side ALWAYS
T operator+(T, T&&) //right side cant bind to lvalues
T operator+(T, const T&) //good
//when implemented as a member, it acts as if the lhs is of type `T`.
If moves are much faster than copies, and you're dealing with a commutative operator, you may be justified in overloading these four. However, it only applies to commutative operators (where A?B==B?A, so + and *, but not -, /, or %). For non-commutative operators, there's no reason to not use the single overload above.
T operator+(T&& lhs , const T& rhs) {return lhs+=rhs;}
T operator+(T&& lhs , T&& rhs) {return lhs+=rhs;} //no purpose except resolving ambiguity
T operator+(const T& lhs , const T& rhs) {return T(lhs)+=rhs;} //no purpose except resolving ambiguity
T operator+(const T& lhs, T&& rhs) {return rhs+=lhs;} //THIS ONE GIVES THE PERFORMANCE BOOST
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23377405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exploration Constant in UCB1 algorithm I'm currently writing a UCB1 algorithm for a game. The algorithm as I'm using it is:
average(i) + sqrt( (2 * ln(totalcount)) / count(i) )
Where averagei is the average score of arm i, count(i) is the count for arm i, and totalcount is the total samples of all arms. This is the equation for the score for a given arm i. The arm with the highest score, max(i), is chosen to be sampled. The algorithm then repeats this equation with the new data it got from that sample, ad infinitum, or until it runs out of thinking time.
I have an assignment which tells me to "modify the exploration constant" for the algorithm. I also notice that it exploits rather than explores almost all the time -- it hardly ever tries arms it has only visited once. However, I don't see any exploration constant. Am I missing some part of the algorithm?
A: The 2 is the exploration constant. The larger it is, the more the algorithm favors exploration over exploitation.
Also beware that this formula makes sense only when the payoffs are in [0,1] range, otherwise a large payoff (say 1000) will nullify the influence of the "exploration" part of the formula, effectively making it exploitation-only.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30229524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get a collection of all the DataRows coresponding to selected DataGridView rows Is there a direct way to do this, or do I need to iterate over the DataGridView.SelectedRows, and then access DataGridViewRow.DataBoundItem for each row to create one?
A: The DataGridView does not provide a SelectedDataRows and SelectedRows in not Linq-enabled, so Yes, you will have to write a foreach loop.
A: A generic extension method to add "SelectedDataRows" to DataGridViews:
public static T[] SelectedDataRows<T>(this DataGridView dg) where T : DataRow
{
T[] rows = new T[dg.SelectedRows.Count];
for (int i = 0; i < dg.SelectedRows.Count; i++)
rows[i] = (T)((DataRowView)dg.SelectedRows[i].DataBoundItem).Row;
return rows;
}
This is generic so that you can return a typed data row using Typed Datasets. You could make yours just return a DataRow[] if you wanted. This also assumes that your DataGridView has a DataView bound to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1829149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TableAdapter - updating without a key I'm a total newbie at the .net c# business and dove in this last week creating a form application to shuffle data around for SSIS configurations. The geniuses at MS decided not to apply a key to the table I'm working with - and generating a composite key of the two candidate fields will not work due to their combined length being too long. I don't particularly want to mess with the [ssis configurations] table schema by adding an autoincrement field.
So I've been having alot of trouble getting an update from a DataGridView control to work with a TableAdapter.
I need the update statement to be update table set a = x where b = y and c = z.
Can I set the update method of the TableAdapter, and if so, how. If not, what to do?
I see this autogenerated code:
this._adapter.InsertCommand = new global::System.Data.SqlClient.SqlCommand();
this._adapter.InsertCommand.Connection = this.Connection;
this._adapter.InsertCommand.CommandText = "INSERT INTO [dbo].[SSIS Configurations Staging] ([ConfigurationFilter], [Configur" +
"edValue], [PackagePath], [ConfiguredValueType]) VALUES (@ConfigurationFilter, @C" +
"onfiguredValue, @PackagePath, @ConfiguredValueType)";
But in my form code, the UpdateCommand is not available. I'm assuming this is because the above code is a class definition which I cannot change after creating the object. I see this code has a recommendation not to be changed since it is autogenerated by VS.
Thanks for your most excellent advice.
A: From your code i assume you are using a typed Dataset with the designer.
Not having a primary key is one of the many reasons the designer will not generate Insert, Update or Delete commands. This is a limitation of the CommandBuilder.
You could use the properties window to add an Update Command to the Apdapter but I would advice against that, if you later configure your main query again it will happily throw away all your work. The same argument holds against modifying the code in any *.Designer.cs file.
Instead, doubleclick on the caption with the Adaptername. The designer will create (if necessary) the accompanying non-designer source file and put the outside of a partial class in it. Unfortunately that is how far the code-generation of the designer goes in C#, you'll have to take it from there. (Aside: The VB designer knows a few more tricks).
Edit:
You will have to provide your own Update(...) method and setup an UpdateCommand etc.
var updateCommand = new SqlCommand();
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/593170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Monaco-editor : Is there a way to prevent cursor/editor's focus from being lost on clicking outside the editor ( on blur ) Monaco-editor :- Is there a way to prevent cursor/editor focus from being lost on clicking outside the editor.
My scenario :- I have a list of items in a dropdown that is outside the editor , user can select a dropdown item and I am calling executeEdits to paste this selected item in the editor's previous cursor position.
When the user opens the dropdown the focus from the editor is lost, user is now not sure where his selected dropdown value will be inserted.
Is there a way in which I can prevent the editor from losing it's focus on blur. ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65843672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calculate sum of values in Object of arrays I have a json in the below format
let newarrayObj = [
{
"cost one": "118",
"cost two": "118",
"cost three": "118"
},
{
"cost one": "118",
"cost two": "118",
"cost three": "118"
},
{
"cost one": "118",
"cost two": "118",
"cost three": "118"
}
]
I need the sum of each object which is 118 + 188 + 118 = 424 and the sum of total which is 424 + 424 + 424 = 1272
approach so far :
Object.entries(newarrayObj).map(([key, value]) => {
Object.values(value).map((j, i) => {
console.log(j);
})
})
how can i get the expected sum values ?
A: You can .map over all array entries and then use .reduce on the Object.values of each array entry to sum the values:
let data = [
{
"cost one": "118",
"cost two": "118",
"cost three": "118"
},
{
"cost one": "118",
"cost two": "111",
"cost three": "118"
},
{
"cost one": "120",
"cost two": "118",
"cost three": "118"
}
];
function sumValues(objArr) {
return objArr.map(curr => {
return Object.values(curr).reduce((prev, val) => prev += Number(val), 0)
});
}
console.log(sumValues(data));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66813203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fetching data from sqllite dynamically in table layout I am trying to fetch data dynamically from sqllite using table layout. I have used getLayoutInflater() for inflating but is not working and unable to get data in table rows.
Code:
MainActivity.java
package com.example.datab;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView user_tv,pass_tv; View view;
TableLayout tb;int counter=0;
TableRow tr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutt);
tb=(TableLayout)findViewById(R.id.tablelayout);
//tr=(TableRow)findViewById(R.id.tableRow1);
SQLiteDatabase md=openOrCreateDatabase("databa",MODE_PRIVATE,null);
md.execSQL("CREATE TABLE IF NOT EXISTS data (Username varchar(20),Password varchar(20))");
md.execSQL("INSERT INTO data VALUES('nobal','Sharma')");
Cursor cr=md.rawQuery("select * from data", null);
cr.moveToFirst();
//String username=cr.getString(cr.getColumnIndex("Username"));
if (cr.moveToFirst()){
do{
String username = cr.getString(cr.getColumnIndex("Username"));
String passwd=cr.getString(cr.getColumnIndex("Password"));
TableRow view=(TableRow)getLayoutInflater().inflate(R.layout.layoutt,tb, false);//here NPE
user_tv=(TextView)view.findViewById(R.id.textView1);
pass_tv=(TextView)view.findViewById(R.id.textView2);
user_tv .setText(username );
pass_tv.setText(passwd);
tb.addView(view);//and NPE here
}while(cr.moveToNext());
}cr.close();
}
}
And below is layoutt.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tablelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:layout_marginLeft="50dp"
android:layout_marginTop="100dp">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textSize="35dp"
android:paddingLeft="20dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="@drawable/cell_shape"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/cell_shape"
android:text="Medium Text"
android:textSize="35dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:paddingLeft="20dp"/>
</TableRow>
</TableLayout>
logcat is not showing up NOW,but i do tested ,the code gives null pointer exception on the commented lines in the code
Here is Logcat:
07-30 01:47:35.219: D/AndroidRuntime(973): Shutting down VM
07-30 01:47:35.219: W/dalvikvm(973): threadid=1: thread exiting with uncaught exception (group=0x41465700)
07-30 01:47:35.238: E/AndroidRuntime(973): FATAL EXCEPTION: main
07-30 01:47:35.238: E/AndroidRuntime(973): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datab/com.example.datab.MainActivity}: java.lang.ClassCastException: android.widget.TableLayout cannot be cast to android.widget.TableRow
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.os.Handler.dispatchMessage(Handler.java:99)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.os.Looper.loop(Looper.java:137)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.ActivityThread.main(ActivityThread.java:5103)
07-30 01:47:35.238: E/AndroidRuntime(973): at java.lang.reflect.Method.invokeNative(Native Method)
07-30 01:47:35.238: E/AndroidRuntime(973): at java.lang.reflect.Method.invoke(Method.java:525)
07-30 01:47:35.238: E/AndroidRuntime(973): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
07-30 01:47:35.238: E/AndroidRuntime(973): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-30 01:47:35.238: E/AndroidRuntime(973): at dalvik.system.NativeStart.main(Native Method)
07-30 01:47:35.238: E/AndroidRuntime(973): Caused by: java.lang.ClassCastException: android.widget.TableLayout cannot be cast to android.widget.TableRow
07-30 01:47:35.238: E/AndroidRuntime(973): at com.example.datab.MainActivity.onCreate(MainActivity.java:42)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.Activity.performCreate(Activity.java:5133)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-30 01:47:35.238: E/AndroidRuntime(973): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
07-30 01:47:35.238: E/AndroidRuntime(973): ... 11 more
A: I feel the approach taken by you can be made better.
You can at all not use a tablelayout, and still get the feel of using a table layout.
A simple approach, your tablerow is nothing but a simple row, and similar rows make a layout, ultimately giving you the look n feel of a tablelayout.
Why not creating a custom linearlayout with two or three textviews inside it with divider views added.
You can inflate this layout in a customadapter class extending BaseAdapter, and in the getView method simply inflate the layout and using a viewholder class you can populate the adapter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25029555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Custom adapter returning wrong row Textview Text I am implementing a custom adapter for listview. In which i have some textview and one checkbox.for checkbox i have implemented setOnCheckedChangeListener.But the problem is when i check a checkbox i am trying to get that row textview text. but it returning last row textview text.
Code
public class CustomStoreAdapter extends BaseAdapter implements Filterable {
ItemFilter mFilter;
int price;
private int lastPosition = -1;
ViewHolder mHolder;
ArrayList<String> favHotel;
private static SparseBooleanArray positionArray=new SparseBooleanArray();
SharedPreferences sharedPreferences;
public static ArrayList<HashMap<String,String>> finalHashList;
public static ArrayList<HashMap<String,String>> tempName;
public static ArrayList<Integer> selectedIds = new ArrayList<Integer>();
Context context;
String flag;
String favId;
ArrayList<String> htlId;
String [] favArr;
public CustomStoreAdapter(String flag, Context context, ArrayList<HashMap<String, String>> finalHashList, String favId) {
System.out.println("custom size>>"+finalHashList.size());
this.context = context;
CustomStoreAdapter.finalHashList =finalHashList;
for (int i=0;i<finalHashList.size();i++) {
htlId.add(finalHashList.get(i).get("id"));
}
tempName=finalHashList;
selectedIds=new ArrayList<>();
this.flag=flag;
this.favId=favId;
if (!favId.equals(""))
{
favId=favId.substring(6,favId.length());
//Log.e("substring favId",favId);
favArr=favId.split(",");
}
Log.e("flag is>>>",flag);
}
@Override
public int getCount() {
return finalHashList.size();
}
@Override
public Object getItem(int position) {
return finalHashList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public static void append( ArrayList<HashMap<String, String>> finalHashList1) {
}
public static StringBuilder getCheckedItems() {
StringBuilder mTempArry = new StringBuilder();
mTempArry.append("htlid=");
for(int i=0;i<finalHashList.size();i++) {
if(positionArray.get(i)) {
mTempArry.append(finalHashList.get(i).get("id"));
mTempArry.append(",");
}
}
return mTempArry;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
favHotel=new ArrayList<>();
View v = convertView;
sharedPreferences = context.getSharedPreferences("hotelDekho", Context.MODE_PRIVATE);
if(finalHashList.size() > position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TypefaceUtil.overrideFont(context.getApplicationContext(), "SERIF", "fonts/splash-font.ttf");
if (v == null) {
v = inflater.inflate(R.layout.serch_result_page, parent, false);
mHolder = new ViewHolder();
mHolder.txtId=(TextView)v.findViewById(R.id.txtId);
mHolder.txthotelRating = (TextView) v.findViewById(R.id.txtRating);
mHolder.txthotelName = (TextView)v.findViewById(R.id.Hotel_name);
mHolder.txtFavorite=(CheckBox) v.findViewById(R.id.imgFavorite);
mHolder.txthotelLocation = (TextView) v.findViewById(R.id.Hotel_location);
mHolder.txthotelPrice = (TextView) v.findViewById(R.id.price);
mHolder.txthotelPrice2 = (TextView) v.findViewById(R.id.price2);
mHolder.txthotelIconPlace = (TextView)v.findViewById(R.id.locIcon);
mHolder.txtLock = (TextView)v.findViewById(R.id.txtLock);
mHolder.txthotelIconR1 = (TextView) v.findViewById(R.id.txtR1);
mHolder.txthotelIconR2 = (TextView) v.findViewById(R.id.txtR2);
mHolder.rhotelRating = (CustomRatingBar) v.findViewById(R.id.ratingBar1);
mHolder.lnrPrice=(LinearLayout)v.findViewById(R.id.lnrPrice);
mHolder.imgHotel = (ImageView) v.findViewById(R.id.hotel_image);
mHolder.lnrRating=(LinearLayout)v.findViewById(R.id.lnrRating);
mHolder.lnrSignHotelList=(LinearLayout)v.findViewById(R.id.lnrSignHotelList);
mHolder.txthotelIconPlace.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder.txthotelIconR1.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder. txthotelIconR2.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder.txtLock.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
mHolder.txtFavorite.setTag(position);
v.setTag(mHolder);
}else
{
mHolder = (ViewHolder) v.getTag();
mHolder.txtFavorite.setOnCheckedChangeListener(null);
}
Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
v.startAnimation(animation);
lastPosition = position;
mHolder.txtId.setText(finalHashList.get(position).get("id"));
mHolder.txthotelName.setText(finalHashList.get(position).get("name"));
mHolder.txthotelLocation.setText(finalHashList.get(position).get("location"));
mHolder.txthotelRating.setText(finalHashList.get(position).get("rating") + "/5");
// mHolder.txtFavorite.setChecked(positionArray.get(position));
mHolder.txtFavorite.setChecked(positionArray.get(position));
for (int i=0;i<favArr.length;i++)
{
if(favArr[i].equals(finalHashList.get(position).get("id")))
{
mHolder.txtFavorite.setChecked(true);
}
}
mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener);
if (!flag.equals("favHtl")) {
mHolder.lnrPrice.setVisibility(View.VISIBLE);
Float price1 = Float.parseFloat(finalHashList.get(position).get("price"));
mHolder.txthotelPrice2.setText(String.valueOf(Math.round(price1)));
if (SearchHotelResults.flag.equals("offer")) {
price = Math.round(price1 + price1);
} else
price = Math.round(price1 + ((price1 * 20) / 100));
mHolder.txthotelPrice.setText(String.valueOf(price));
mHolder.txthotelPrice.setPaintFlags(mHolder.txthotelPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
mHolder.rhotelRating.refreshDrawableState();
if (!sharedPreferences.getString("email","").equals(""))
{
mHolder.lnrSignHotelList.setVisibility(View.GONE);
}
mHolder.rhotelRating.setScore(Float.parseFloat(finalHashList.get(position).get("star")));
if (finalHashList.get(position).get("img").startsWith("hoteldekho")) {
loadImagePicaso( mHolder.imgHotel, Config.storeImagePath + finalHashList.get(position).get("img"));
} else {
loadImagePicaso( mHolder.imgHotel, finalHashList.get(position).get("img"));
}
}
return v;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
Animation zoomOutAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
buttonView.startAnimation(zoomOutAnimation);
positionArray.put(htlId.indexOf(mHolder.txtFavorite.getText().toString()), isChecked);
Log.e("array is>>",getCheckedItems().toString()+">>>>"+ finalHashList.indexOf(mHolder.txtId.getText().toString()));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("favHotelId", getCheckedItems().toString());
editor.apply();
}
};
private class ViewHolder {
private TextView txtId;
private TextView txthotelRating;
private TextView txthotelName;
private TextView txthotelLocation;
private TextView txthotelPrice;
private TextView txthotelPrice2;
private TextView txthotelIconPlace;
private TextView txtLock;
private CheckBox txtFavorite;
LinearLayout lnrPrice;
private TextView txthotelIconR1;
private TextView txthotelIconR2;
private TextView txthotelIconArrow;
private CustomRatingBar rhotelRating;
private ImageView imgHotel;
private Button btnSubmit;
private LinearLayout lnrRating;
private LinearLayout lnrSignHotelList;
}
}
Please help me to how to get same row textview text on checkbox click
A: Problem:
Currently you're storing your ViewHolder in a class level field, which is being set in getView(), its going to be set to the latest ViewHolder every time ListView is calling getView() and there's absolutely no guarantee in the order of the position the getView() is called for. Its going to get random ViewHolder references, creating problems for you to track position So a class level ViewHolder isn't good solution.
Solution:
You need to keep track of position related to every check box. Tag the position to checkbox and get it in the listener as follow:
mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener);
mHolder.txtFavorite.setTag(position+""); //tag position as String object
Now you can get this position in your listener:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Since we set position in form of String, we need to convert String to int
int position = Integer.parseInt(buttonView.getTag());
}
A: You save position of mHolder.txtFavorite to tag, so you should just read the right position from tag, not from text
positionArray.put(htlId.indexOf(mHolder.txtFavorite.getTag()), isChecked);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43933658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS3: show/hide icon in li a I have this code for show/hide icon using css hover:
HTML:
<li>
<span class="tools"><a href="javascript:void()"><i alt="Delete" title="Delete" class="icon-remove-sign" onclick=deleteBox("1")></i></a></span>
</li>
CSS:
.box .todo-list > li> a> .tools {
display: none;
float: right;
color: #f56954;
}
.box .todo-list > li> a:hover .tools {
display: inline-block;
}
Now This Not Worked and not hide my icon. if i remove > a> from code this worked and hide but when add a> not worked.
how do can i fix this problem?
A: Your CSS selectors are slightly wrong, try:
.box .todo-list > li > .tools > a
And
.box .todo-list > li > .tools > a:hover
The selector parts need to go in the same order as the elements that they select are nested in the HTML.
Check out the W3C Selectors documentation for more details.
A: The > selector means immediate descendent.
In your markup, the immediate descendant of the li is the span.tools.
Therefore, li > a does not select anything.
But, li > .tools > a does select the a element.
An excellent write-up can be found here: Child and Sibling Selectors
A: The > selector above is a child combinator selector. This means it will only select elements that are direct children of a parent. In otherwords, it only looks one level down the markup structure, no deeper.
So
.box .todo-list > li > .tools > a
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24342183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: serve content from cache Node JS Good Night
I am trying of serving content from cache memory, I am learning using a online course, but I have a problem, becouse when i modify a file of the content, the serve continnue using cache memory and I use a conditionel where evaluate if the cache is update or no....
I have used this code in Linux and it serves, but when I do it using windows It does not serve...
var http = require('http');
var path = require('path');
var fs = require('fs');
var mimeTypes = {
'.js' : 'text/javascript',
'.html': 'text/html',
'.css' : 'text/css'
};
var cache = {};
function cacheYEntrega(f, cb) {
fs.stat(f, function (err, stats) {
var ultimoCambio = Date.parse(stats.ctime),
estaActualizado = (cache[f]) && ultimoCambio > cache[f].timestamp;
if (!cache[f] || estaActualizado) {
fs.readFile(f, function (err, data) {
console.log('cargando ' + f + ' desde archivo');
if (!err) {
cache[f] = {content: data,
timestamp: Date.now() //almacenar datos tiempo actual
};
}
cb(err, data);
});
return;
}
console.log('cargando ' + f + ' de cache');
cb(null, cache[f].content);
}); //final de fs.stat
}
http.createServer(function (request, response) {
var buscar= path.basename(decodeURI(request.url)) || 'index.html',
f = 'content/' + buscar;
fs.exists(f, function (exists) { //path.exists para Node 0.6 e inferiores
if (exists) {
cacheYEntrega(f, function (err, data) {
if (err) {response.writeHead(500); response.end(); return; }
var headers = {'Content-type': mimeTypes[path.extname(f)]};
response.writeHead(200, headers);
response.end(data);
});
return;
}
response.writeHead(404); //no se ha encontrado archivo
response.end('Pagina no encontrada');
});
}).listen(8080);
Thanks
A: After of checking the code and the variables, I discovered I had a problem with the ctime of stats, I do not know why the ctimes does not change when a file content is modified, so I only used mtime instead of ctime and it start serving the content in the right way....
thanks...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28016172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Having Docker access External files I am interested in having Docker have access to external files, but I do not wish to include them as a volume. The files that I need access to will change over time, and this means I would need to re-mount repeatedly, unless I can mount a mere directory, and whatever is in that directory is also mounted.
I am just in need of allowing a software program pushed into a container, to run "over" my local system, where this software program has access to files on my local system.
Advice? Is there another way besides adding the files needing to be processed as a volume?
A: I solved the same problem with below commands
docker run --mount type=bind,source="$(pwd)"/data,target=/home/data -it <name_of_container>
Note "-it conainter_name" should be the last flags.
A: It sounds like mounting a host directory in the container is what you're looking for. You won't have to restart the container to pick up changes to the mounted directory. Link to relevant docs.
A: I wonder if the ADD command could help you accomplish your goal. For instance, given the Dockerfile line:
ADD /Users/userX/myappfiles /appfiles
and the command line:
docker run myapp --input /myappfiles
myapp would be able to access /Users/userX/myappfiles on the local filesystem to fetch its inputs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30652299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: java jzy3d dependencies issue I've linked latest jogl library to my project, but unfortunately I have next error during compiling the program Exception in thread "main" java.lang.NoSuchMethodError: javax.media.opengl.GLProfile.isAvailable(Ljava/lang/String;)Z
what library should I link to solve this issue?
A: I just solved this issue for myself.
Go here: http://search.maven.org/#search%7Cga%7C2%7Cjogamp
and download gluegen-2.3.2, gluegen-rt-2.3.2, and jogl-all-2.3.2 (or whatever the latest version is). You have to download two things for each, the regular jar AND the source.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37657091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to bind ngFormModel in angular2 using Dart? The following works in a form (the form is displayed)
.html
<form (ngSubmit) = "onSubmit()"
#nameForm = "ngForm">
{{diagnostic}}
<div class = "mdl-card mdl-shadow--3dp layout horizontal wrap">
<div class = "mdl-card__title">
<h2 class = "mdl-card__title-text">Name</h2>
</div>
<div
class = "mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input
required
type = "text"
[(ngModel)] = "name.first"
ngControl = "first"
#first = "ngForm"
(input)="onInputHandler($event)"
class = "mdl-textfield__input ng-valid"
id = "first">
<label
class = "mdl-textfield__label"
for = "first">First</label>
<span [hidden] = "isFirstValid"
class = "mdl-textfield__error">{{firstErrorMsg}}</span>
</div>
<div class =
"mdl-card__actions mdl-card--border">
<button id = "startButton"
class = "mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect"
>Submit
</button>
<br>
<button class = "mdl-button mdl-js-button mdl-button--raised mdl-button--colored">
Button All
</button>
</form>
Trying to follow the example at Forms and Validation in Angular 2.0,
I cannot get the UI to display by changing the first line of the form to
<form (ngSubmit) = "onSubmit()"
[ngFormModel]="form" #f="form">
{{diagnostic}}
..
With the change the browser simply does not display anything as if it cannot parse the markup - the error is actually shown in pub-serve or debug mode.
Transform TemplateCompiler on epimss_ng2_reg|lib/components/name_component.ng_meta.json threw error: Template parse errors:
There is no directive with "exportAs" set to "form" ("
<div [hidden] = "isSubmitted">
<form (ngSubmit) = "onSubmit()"
[ng-form-model]="form" [ERROR ->]#f="form">
{{diagnostic}}
<div class = "mdl-card mdl-shadow--3dp layout horizontal wrap">
"): NameComponent@12:31
....
Why is this not working?
A: Seems this was changed since when the blog post was created.
NgForm is now exported as ngForm instead of form.
[ngFormModel]="form" #f="ngForm">
It's correct in the GitHub source but not in the blog post.
Full component according to the example in the blog post in Dart
@Component(selector: 'form-element')
@View(template: '''
<h1>form-element</h1>
<form (ngSubmit)="onSubmit()" [ngFormModel]="form" #f="ngForm">
<div>
<div class="formHeading">First Name</div>
<input type="text" id="firstName" ngControl="firstName">
<div class="errorMessage" *ngIf="f.form.controls['firstName'].touched && !f.form.controls['firstName'].valid">First Name is required</div>
</div>
<div>
<div class="formHeading">Street Address</div>
<input type="text" id="firstName" ngControl="streetAddress">
<div class="errorMessage" *ngIf="f.form.controls['streetAddress'].touched && !f.form.controls['streetAddress'].valid">Street Address is required</div>
</div>
<div>
<div class="formHeading">Zip Code</div>
<input type="text" id="zip" ngControl="zip">
<div class="errorMessage" *ngIf="f.form.controls['zip'].touched && !f.form.controls['zip'].valid">Zip code has to be 5 digits long</div>
</div>
<div>
<div class="formHeading">Address Type</div>
<select id="type" ngControl="type">
<option [value]="'home'">Home Address</option>
<option [value]="'billing'">Billing Address</option>
</select>
</div>
<button type="submit" [disabled]="!f.form.valid">Save</button>
<div>
<div>The form contains the following values</div>
<div>
{{payLoad}}
</div>
</div>
</form>
''')
class FormElement {
ControlGroup form;
String payLoad;
FormElement(FormBuilder fb) {
form = fb.group({
"firstName": ['', Validators.required],
"streetAddress": ['', Validators.required],
"zip": [
'',
Validators.compose([ZipValidator.validate])
],
"type": ['home']
});
}
void onSubmit() {
payLoad = JSON.encode(this.form.value);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34868228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Gmail sending error (C#) I'm trying to send an email via C# but I keep on getting this error:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at...
The stack trace can be found here:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Repetrel.View.EmailForm.btnSend_Click(Object sender, EventArgs e) in c:\2015 Hyrel Projects\Repetrel\src\Repetrel\View\EmailForm.cs:line 238
Here is my code:
NetworkCredential loginInfo = new NetworkCredential(Properties.Settings.Default.MyEmailAddress, Properties.Settings.Default.MyEmailPassword);
//System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(Properties.Settings.Default.SMTPAddress);
////Trace.WriteLine("smtp = " + Properties.Settings.Default.SMTPAddress);
//smtpClient.Port = 587;
//smtpClient.EnableSsl = true;
//smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
////smtpClient.UseDefaultCredentials = false;
//smtpClient.Credentials = loginInfo;
var smtpClient = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
Credentials = loginInfo,
Timeout = 20000
};
//smtpClient.SendAsync(message, "test");
smtpClient.Send(message);
//Output to log
OutputToLog(message);
//Close Window
Close();
}
catch (Exception ex)
{
Trace.WriteLine(ex.ToString());
MessageBox.Show("An error occurred. Please see the trace log for more information.");
}
I have tried everything mentioned in previous posts(there are many of them), but nothing seems to work. I have tried with and without default credentials and setting the flag to false/true. Nothing seems to work. Might anyone be able to point me in the right direction?
Thanks in advance!
A: Apparently GMAIL was blocking my email address from using less secure devices. You can turn off the blocking at: https://www.google.com/settings/security/lesssecureapps.
A: Perhaps UseDefaultCredentials = false, instead?
Edit: This seems similar to an older StackOverflow question: SmtpClient with Gmail
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31169792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does AWS Device Farm support Android Orchestrator? Can I upload Android Orchestrator .apk to the AWS Device Farm as a 3rd apk (together with main app apk and test-suite apk)? Or application state is not persistent in the Device Farm, so that it doesn't require external Orchestrator at all?
Currently we use local runner for Android Espresso tests. Some tests require app state/data to be cleared between tests, so that we use Orchestrator. According to a console, it is uploaded as a separate apk to the device. AWS Device Farm allows uploading only 2 apks: app itself and a test-suite.
So, how could I use Orchestrator in the AWS Device Farm for tests to have cleared app state/data after each test?
A: You could send Orchestrator as an auxiliary apps when using AWS Device Farm.
If you're using the console, this is done during the Specify device state step under Install other apps
If you're using the CLI use auxiliaryApps flag https://docs.aws.amazon.com/cli/latest/reference/devicefarm/schedule-run.html
A: Short answer: Uploading the orchestrator seems to work, but you dont need it to get the tests run in separate processes.
Long answer: As Scott's answer said, you can upload and install the orchestrator to the device. You should upload android test services apk as well (test-services-1.4.0-alpha05.apk for example)
Also the Piotr's comment is correct. If you want to use the orchestrator, you should specify your own start command for tests like this: "adb shell "CLASSPATH=$(pm path androidx.test.services) exec app_process / androidx.test.services.shellexecutor.ShellMain am instrument ...". This can be done by using the custom evironment option from the device farm's start test wizard. More info can be found here: https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator
If you want to get the tests run separatedly, just use the default environment option, as it seems to isolate the tests by default in the aws farm. There's no need to use the orchestrator. Orchestrator is needed only, if you want to use your own custom test runners, or use custom parameters that needs to be passed to the tests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53911778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php re-sorting an array I have an array of entries that are separated by year and month like below. I need to sort this array so that entries are "grouped" by year and then by category.
Array
(
[Oct 2011] => Array
(
[0] => Array
(
[title] => CAD Drawing Updates
[file] => /gm-June2010-driver.pdf
[category] => Windows
)
)
[Sep 2011] => Array
(
[0] => Array
(
[title] => title
[file] => /gm-June2010-driver.pdf
[category] => Windows
)
[1] => Array
(
[title] => edges
[file] => /gm-June2010-driver.pdf
[category] =>Walling
)
[2] => Array
(
[title] => Specification update
[file] => /gm-June2010-driver.pdf
[category] => Windows
)
)
)
So this is the sort of thing I'm after.
Array
(
[Oct 2011] => Array
(
[Windows] => Array
(
[0] => Array
(
[title] => CAD Drawing Updates
[file] => /gm-June2010-driver.pdf
)
)
)
[Sep 2011] => Array
(
[Windows] => Array
(
[0] => Array
(
[title] => title
[file] => /gm-June2010-driver.pdf
[category] => Windows
)
[1] => Array
(
[title] => Specification update
[file] => /gm-June2010-driver.pdf
[category] => Windows
)
)
[Walling] => Array
(
[0] => Array
(
[title] => edges
[file] => /gm-June2010-driver.pdf
[category] => Curtain Walling
)
)
)
)
I'm not sure if this is a job for the sort functions, any help would be appreciated, thanks.
A: No, that can't be done with the sort function, you need to create a new array by iterating through your original array with nested foreach loops.
$newArr = array();
foreach($arr as $month => items) {
foreach($items as $data) {
$newArr[$month][$data["category"]][] = $data;
}
}
A: You don't want to sort but just to rename keys. PHP Arrays do not support to rename keys directly, so you need to create a new array first that is build with the new keys while maintaining the existing values.
At the end you can replace the original array with the new one:
$rekeyed = array();
foreach($array as $monthYear => &$value)
{
$r = sscanf($monthYear, '%s %d', $month, $year);
if ($r != 2) throw new Exception(sprintf('Invalid Key "%s".', $monthYear));
$categories = array();
foreach($value as &$item)
{
$category =& $item['category'];
unset($item['category']);
$categories[$category][] =& $item;
}
unset($item);
$value =& $categories;
unset($categories);
$rekeyed[$year][$month] =& $value;
}
unset($value);
$array =& $rekeyed;
unset($rekeyed);
print_r($array);
Output:
Array
(
[2011] => Array
(
[Oct] => Array
(
[Windows] => Array
(
[0] => Array
(
[title] => CAD Drawing Updates
[file] => /gm-June2010-driver.pdf
)
)
)
[Sep] => Array
(
[Windows] => Array
(
[0] => Array
(
[title] => title
[file] => /gm-June2010-driver.pdf
)
)
[Walling] => Array
(
[0] => Array
(
[title] => edges
[file] => /gm-June2010-driver.pdf
)
)
)
)
)
Demo
A: I think the function you should be looking at is uasort.
http://www.php.net/manual/en/function.uasort.php
First do a sort on the main array, the for each element in the array, do a usort on the child array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7723076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is Parallelizable attribute not showing in my SpecFlow feature.cs files I'm using NUnitv3 with SpecFlow 2.0, ive added the attribute [assembly: Parallelizable(ParallelScope.Fixtures)] to my assemblyinfo.cs and have regenerated all of the steps.
However what im noticing is this attribute is not being populated into the generated feature files.
A post by Gaspar Nagy here: https://github.com/techtalk/SpecFlow/wiki/Parallel-Execution
suggests that it should be. Could someone she light on how I can get this attribute included?
A: This is an assembly level attribute. You need it only once. This is the "flag" that the NUnit Test Runner uses to determine if the tests supports parallelism.
SpecFlow 2.0 is not adding this attribute automatically to your code, so have to do it manually once.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35845755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Select all events from a month in grails I am new to groovy/grails, and I'm trying to to do a criteria search that finds all posts for a month, basically like this:
def getUserMinutesForYear(User user, Date date){
Date firstDate = new GregorianCalendar(date.year, Calendar.JANUARY, 1, 0, 0, 0).time
Date lastDate = new GregorianCalendar(date.year, Calendar.DECEMBER, 31, 23, 59, 59).time
def c = JobRegistration.createCriteria()
def minutes = c.get {
and{
eq("user.id", user.id)
between("job.happening", firstDate, lastDate)
}
projections {
sum("minutesWorked")
}
}
return minutes
}
The domain classes are
class Job {
String title
String description
Date happening
static hasMany = [registrations:JobRegistration]
}
class User {
static hasMany = [authorities: Role, registrations: JobRegistration]
static belongsTo = Role
String username
}
class JobRegistration {
Job job
User user
Integer minutesWorked
static belongsTo = [user:User,job:Job]
static constraints = {
user(blank: false)
job(blank:false)
minutesWorked(nullable :true)
}
String toString(){
return user.userRealName
}
}
Now, why do I get this exception?
org.codehaus.groovy.runtime.InvokerInvocationException: org.hibernate.QueryException: could not resolve property: job.happening of: JobRegistration
A: You need to nest the job relationship (you can also just us eq with user):
def minutes = c.get {
and{
eq("user", user)
job{
between("happening", firstDate, lastDate)
}
}
projections {
sum("minutesWorked")
}
}
cheers
Lee
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1468208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find and replace String from Object value using foreach C# I want to replace the value of two "string" members from their record in Object with the string I want.
I'm trying to use the .Contains() and replace() function on object
This is the object:
EmailParam param = new EmailParam();
And the EmailParam:
public class EmailParam {
public string UserName {get; set;}
public string Code {get; set;}
public string Param1 {get; set;}
public string Param2 {get; set;}
}
And this is the example:
string body = "My name is @UserName and my code is @Code";
param.UserName = "Tony";
param.Code = "A01";
What I want for result will be like My name is Tony and my code is A01
It is come from find body @UserName, and then replace from value Username Tony
A: you can use this code
List<EmailParam> param = new List<EmailParam>()
{
new EmailParam(){Code ="A01",UserName="Tony"},
new EmailParam(){Code ="B01",UserName="William"},
};
string body = "My name is @UserName and my code is @Code";
var findItem = param.Where(a => a.UserName.Equals("Tony") && a.Code.Equals("A01")).FirstOrDefault();
body = body.Replace("@UserName", findItem.UserName).Replace("@Code", findItem.Code);
A: You can use something similar to following
string body = "My name is {0} and my code is {1}"; //use placeholders instead of @UserName, @Code.
param.UserName = "Tony";
param.Code = "A01";
var convertedBody = String.Format(body, aram.UserName, param.Code);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66130713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Call another rest api from my server in Spring-Boot I want to call another web-api from my backend on a specific request of user. For example, I want to call Google FCM send message api to send a message to a specific user on an event.
Does Retrofit have any method to achieve this? If not, how I can do that?
A: Modern Spring 5+ answer using WebClient instead of RestTemplate.
Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).
@Bean
public WebClient localApiClient() {
return WebClient.create("http://localhost:8080/api/v3");
}
Inject and use the bean from your service(s).
@Service
public class UserService {
private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);
private final WebClient localApiClient;
@Autowired
public UserService(WebClient localApiClient) {
this.localApiClient = localApiClient;
}
public User getUser(long id) {
return localApiClient
.get()
.uri("/users/" + id)
.retrieve()
.bodyToMono(User.class)
.block(REQUEST_TIMEOUT);
}
}
A: Create Bean for Rest Template to auto wiring the Rest Template object.
@SpringBootApplication
public class ChatAppApplication {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ChatAppApplication.class, args);
}
}
Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.
@RequestMapping(value = "/postdata",method = RequestMethod.POST)
public String PostData(){
return "{\n" +
" \"value\":\"4\",\n" +
" \"name\":\"David\"\n" +
"}";
}
@RequestMapping(value = "/post")
public String getPostResponse(){
HttpHeaders headers=new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity=new HttpEntity<String>(headers);
return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
}
Refer this tutorial[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm
A: As has been mentioned in the various answers here, WebClient is now the recommended route.
You can start by configuring a WebClient builder:
@Bean
public WebClient.Builder getWebClientBuilder(){
return WebClient.builder();
}
Then inject the bean and you can consume an API as follows:
@Autowired
private WebClient.Builder webClientBuilder;
Product product = webClientBuilder.build()
.get()
.uri("http://localhost:8080/api/products")
.retrieve()
.bodyToMono(Product.class)
.block();
A:
Does Retrofit have any method to achieve this? If not, how I can do that?
YES
Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.
For more information refer the following link
https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial
A: This website has some nice examples for using spring's RestTemplate.
Here is a code example of how it can work to get a simple object:
private static void getEmployees()
{
final String uri = "http://localhost:8080/springrestexample/employees.xml";
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject(uri, String.class);
System.out.println(result);
}
A: Instead of String you are trying to get custom POJO object details as output by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,
In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,
@Autowired
private RestTemplate restTemplate;
Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.
ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
URL,
HttpMethod.GET,
null,
new ParameterizedTypeReference<List<POJO>>() {
});
List<POJO> pojoObjList = responseEntity.getBody();
Happy Coding :)
A: In this case need download whit my API, files hosted in other server.
In my case, don't need use a HTTP client to download the file in a external URL, I combined several answers and methods worked in previous code for files that were in my local server.
My code is:
@GetMapping(value = "/download/file/pdf/", produces = MediaType.APPLICATION_PDF_VALUE)
public ResponseEntity<Resource> downloadFilePdf() throws IOException {
String url = "http://www.orimi.com/pdf-test.pdf";
RestTemplate restTemplate = new RestTemplate();
byte[] byteContent = restTemplate.getForObject(url, String.class).getBytes(StandardCharsets.ISO_8859_1);
InputStream resourceInputStream = new ByteArrayInputStream(byteContent);
return ResponseEntity.ok()
.header("Content-disposition", "attachment; filename=" + "pdf-with-my-API_pdf-test.pdf")
.contentType(MediaType.parseMediaType("application/pdf;"))
.contentLength(byteContent.length)
.body(new InputStreamResource(resourceInputStream));
}
and it works with HTTP and HTTPS urls!
A: Since the question explicitly tags spring-boot, it worth noting that recent versions already ship a pre-configured instance of a builder for WebClient, thus you can directly inject it inside your service constructor without the needing to define a custom bean.
@Service
public class ClientService {
private final WebClient webClient;
public ClientService(WebClient.Builder webClientBuilder) {
webClient = webClientBuilder
.baseUrl("https://your.api.com")
}
//Add all the API call methods you need leveraging webClient instance
}
https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-webclient.html
A: Simplest way I have found is to:
*
*Create an annotated interface (or have it generated from somehing like OpenAPI)
*Give that interface to Spring RestTemplate Client
The Spring RestTemplate Client will parse the annotations on the interface and give you a type safe client, a proxy-instance. Any invocation on the methods will be seamlessly translated to rest-calls.
final MyApiInterface myClient = SpringRestTemplateClientBuilder
.create(MyApiInterface.class)
.setUrl(this.getMockUrl())
.setRestTemplate(restTemplate) // Optional
.setHeader("header-name", "the value") // Optional
.setHeaders(HttpHeaders) // Optional
.build();
And a rest call is made by inoking methods, like:
final ResponseEntity<MyDTO> response = myClient.getMyDto();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42365266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "115"
}
|
Q: how to take input in python when no of input are not defined this is an c++ code , how can I implement this in python ?
while(scanf("%lld",&n)!=EOF)
{
cout<<convert(n)<<endl;
}
A: This is roughly equivalent:
def convert(input):
#do something with your input
import sys
for line in sys.stdin:
convert(int(line))
A: In Python, instead of using scanf and friends, usually you read a line or an entire file into a string, and use string operations to get the results you want.
In your example, you could do something like:
import sys
for line in sys.stdin:
for word in line.split():
number = int(word)
... = convert(number)
A: it can be done using try except
link below can be used
https://stackoverflow.com/a/38621838/4557946
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31644677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: matplotlib.plot.show continues shows plots even the script finished There isn't duplicated answer because I was always blocked by solution below !!!!!!!
I want to plot a graph and still run following code without closing the graph automatically like Matlab.
I try plt.show(block=False) , it failed and appear in a small moment then close itself.
Code:
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
plt.figure(figsize=(10, 10))
plt.plot(range(5), lw=2, label='Real')
plt.title('Prediction')
plt.legend(loc="best")
plt.show(block=False)
print("---Plot graph finish---")
I try plt.draw() or interactive mode , it failed, too. Check the code below.
Code:
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
plt.figure(figsize=(10, 10))
plt.plot(range(5), lw=2, label='Real')
plt.title('Prediction')
plt.legend(loc="best")
plt.draw()
plt.show()
print("---Plot graph finish---")
Above will block until I close it.
Code:
import numpy as np
import matplotlib.pyplot as plt
if __name__ == '__main__':
plt.ion()
plt.figure(figsize=(10, 10))
plt.plot(range(5), lw=2, label='Real')
plt.title('Prediction')
plt.legend(loc="best")
plt.draw()
plt.show()
print("---Plot graph finish---")
Above will appear nothing, or it appear and disappear very fast.
My version is below:
user@ya:~/$ sudo pip freeze | grep matplotlib
matplotlib==2.2.3
user@ya:~/$ sudo pip -V
pip 18.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)
Environments:
I only execute script in Ubuntu ex: user@ya: python xxx.py
Distributor ID: Ubuntu
Description: Ubuntu 16.04.5 LTS
Release: 16.04
Codename: xenial
Can anyone help me? I just want to do like Matlab which won't close the plotted graph even if the script finishes.
A: The plots will close when the script is finished, even if you use block=False
Similar to the answer here, when running from the terminal you have to call plt.show at the end of the script to keep these plots open after you've finished. I made a similar code to yours which works as intended; the plot simply refreshes at the end of the code. (added a for loop for a 5 second delay just so you can see it's running).
import numpy as np
import matplotlib.pyplot as plt
import time
if __name__ == '__main__':
plt.figure(figsize=(10, 10))
plt.plot(range(5), lw=2, label='Real')
plt.title('Prediction')
plt.legend(loc="best")
plt.show(block=False)
print("---Plot graph finish---")
for i in range(5):
print('waiting...{}'.format(i))
time.sleep(1)
print('code is done')
plt.show()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53097475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Slide out animation of three elements on top of each other I'm looking for the best way to make the following animation. I've tried some solutions, but none of them seem to tackle my problem as every single solution seems to fail at some point. The animation I need to do is the following:
User swipes his finger up and the tableView & 1 & 2 scroll up (it's like tableView & 1 & 2 are one scrollable element). Then, when 2 becomes invisible upon the scroll, 3 & 1 & tableView become scrollable (again, as if it were one scrollable element). Then, when 3 becomes invisible (as it is scrolled) the tableView is then the only scrollable element.
What I tried:
*
*I initially tried with simple animations like changing height constraints for every 1/2/3 element based on the scroll offset and although it seemed fine to me, it didn't to the reviewer as he wanted more precise scrolling in between hiding elements animations
*I then tried to combine panGesture with scroll. I embedded 1 & 2 and tableView into one scroll View and set panGesture recognizer for it with delegate function shouldRecognizeSimultaneouslyWith returning true while having tableView scrolling disabled. Then, upon intersecting 3 I was disabling the panGesture and tried to enable tableView scrolling, but failed to recognize which panGesture/scrolling works or not, which one to disable, which one to fail or work alone/simultaneously.
How would you dear developers tackle it so that the animations are smooth and as described? Perhaps, you have an awesome idea :)
A: I'm using a simplified version of your idea with a UIScrollView & 3 UILabel instances.
You can easily adapt this to be UITableView & 3 UIView instances.
Idea
*
*UIScrollView & 3 UILabel instances have a common superview. In this case it's UIViewController.view.
*UIScrollView is laid out to be full screen (edge-to-edge) and extends below these 3 UILabel instances.
*UIScrollView has contentInset.top = height_of_three_labels so it's content starts below these other instances.
*Whenever UIScrollView.contentOffset changes, we shift frame.origin.y for these 3 instances to provide the needed effect.
UI Setup
import UIKit
class ViewController: UIViewController {
let tileHeight: CGFloat = 60
let view1 = UILabel()
let view2 = UILabel()
let view3 = UILabel()
override func viewDidLoad() {
super.viewDidLoad()
let bounds = self.view.bounds
let scrollView = UIScrollView(frame: bounds)
scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
scrollView.delegate = self
scrollView.alwaysBounceVertical = true
self.view.addSubview(scrollView)
view1.frame = CGRect(x: 0, y: 2*tileHeight, width: bounds.width, height: tileHeight)
configureLabel(view1, text: "1", backgroundColor: .red)
view2.frame = CGRect(x: 0, y: tileHeight, width: bounds.width, height: tileHeight)
configureLabel(view2, text: "2", backgroundColor: .blue)
view3.frame = CGRect(x: 0, y: 0, width: bounds.width, height: tileHeight)
configureLabel(view3, text: "3", backgroundColor: .green)
scrollView.contentInset = UIEdgeInsets(top: 3*tileHeight, left: 0, bottom: 0, right: 0)
// 3 is between 2 and 1, 1 is at the top, order is important here
self.view.addSubview(view2)
self.view.addSubview(view3)
self.view.addSubview(view1)
}
private func configureLabel(_ label: UILabel, text: String, backgroundColor: UIColor) {
label.text = text
label.textColor = .white
label.font = .boldSystemFont(ofSize: 34)
label.textAlignment = .center
label.backgroundColor = backgroundColor
}
}
Scroll Management
extension ViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.adjustedContentInset.top + scrollView.contentOffset.y
print(offset)
if offset > 0 {
view3.frame.origin.y = (offset > tileHeight) ? (tileHeight - offset) : 0
view2.frame.origin.y = tileHeight - offset
view1.frame.origin.y = 2*tileHeight - offset
}
else {
view3.frame.origin.y = 0
view2.frame.origin.y = tileHeight
view1.frame.origin.y = 2*tileHeight
}
}
}
Output
A: I think you'll be fighting a losing battle trying to toggle scrolling.
Here's another approach...
*
*add the tableView as a subview of a "container" UIView
*add the three "top" views as subviews
*give the tableView a contentInset.top of the height of the three views plus vertical spacing
*constrain the three "top" views so
*
*3 will stick to the top, until it is pushed up by 1
*2 till slide under 3 when 1 pushes it up
*update the top constraint for 1 when the tableView scrolls
You can try it with this example code (no @IBOutlet connections needed):
class ExampleViewController: UIViewController, UIScrollViewDelegate {
let tableView: UITableView = {
let v = UITableView()
v.translatesAutoresizingMaskIntoConstraints = false
v.separatorInset = .zero
return v
}()
let view1: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.textAlignment = .center
v.backgroundColor = .systemRed
v.text = "1"
return v
}()
let view2: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.textAlignment = .center
v.backgroundColor = .systemGreen
v.text = "2"
return v
}()
let view3: UILabel = {
let v = UILabel()
v.translatesAutoresizingMaskIntoConstraints = false
v.textAlignment = .center
v.backgroundColor = .systemBlue
v.text = "3"
return v
}()
// this will hold the tableView and the
// three other views
let containerView: UIView = {
let v = UIView()
v.translatesAutoresizingMaskIntoConstraints = false
// clip to bounds to prevent the "top" views from showing
// as they are "pushed up" out of bounds
v.clipsToBounds = true
return v
}()
// this constraint constant will be changed
// in scrollViewDidScroll
@IBOutlet var view1TopConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
// add our container view
view.addSubview(containerView)
// add our tableView and three "top" views
containerView.addSubview(tableView)
containerView.addSubview(view2)
containerView.addSubview(view3)
containerView.addSubview(view1)
for v in [view1, view2, view3] {
// all three "top" views should be
// equal width to tableView
// horizontally centered to tableView
// 40-pts tall
NSLayoutConstraint.activate([
v.widthAnchor.constraint(equalTo: tableView.widthAnchor),
v.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
v.heightAnchor.constraint(equalToConstant: 40.0),
])
}
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// constrain container view with 20-pts "padding"
containerView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
containerView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),
// constrain all 4 sides of tableView ot container view
tableView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0),
tableView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0.0),
tableView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0.0),
tableView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0.0),
])
// view3 should stick to the top of the table,
// unless it's being pushed up by view1
let v3Top = view3.topAnchor.constraint(equalTo: tableView.topAnchor)
v3Top.priority = .defaultHigh + 1
// view2 should stick to the bottom of view3,
// unless it's being pushed up by view1
let v2Top = view2.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 4.0)
v2Top.priority = .defaultHigh
// view1 should ALWAYS be 4-pts from bottom of view2
let v1TopA = view1.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 4.0)
v1TopA.priority = .required
// view1 should ALWAYS be greater-than-or-equal 4-pts from bottom of view3
let v1TopB = view1.topAnchor.constraint(greaterThanOrEqualTo: view3.bottomAnchor, constant: 4.0)
v1TopB.priority = .required
// view1 top should ALWAYS be greater-than-or-equal top of tableView
let v1TopC = view1.topAnchor.constraint(greaterThanOrEqualTo: tableView.topAnchor)
v1TopC.priority = .required
// 88-pts is 40-pts for view3 and view2 plus 4-pts vertical spacing
// view1 top should NEVER be more-than 88-pts from top of tableView
let v1TopD = view1.topAnchor.constraint(lessThanOrEqualTo: tableView.topAnchor, constant: 88.0)
v1TopD.priority = .required
// view1 top will start at 88-pts from top of tableView
view1TopConstraint = view1.topAnchor.constraint(equalTo: tableView.topAnchor, constant: 88.0)
view1TopConstraint.priority = .defaultHigh + 2
// activate those constraints
NSLayoutConstraint.activate([
v3Top,
v2Top,
v1TopA,
v1TopB,
v1TopC,
v1TopD,
view1TopConstraint,
])
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.dataSource = self
tableView.delegate = self
// top inset is
// three 40-pt tall views
// plus 4-pts vertical spacing between each
// and 4-pts vertical spacing below view1
tableView.contentInset.top = 132
tableView.contentOffset.y = -132
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// we're getting called when the tableView scrolls
// invert the contentOffset y
let y = -scrollView.contentOffset.y
// subtract 44-pts (40-pt tall view plus 4-pts vertical spacing)
view1TopConstraint.constant = y - 44.0
}
}
extension ExampleViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 30
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let c = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
c.textLabel?.text = "Row \(indexPath.row)"
return c
}
}
Here's how it looks to start:
then, after scrolling up just a bit (2 is sliding under 3):
scrolling a bit more (1 is pushing 3 up and out of view):
and then table scrolling while 1 remains at the top:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68267556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Building a nested HashMap I want to build a nested hashmap in java like this
{Customer:
{
Area:{}
}
Bank:
{
City:{}
}
}
How can i do this?
A: The easiest way is to use a map as the value of your outer map, like the following:
Map<String, Map<String, String>> nestedMap = new HashMap<> ();
Map<String, String> fooInnerMap = new HashMap<> (), barInnerMap = new HashMap<> ();
nestedMap.put ("foo", fooInnerMap);
nestedMap.put ("bar", barInnerMap);
However, this is not really convenient to use. If you want better answers, please specify what you want and what you tried.
Your data structure, for example, looks like JSON. If you need your Map to save or exchange data, you could use a JSON library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31812348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: React Material UI 2 TableRows in one loop error I'm making my first project in React and I have a problem rendering my table correctly.
What I'm trying to achieve is this;
The green brackets are what's inside my loop. The problem is that REACT says I need a wrapper for my TableRow-elements. I would assume my wrapper is my TableBody. The return method of my table looks like this;
return(
<div className="container">
<Table>
<TableHead>
<TableRow>
{this.props.headers.map((el, i) =>
<TableCell key={i+3}>{el}</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{this.props.data.map((element, j) =>
<TableRow key={j+j+j+j+j}>
<TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
<TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
<TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
<TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
{toolTip[j]}
</TableCell>
</TableRow>
<TableRow> !!REACT WON'T ACCEPT THIS SECOND TABLEROW!! </TableRow>
)}
</TableBody>
</Table>
</div>
)
The error is the following;
Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment < >...< />?
What I've tried so far is wrap both TableRows of this loop in a parent TableRow, but Table rows cannot directly contains Table rows, of course.
Any help is greatly appreciated!
A: In react some things (almost everything) needs the same start and end tag to be valid, take a return for example, this is valid:
export default observer(() => {
return (
<div>
<h1>Hello</h1>
</div>
)
})
This will reslut in a error
export default observer(() => {
return (
<h1>Hello</h1>
<div>
</div>
)
})
So what you can do is to use the <React.Fragment>tag around all code in your loop, or simply use a loop foreach block. This is valid
export default observer(() => {
return (
<React.Fragment>
<h1>Hello</h1>
<div>
</div>
</React.Fragment>
)
})
Your code with fragment
return(
<div className="container">
<Table>
<TableHead>
<TableRow>
{this.props.headers.map((el, i) =>
<TableCell key={i+3}>{el}</TableCell>
)}
</TableRow>
</TableHead>
<TableBody>
{this.props.data.map((element, j) =>
<React.Fragment>
<TableRow key={j+j+j+j+j}>
<TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
<TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
<TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
<TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
{toolTip[j]}
</TableCell>
</TableRow>
<TableRow> !!REACT WILL ACCEPT THIS SECOND TABLEROW!! </TableRow>
</React.Fragment>
)}
</TableBody>
</Table>
</div>
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59067511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: iOS CoreBluetooth CBPeripheral didReceiveReadRequest I have two projects. One acts as central ,the other as a peripheral. Central has connected to peripheral, then central calls method readValueForCharacteristic.
Not immediately, but after about 5-10 seconds, peripheral invokes delegate method - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request. Why is there a delay? How can I eliminate the delay?
Any thoughts? I've been trying for almost a week now.
Appreciate every helps, thanks
central
- (void)sendBtnClick:(id)sender
{
USCPeerBtn *btn = (USCPeerBtn *)sender;
CBPeripheral *peripheral = btn.connectedPeripheral;
if (!peripheral) {
return;
}
[self.charachterMDict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
if (key == peripheral) {
[(CBPeripheral *)key readValueForCharacteristic:(CBCharacteristic *)obj]; // read
*stop = YES;
}
}];
}
periperal
// CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
{
NSLog(@"didReceiveReadRequest");
}
A: Call respondToRequest: in method - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
// CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request
{
[peripheral respondToRequest:request withResult:CBATTErrorSuccess];
NSLog(@"didReceiveReadRequest");
}
@Paulw11 ,thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33647572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I make a path for a folder on the root? Here is my directory:
/myweb
/css
style.css
/img
icon.png
index.php
.htaccess
I need to call icon.png in style.css. I've tested lots of cases but none of these works:
// style.css
url(../img/icon.png)
url(./img/icon.png)
url(/img/icon.png)
url(img/icon.png)
url(../icon.png)
url(./icon.png)
Does anybody know what's the correct path?
A: Calling url(../img/icon.png) is correct.
Did you try to call the image from somewhere else, in example for background:
body {
background-image: url(../img/icon.png);
}
Also please check the configuration in your .htaccess.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41893854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Extracting text from PDF file using pdfbox I am trying to extract text from PDF file using pdfbox but not as a command line tool but inside my Java app. I am downloading pdf using jsoup.
res = Jsoup
.connect(host+action)
.ignoreContentType(true)
.data(data)
.cookies(cookies)
.method(Method.POST)
.timeout(20*1000)
.execute();
// prepare document
InputStream is = new ByteArrayInputStream(res.bodyAsBytes());
PDDocument pdf = new PDDocument();
pdf.load(is,true);
// extract text
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(pdf);
// print extracted text
System.out.println(text);
This code prints just empty line. When I do this:
System.out.println(res.body());
it prints the pdf file to output like this:
%PDF-1.4
%����
6 0 obj
<<
/Filter /FlateDecode
/Length 1869
>>
stream
x��X�n��
...
<<
/Size 28
/Info 27 0 R
/Root 26 0 R
>>
startxref
20632
%%EOF
So I am sure that pdf in downloaded correctly - just this PDF stripper doesnt work...
---------------------------------------------- edit
this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/
A: (Question answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) )
@WeloSefer wrote:
maybe this can help you get started ... I have never worked with jsoup nor pdfbox so I am no help but I sure will try pdfbox since I've been testing itextpdf reader for extracting texts.
The OP wrote:
Thanks, that is what I was looking for - it works now :)
this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14354427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to solve the no mono behavior script found error in unity? I have a problem with a game I am programming in unity. This specificaly occured when i added the script given below. the error message says that no monobehaviorscripts in the file, or their names do not match the file name. This script is meant to spawn the eniemies in the game.
I have already tried changing the class name, file name and copy the one into the other. but this does not seem to help.
screenshot unity of error message and code
i just edited my code and it does not seem to be solved.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class wavesystem : MonoBehaviour
{
public int enimicount;
public int[] enimi = { 1 };
public int wave = 1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (enimicount = 0)
{
int threat = 0;
for (threat < wavesystem.wave)
{
int name = Random.Range(0, wavesystem.enimi.Length);
int enimitreat = wavesystem.enimi[name];
if (threat + enimitreat <= wave)
{
float xpos = Random.Range(0, 2);
Instantiate("enimie" + name, (xpos, 1));
wavesystem.enimicount = wavesystem.enimicount + 1;
threat = threat + enimitreat;
}
}
wavesystem.wave = wavesystem.wave + 1;
}
}
}
A: you need the exact same name in the unity editor for the script as well as in the code editor (I suppose visual studio). the name is Case Sensitive and needs to be correctly spelled in each part. check the name and the location of the file and place them so they are easily found by you.
for example:
Name in unity: WaveSystem_LoL
//Name in C# code:
public class WaveSystem_LoL : MonoBehavior
if they do not match the error will appear so double and even triple check!
A: Seems like your file name is different than class name. Your file name of cs file should be wavesystem.cs
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65089036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel 5 shows php file content in browser (doesn't render html) Laravel 5 site doesn't render html, rather it shows php file content in browser. I tried various apache configurations and changes in htaccess but no luck. Not sure where this is going wrong.
Here is the .htaccess file
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
DirectoryIndex index.php
RewriteEngine On
# Redirect Trailing Slashes...
#RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ public/$1 [L]
# RewriteRule ^ index.php [L]
</IfModule>
and here is the apache conf file:
<VirtualHost *:80>
DocumentRoot /var/www/laravelapp/public
ServerName laravelapp.dev
ServerAlias laravelapp.dev
<Directory "/var/www/laravelapp/public">
AllowOverride all
Allow from all
</Directory>
</VirtualHost>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31188276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: AOSP - Android 6 Marshmallow compilation - make: *** [run_soong] Error 126 I've tried to compile Android 6 Marshmallow for my Sony Xperia Z1 Compact.
I've done everything what was in:
How to build AOSP Marshmallow for unlocked Xperia devices (developer.sonymobile.com)
and checking out:
Android - Downloading and Building (source.android.com)
on virtual machine with newest Debian (32-bit), but when I was on
To start the build, type: make –j < insert the cpu thread number of
your computer >
I've received an error:
root@debian:~/android# make –j 8
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=6.0.1
TARGET_PRODUCT=aosp_d5503
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a-neon
TARGET_CPU_VARIANT=krait
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86
HOST_2ND_ARCH=
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.5.0-2-686-pae-i686-with-debian-stretch-sid
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=MASTER
OUT_DIR=out
============================================
out/soong/soong: line 43: prebuilts/build-tools/linux-x86/bin/ninja: cannot execute binary file: Exec format error
build/core/soong.mk:87: recipe for target 'run_soong' failed
make: *** [run_soong] Error 126
#### make failed to build some targets (1 seconds) ####
Debug info:
root@debian:~/android# make -nd –j 8
GNU Make 4.1
Built for i586-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Reading makefiles...
Reading makefile 'Makefile'...
(...)
Reading makefile 'build/core/dumpvar.mk' (search path) (no ~ expansion)...
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=6.0.1
TARGET_PRODUCT=aosp_d5503
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a-neon
TARGET_CPU_VARIANT=krait
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86
HOST_2ND_ARCH=
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.5.0-2-686-pae-i686-with-debian-stretch-sid
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=MASTER
OUT_DIR=out
============================================
Reading makefile 'build/core/ninja.mk' (search path) (no ~ expansion)...
Reading makefile 'build/core/soong.mk' (search path) (no ~ expansion)...
Reading makefile 'vendor/google/build/ninja_config.mk' (search path) (do not care) (no ~ expansion)...
Updating makefiles....
Considering target file 'vendor/google/build/ninja_config.mk'.
File 'vendor/google/build/ninja_config.mk' does not exist.
Looking for an implicit rule for 'vendor/google/build/ninja_config.mk'.
No implicit rule found for 'vendor/google/build/ninja_config.mk'.
Finished prerequisites of target file 'vendor/google/build/ninja_config.mk'.
Must remake target 'vendor/google/build/ninja_config.mk'.
Failed to remake target file 'vendor/google/build/ninja_config.mk'.
Considering target file 'build/core/soong.mk'.
Looking for an implicit rule for 'build/core/soong.mk'.
No implicit rule found for 'build/core/soong.mk'.
Finished prerequisites of target file 'build/core/soong.mk'.
No need to remake target 'build/core/soong.mk'.
Considering target file 'build/core/ninja.mk'.
Looking for an implicit rule for 'build/core/ninja.mk'.
No implicit rule found for 'build/core/ninja.mk'.
Finished prerequisites of target file 'build/core/ninja.mk'.
No need to remake target 'build/core/ninja.mk'.
Considering target file 'build/core/dumpvar.mk'.
Looking for an implicit rule for 'build/core/dumpvar.mk'.
No implicit rule found for 'build/core/dumpvar.mk'.
Finished prerequisites of target file 'build/core/dumpvar.mk'.
(...)
No need to remake target 'build/core/main.mk'.
Considering target file 'Makefile'.
Looking for an implicit rule for 'Makefile'.
No implicit rule found for 'Makefile'.
Finished prerequisites of target file 'Makefile'.
No need to remake target 'Makefile'.
Updating goal targets....
Considering target file '–j'.
File '–j' does not exist.
Considering target file 'ninja_wrapper'.
File 'ninja_wrapper' does not exist.
Considering target file 'out/combined-aosp_d5503.ninja'.
File 'out/combined-aosp_d5503.ninja' does not exist.
Considering target file 'out/build-aosp_d5503.ninja'.
File 'out/build-aosp_d5503.ninja' does not exist.
Considering target file 'prebuilts/build-tools/linux-x86/bin/ckati'.
Looking for an implicit rule for 'prebuilts/build-tools/linux-x86/bin/ckati'.
No implicit rule found for 'prebuilts/build-tools/linux-x86/bin/ckati'.
Finished prerequisites of target file 'prebuilts/build-tools/linux-x86/bin/ckati'.
No need to remake target 'prebuilts/build-tools/linux-x86/bin/ckati'.
Considering target file 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
Looking for an implicit rule for 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
No implicit rule found for 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
Finished prerequisites of target file 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
No need to remake target 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
Considering target file 'out/Android.mk'.
Finished prerequisites of target file 'out/Android.mk'.
No need to remake target 'out/Android.mk'.
Considering target file 'out/CleanSpec.mk'.
Finished prerequisites of target file 'out/CleanSpec.mk'.
No need to remake target 'out/CleanSpec.mk'.
Considering target file 'run_soong'.
File 'run_soong' does not exist.
Considering target file 'out/soong/.soong.bootstrap'.
Considering target file 'bootstrap.bash'.
Looking for an implicit rule for 'bootstrap.bash'.
No implicit rule found for 'bootstrap.bash'.
Finished prerequisites of target file 'bootstrap.bash'.
No need to remake target 'bootstrap.bash'.
Finished prerequisites of target file 'out/soong/.soong.bootstrap'.
Prerequisite 'bootstrap.bash' is older than target 'out/soong/.soong.bootstrap'.
No need to remake target 'out/soong/.soong.bootstrap'.
Considering target file 'out/soong/soong.variables'.
Considering target file 'FORCE'.
File 'FORCE' does not exist.
Finished prerequisites of target file 'FORCE'.
Must remake target 'FORCE'.
Successfully remade target file 'FORCE'.
Finished prerequisites of target file 'out/soong/soong.variables'.
Prerequisite 'FORCE' of target 'out/soong/soong.variables' does not exist.
Must remake target 'out/soong/soong.variables'.
mkdir -p out/soong/
(\
echo '{'; \
echo ' "Make_suffix": "-aosp_d5503",'; \
echo ''; \
echo ' "Platform_sdk_version": 23,'; \
echo ' "Unbundled_build": false,'; \
echo ' "Brillo": false,'; \
echo ' "Malloc_not_svelte": true,'; \
echo ' "Allow_missing_dependencies": false,'; \
echo ' "SanitizeHost": [],'; \
echo ' "SanitizeDevice": [],'; \
echo ' "HostStaticBinaries": false,'; \
echo ''; \
echo ' "DeviceName": "amami",'; \
echo ' "DeviceArch": "arm",'; \
echo ' "DeviceArchVariant": "armv7-a-neon",'; \
echo ' "DeviceCpuVariant": "krait",'; \
echo ' "DeviceAbi": ["armeabi-v7a", "armeabi"],'; \
echo ' "DeviceUsesClang": true,'; \
echo ''; \
echo ' "DeviceSecondaryArch": "",'; \
echo ' "DeviceSecondaryArchVariant": "",'; \
echo ' "DeviceSecondaryCpuVariant": "",'; \
echo ' "DeviceSecondaryAbi": ["", ""],'; \
echo ''; \
echo ' "HostArch": "x86",'; \
echo ' "HostSecondaryArch": "",'; \
echo ''; \
echo ' "CrossHost": "windows",'; \
echo ' "CrossHostArch": "x86",'; \
echo ' "CrossHostSecondaryArch": "x86_64",'; \
echo ' "Safestack": false'; \
echo '}') > out/soong/soong.variables.$$; \
if ! cmp -s out/soong/soong.variables.$$ out/soong/soong.variables; then \
mv out/soong/soong.variables.$$ out/soong/soong.variables; \
else \
rm out/soong/soong.variables.$$; \
fi
Successfully remade target file 'out/soong/soong.variables'.
Considering target file 'out/soong/.soong.in_make'.
Finished prerequisites of target file 'out/soong/.soong.in_make'.
No need to remake target 'out/soong/.soong.in_make'.
Pruning file 'FORCE'.
Finished prerequisites of target file 'run_soong'.
Must remake target 'run_soong'.
out/soong/soong out/soong/build.ninja -w dupbuild=err
Successfully remade target file 'run_soong'.
Pruning file 'FORCE'.
Finished prerequisites of target file 'out/build-aosp_d5503.ninja'.
Must remake target 'out/build-aosp_d5503.ninja'.
echo Running kati to generate build-aosp_d5503.ninja...
prebuilts/build-tools/linux-x86/bin/ckati --ninja --ninja_dir=out --ninja_suffix=-aosp_d5503 --regen --ignore_dirty=out/% --no_ignore_dirty=out/soong/Android-aosp_d5503.mk --no_ignore_dirty=out/soong/make_vars-aosp_d5503.mk --ignore_optional_include=out/%.P --detect_android_echo --use_find_emulator -f build/core/main.mk --gen_all_targets BUILDING_WITH_NINJA=true SOONG_ANDROID_MK=out/soong/Android-aosp_d5503.mk SOONG_MAKEVARS_MK=out/soong/make_vars-aosp_d5503.mk
Putting child 0x94b8a18 (out/build-aosp_d5503.ninja) PID 8221 on the chain.
Live child 0x94b8a18 (out/build-aosp_d5503.ninja) PID 8221
/bin/bash: prebuilts/build-tools/linux-x86/bin/ckati: cannot execute binary file: Exec format error
Reaping losing child 0x94b8a18 PID 8221
build/core/ninja.mk:161: recipe for target 'out/build-aosp_d5503.ninja' failed
make: *** [out/build-aosp_d5503.ninja] Error 126
Removing child 0x94b8a18 PID 8221 from chain.
#### make failed to build some targets (1 seconds) ####
What should I do to compile this correctly?
A: This post is not going to be an answer, it didn't really solve the problem. The purpose is to provide more valuable information.
Create two symbolic links in your build top directory. It will get rid of the problem. Run following command in you build top directory.
$ ln -s build/soong/bootstrap.bash
$ ln -s build/soong/Android.bp
But as you go further, you will encounter problems like following
FAILED: out/soong/.bootstrap/bin/minibp -t -m ./build/soong/build.ninja.in -b out/soong -d out/soong/.bootstrap/bootstrap.ninja.in.d -o out/soong/.bootstrap/bootstrap.ninja.in Android.bp
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint"
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint-bootstrap"
[2/4] minibp out/soong/.bootstrap/primary.ninja.in
FAILED: out/soong/.bootstrap/bin/minibp --build-primary -t -m ./build/soong/build.ninja.in --timestamp out/soong/.bootstrap/primary.ninja.in.timestamp --timestampdep out/soong/.bootstrap/primary.ninja.in.timestamp.d -b out/soong -d out/soong/.bootstrap/primary.ninja.in.d -o out/soong/.bootstrap/primary.ninja.in Android.bp
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint"
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint-bootstrap"
ninja: error: rebuilding 'out/soong/build.ninja': subcommand failed
make: *** [run_soong] Error 1
I have no idea how to solve this either. Maybe the new build system for aosp master branch is not fully prepared.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37310667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: input type hidden attribute value missing when I inspect with Fiddler For the same request, the attrib value of tag input type=hidden is not displayed on the content (raw text) of the response using Fiddler and VStudio debugger. But when I inspect the code with Chrome it is displayed. Why does this happen? See these snapshots:
Element inspect from google
Inspector response content from Fiddler4
I'm a beginner in HTTP and HTML.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38109936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add a Hyperlink to a tab in Excel? I want to add a hyperlink to a Tab in Excel. Actually I want to do it as an Excel Add in?
But now it seems there is not option for it by customizing ribbon directly. I know there is document location with a drop down list. But I want a link to a URL. From what I know hyperlinks can be placed on cells only. Please give me some ideas.
A: What is a hyperlink, really? Its a text "button" that, when clicked, brings you to a website or opens a link of some sort.
So in this case, use a button in a tab on the Excel ribbon that when clicked brings you to a website. Easy:
Private Sub MyRibbonButton_Click(Byval sender as Object, Byval e as EventArgs) Handles MyRibbonButton.Click
System.Diagnostics.Process.Start("my website url")
End Sub
Does it look like a button? Of course, but essentially it's just a hyperlink, right?
A: Use a CustomUI to create buttons for macros:
'To send email
'Callback for customButton onAction
Sub MyWeb(control As IRibbonControl)
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
oShell.Run ("http://www.plugpro.com.br")
End Sub
'To Open URL
'Callback for customButton onAction
Sub MyWeb(control As IRibbonControl)
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
oShell.Run ("mailto:oton@podium.pro.br")
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17635315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jquery cross domain request? I just need a single digit returned, but I can't get it to work I am making a dashcode webapp and all I want is a single digit, a 1 or 0 returned from an external server so if there is an easier way to do this please let me know. I am using the plug in found at http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/ to try to make a cross domain request, but everything I am trying isn't working.
When I run this code
$.ajax({
url: "status.html",
context: document.body,
success: function(data){
alert("working" + data);
}
});
everything works perfectly and an alert with the text "working1" is displayed, but when I run this code
$.ajax({
url: "http://externalsite.com/status.html",
context: document.body,
success: function(data){
alert("working" + data);
}
});
nothing happens. Can anyone help? This is just what I am trying now, I've also tried a .get request and the returned data was "objectObject" I also tried a php proxy without any luck. I'm just asking for a simple solution to return a SINGLE number from an external server.
A: If you can control other server output, put header:
Access-Control-Allow-Origin: *
in http response, and load with ajax without plugins or using YQL
https://developer.mozilla.org/en/HTTP_access_control
A: It looks like the plugin is making a JSONP request via YQL (see line 18 here).
If you load up Firebug or the developer tools in Chrome, do you see the JSONP request being made?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6962917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Redirect to a specific page when WooCommerce product search returns "no product found" In Woocommerce I am trying to use the following code snippet to redirect to a specific page of my site instead of showing "no result found" on an empty product search.
Now the shortcode [insert page id="99"] doesn't work, and displays [insert page id="99"] as plain text. If I use shortcode any shortcode like '[recent_products per_page="4"]' it displays products.
remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );
add_action( 'woocommerce_no_products_found', 'show_products_on_no_products_found', 20 );
function show_products_on_no_products_found() {
echo '<h4>' . __( 'Are u looking for this?', 'domain' ) . '</h4>';
echo do_shortcode( '[insert page id="99"]' );
}
But I want is to redirect to a specific WordPress page which post id is 99.
How to redirect user to a specific page when a product search returns "no product found"?
A: Using template_redirect hook, you can redirect user to a specific page when there is "no results found" on a product query search, like:
add_action( 'template_redirect', 'no_products_found_redirect' );
function no_products_found_redirect() {
global $wp_query;
if( isset($_GET['s']) && isset($_GET['post_type']) && 'product' === $_GET['post_type']
&& ! empty($wp_query) && $wp_query->post_count == 0 ) {
wp_redirect( get_permalink( 99 ) );
exit();
}
}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62404641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Turn "fieldname .startsWith. 'fieldValue'" into .Where(p => p.fieldname.StartsWith('fieldValue')) predicate? I attempted to do this below, with mind blanks as it got complicated.
I need to build a predicate to pass to my Product Repository from a client string:
"fieldname .startsWith. 'fieldvalue'"
"fieldname .contains. 'fieldvalue'"
"fieldname .equals. 3"
"fieldname .greaterThan. 3"
"fieldname .lessThan. 3"
The field names could be any existing field in the Entity. It's there job to match them exactly. There are only numbers and string, and only the commands listed.
Code so far (wild flailing):
// p => p.L == R
// L is the left side (the field to examine)
// R is the right side (the value to compare to)
// O is the operator (Equal)
var fieldParm = Expression.Parameter(typeof(Entity), typeof(Entity).Name);
var compareL1 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR1 = Expression.Constant("fieldValue"); // what field should equal
var compareO1 = MemberExpression.Equal(compareWhat, compareTo);
// Do it again for each one (probably should make a foreach out of this)
var compareL2 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR2 = Expression.Constant("fieldValue"); // what field should equal
var compareO2 = MemberExpression.Equal(compareWhat, compareTo);
// Put them all together
var myExpress = Expression.And(compareO1, compareO2) // And them together
// Create predicate
Expression<Func<Entity, bool>> resultLambda =
Expression.Lambda<Func<Entity, bool>>( myExpress,
new ParameterExpression[] { fieldParm });
And resultLambda should contain our predicate to pass to our .Where() clause
How would you do this for a series of AND conditions like above?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4065454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding an Enter key to the end of scanned data I have Motorola MC32.. and Windows CE 7.
I intend to use Symbol.Barcode2 namespace and looking for the setting to set this data modifying rule.
There is the Datawedge preinstalled but I want to set the rule programmaticaly. I have found nothing in EMDK Help.
Could somebody help me where can I found this opportunity?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30772851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Xamarin Bluetooth. Show scan in popup menu and connect I'm programing a bluetooth controller for android. I've been able to switch the Bluetooth on and off, but now I need to scan the nearby devices. These I want to display as a popup menu as soon it finished scanning. Then you should click on the device you want and connect with it.
Note that it should connect also to not paired devices.
And the popup menu should be "big" like covering most of the screen... (not like the button-popup only)
namespace BluetoothController
{
[Activity(Label = "BluetoothController", MainLauncher = true)]
public class MainActivity : Activity, View.IOnTouchListener
{
BluetoothAdapter BTAdapter;
Button button_OnOff, button_Forward, button_Fire, button_Backward, button_Left, button_Right;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Initialize Components
Initialize();
// Get local Bluetooth Adapter
BTAdapter = BluetoothAdapter.DefaultAdapter;
}
public void Initialize()
{
button_OnOff = (Button)FindViewById(Resource.Id.button_onoff);
button_Forward = (Button)FindViewById(Resource.Id.button_forward);
button_Fire = (Button)FindViewById(Resource.Id.button_fire);
button_Backward = (Button)FindViewById(Resource.Id.button_backward);
button_Left = (Button)FindViewById(Resource.Id.button_left);
button_Right = (Button)FindViewById(Resource.Id.button_right);
button_OnOff.SetOnTouchListener(this);
button_Forward.SetOnTouchListener(this);
button_Backward.SetOnTouchListener(this);
button_Left.SetOnTouchListener(this);
button_Right.SetOnTouchListener(this);
button_Fire.SetOnTouchListener(this);
}
// Event handler for Buttons
public bool OnTouch(View v, MotionEvent e)
{
// Handle if Buttons is pressed or released
switch (e.Action)
{
case MotionEventActions.Down:
// Do if pressed
switch (v.Id)
{
case Resource.Id.button_forward:
break;
case Resource.Id.button_backward:
break;
case Resource.Id.button_left:
break;
case Resource.Id.button_right:
break;
case Resource.Id.button_fire:
break;
case Resource.Id.button_onoff:
break;
}
break;
case MotionEventActions.Up:
// Do if released
switch (v.Id)
{
case Resource.Id.button_forward:
break;
case Resource.Id.button_backward:
break;
case Resource.Id.button_left:
break;
case Resource.Id.button_right:
break;
case Resource.Id.button_fire:
break;
case Resource.Id.button_onoff:
if (BTAdapter != null)
{
if (!BTAdapter.IsEnabled)
{
BTAdapter.Enable();
Toast.MakeText(this, "Bluetooth enabled", ToastLength.Short).Show();
System.Threading.Thread.Sleep(5000);
// Display Devices and connect to the clicked one
}
else
{
BTAdapter.Disable();
Toast.MakeText(this, "Bluetooth disabled", ToastLength.Short).Show();
}
}
else
{
Toast.MakeText(this, "Bluetooth not supported", ToastLength.Long).Show();
}
break;
}
break;
}
return true;
}
}
}
After I turn on the Bluetooth in the event handler, it should wait a bit and display the selectable devices... this I did with System.Threading.Thread.sleep()
How can I take the discovered BT-devices and show them on the popup menu?
And how can I choose one of them to connect to it?
A: I think this could help you recognising bluetooth devices and managing them.
[BroadcastReceiver]
public class AndroidBluetooth : BroadcastReceiver
{
private static BluetoothDevice _bluetoothDevice;
private readonly BluetoothAdapter _bluetoothAdapter;
public BluetoothSocket _bluetoothSocket;
public readonly IntentFilter _intentFilter;
public AndroidBluetooth()
{
_bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
_intentFilter = new IntentFilter();
_intentFilter.AddAction(BluetoothDevice.ActionFound);
_intentFilter.AddAction(BluetoothDevice.ActionNameChanged);
_intentFilter.AddAction(BluetoothDevice.ActionBondStateChanged);
_intentFilter.AddAction(BluetoothDevice.ActionPairingRequest);
_intentFilter.AddAction(BluetoothDevice.ActionAclConnected);
_intentFilter.AddAction(BluetoothDevice.ActionAclDisconnected);
_intentFilter.AddAction(BluetoothDevice.ActionAclDisconnectRequested);
_intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryStarted);
_intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryFinished);
_intentFilter.AddAction(BluetoothAdapter.ActionRequestEnable);
Xamarin.Forms.Forms.Context.RegisterReceiver(this, _intentFilter);
}
public override void OnReceive(Context context, Intent intent)
{
try
{
BluetoothDevice item = null;
string action = intent.Action;
switch (action)
{
case BluetoothDevice.ActionPairingRequest:
try
{
//You can set device pin by default to avoid asking.
int pin = intent.GetIntExtra(BluetoothDevice.ExtraPairingKey, 1234);
_bluetoothDevice.SetPin(ASCIIEncoding.UTF8.GetBytes(pin.ToString()));
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
break;
case BluetoothDevice.ActionBondStateChanged:
break;
case BluetoothDevice.ActionFound:
//Bluetooth device found
/*/
/ Here you can make a list for preparing popup
/*/
break;
case BluetoothDevice.ActionNameChanged:
break;
case BluetoothAdapter.ActionDiscoveryFinished:
//Occurs when scan is finished
/*/
/ Launch desired popup
/*/
break;
case BluetoothDevice.ActionAclConnected:
//Bluettoth device is connected
break;
case BluetoothDevice.ActionAclDisconnected:
//Device is disconnected
break;
case BluetoothDevice.ActionAclDisconnectRequested:
break;
}
}
catch (Exception ex)
{
Logger.WriteException(ex);
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46425560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL workbench says bad handshake I tried connecting the database from the server, but MySQL Workbench says that the connection cannot be made and declaring it as Bad Handshake. Can someone help me with this? But if I use the same user id and password and DB connections, it works on the other computer systems. Can someone solve this issue?
A: The authentication has changed from mysql V8, you must use a compatible client and server.
BTW it's a bug : https://bugs.mysql.com/bug.php?id=91828
Here is a workaround without uninstalling the new workbench.
The most probable case is having an old server with a new workbench:
*
*get the server version
From a SQL cli tool:
SHOW VARIABLES LIKE "%version%";
or from a cli connected on the server:
$ mysql -v
It should show a version < 8.0, in my case 5.1.73
*Get the mysqlWorkbench for a version <8.0:
You cannot install the msi if you already have a workbench V8.0, so you have to choose a portable installation form a zip file here:
https://dev.mysql.com/downloads/workbench/6.1.html
Select the version 6.2.5 (last before v8.0) zip version
Unzip
Close the workbench v.8 (it lock any other workbench launch)
Launch the V6.2.3 version of workbench, it should works.
A: This is probably because of a mismatch in the versions of MySQL servers.
Check the version of the MySQL server you are trying to connect to, and the version you have installed on the computer you are using, they have to be the same.
A: The reason of this warning is version problem. If you have installed mysql server version <= 5.1 and your remote server mysql version is greater than that you will face this problem. I recommend you to install 5.7 or greater in both your local and remote server. This problem will be fixed.
A: Fortunately there is an easy way around this. Use the old MYSQL ADMINISTRATOR tool as shown below. In my case I was trying to open a MySQL 5.1 database for a clients WordPress installation with MySQL Workbench 8 and that did not work out :).
ALl credits goes to https://www.urtech.ca/2019/01/solved-bad-handshake-mysql-workbench-failed-to-connect-to-sql/
Follow this link for the details
https://www.urtech.ca/2019/01/solved-bad-handshake-mysql-workbench-failed-to-connect-to-sql/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55159619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to get the package name where error is triggered in Oracle Forms 6i I'm giving support on some oracle forms 6i forms, and I'm getting a Numeric or value error. However, the process is very long and it navigates along many packages in the form. What I could do, is just put messages along the process (only visible to me, of course) to see where exactly it comes out, but this would be really long. So, I was wondering if there is anything I could use like DBMS_UTILITY.format_error_backtrace but on the client side, and get the package name where the error was generated. I currently use:
exception when others then functionThatPrintsMe(sqlerrm);
But this does not give me enough information.
A: DBMS_ERROR_TEXT returns the entire sequence of recursive errors
so you should get all the required information from that
Kindly use
exception when others then functionThatPrintsMe(DBMS_ERROR_TEXT);
for more information about oracle 6i forms you can refer
http://www.oracle.com/technetwork/documentation/6i-forms-084462.html
A: At form level ON-ERROR TRIGGER .Add these lines will solve your problem
--form level error display
message(ERROR_type||'-'||TO_CHAR(message_code)||': '||ERROR_text); message(' ');
--Database level error display
if DBMS_ERROR_TEXT is not null then
message(DBMS_ERROR_TEXT );message(' ');
end if ;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9811526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I print scroll tab content with whole page?
As shown in an image I want to print the whole page with scroll content of tab. Currently the only visible screen content is being printed
A: You may use CSS media selectors to alter your styling for components when printing:
https://developer.mozilla.org/en-US/docs/Web/CSS/@media
It is perhaps the cleanest solution as it was meant for such situations. Ofc, it may require to address CSS for all the components on the page to make the outcome look as desired.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69659155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make a Ninja Form open up when you click on a bootstrap modal button (inside of a wordpress widget) I am using the following:
Ninja Version: 3.4.25 /
WordPress Version: 5.5 /
Bootstrap Version: 3 (or maybe 4)
I have a WordPress template based on bootstrap, and I am using the latest Ninja forms version.
I have created a Bootstrap button in a widget, that I want to open up a model window displaying my Ninja Contact form.
I have actually been successful with this setup with an older version of Ninja form. But since the latest updates, they have changed all their form field names, and so now it won't work on my new site, because I am not using the correct field names.
If anyone knows what the old field name: "ninja_forms_display_form" is now, then you don't have to read the rest of my documentation. I did try: "ninja_forms", but that didn't work either.
I will provide the coding I use on another site using the same template but using an older version of Ninja Forms (3.2.11). This modal button does work, and can be seen on the sidebar's green 'contact us' button here: www.oasisflighttraining.com.au/about-oasis-flying-school/
Here is the Sidebar Widgets code that uses the Bootstrap button:
<div class="im-centered">
<button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#contactform">Contact Us</button>
</div>
And here is the code that creates the Bootstrap button (found at the bottom of my footer.php file just before the call to wp_footer function.
<div class="modal fade" id="contactform">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Contact Us</h4>
</div>
<div class="modal-body">
<?php
if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }
?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
The code referencing "ninja_forms_display_form" is the part that doesn't work on my new site with the latest version of Ninja Forms. I know that field name has changed, but I can't figure out what to replace it with.
Can anyone give me some help figuring out how to make this bootstrap modal button work with my Ninja Form created with the updated version with new field names?
Thanks!
A: The newer Ninja Forms can use shortcode, so I just changed this:
<?php
if( function_exists( 'ninja_forms_display_form' ) ){ ninja_forms_display_form( 1 ); }
?>
to this:
<?php echo do_shortcode( '[ninja_form id=1]' ); ?>
(And as a public service advice.. just make sure that you don't have the bootstrap js pulled in twice, or the modal window won't stay displayed after you click the button. I found that the bootstrap shortcode plugin added another bootstrap.js)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63573513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Installed caret but still missing createDataPartition function in R I am new to R so I tried predicting using linear reg model and I am getting the error as shown in the image below, can you help me out?
Libraries included:
library(tidyverse)
library(ggplot2)
library(caret)
library(dplyr)
library(tidypredict)
png
A: Try running the library(caret) again, if the package is loaded, createDataPartition is there. If you still face the issue, check for Caret updates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67429488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Changing control group for Dunnett glht in multcomp I was wondering if anyone knows how to change between treatment groups for the control treatment for the Dunnett test in multcomp? A control treatment is selected by the first treatment alphabetically/numerically. I have several sets of data that I'd prefer not to go through editing if I can simply do it with code, plus I have two controls I'd like to compare my experimental treatments to.
For example, my "data"
TrtName Block Trt X3dpi X6dpi X12dpi
Neg_ctrl 1 1 1 4 8
Neg_ctrl 1 1 1 3 8
Neg_ctrl 1 1 2 4 9
Neg_ctrl 2 1 1 3 9
Neg_ctrl 2 1 1 4 8
Neg_ctrl 2 1 1 5 9
TC_ctrl 1 2 2 5 9
TC_ctrl 1 2 2 5 9
TC_ctrl 1 2 1 4 9
TC_ctrl 2 2 1 3 7
TC_ctrl 2 2 2 4 9
TC_ctrl 2 2 2 3 8
D_112 1 3 0 1 5
D_112 1 3 0 1 4
D_112 1 3 1 2 5
D_112 2 3 0 2 5
D_112 2 3 1 1 3
D_112 2 3 1 2 4
D_332 1 4 0 1 5
D_332 1 4 0 2 5
D_332 1 4 1 2 4
D_332 2 4 0 2 5
D_332 2 4 1 3 6
D_332 2 4 2 4 7
J_045 1 5 2 5 9
J_045 1 5 2 5 8
J_045 1 5 1 4 8
J_045 2 5 2 5 9
J_045 2 5 1 5 8
J_045 2 5 1 3 8
J_185 1 6 2 5 8
J_185 1 6 1 4
J_185 1 6 2 4 8
J_185 2 6 0 3 9
J_185 2 6 2 5 9
J_185 2 6 2 4 9
J_185 2 6 1 3 8
Code I'm using:
FHBficFit3dpi <- aov(X3dpi~ TrtName, FHBficData)
set.seed(115)
FHBficDunnett3dpi <- glht(model = FHBficFit3dpi, linfct=mcp(TrtName="Dunnett"))
summary(FHBficDunnett3dpi)
Results:
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Dunnett Contrasts
Fit: aov(formula = X3dpi ~ TrtName, data = FHBficData)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
D_332 - D_112 == 0 0.1667 0.3624 0.460 0.9873
J_045 - D_112 == 0 1.0000 0.3624 2.759 0.0390 *
J_185 - D_112 == 0 0.9286 0.3492 2.659 0.0489 *
Neg_ctrl - D_112 == 0 0.6667 0.3624 1.840 0.2534
TC_ctrl - D_112 == 0 1.1667 0.3624 3.219 0.0128 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
I realize changing the model to "X3dpi ~ Trt" would result in the correct comparison, but I'd like to compare each of the treatments to the TC_ctrl group as well.
A: Try this: change the order of the factors and put the group you want first:
FHBficData$TrtName<-factor(FHBficData$TrtName,levels=c("TC_ctrl","D_332","J_045","J_185","Neg_ctrl","D_112"),ordered=TRUE)
FHBficFit3dpi <- aov(X3dpi~ TrtName, FHBficData)
set.seed(115)
FHBficDunnett3dpi <- glht(model = FHBficFit3dpi, linfct=mcp(TrtName="Dunnett"))
summary(FHBficDunnett3dpi)
You'll get this:
Simultaneous Tests for General Linear Hypotheses
Multiple Comparisons of Means: Dunnett Contrasts
Fit: aov(formula = X3dpi ~ TrtName, data = FHBficData)
Linear Hypotheses:
Estimate Std. Error t value Pr(>|t|)
D_332 - TC_ctrl == 0 -1.0000 0.3624 -2.759 0.0391 *
J_045 - TC_ctrl == 0 -0.1667 0.3624 -0.460 0.9873
J_185 - TC_ctrl == 0 -0.2381 0.3492 -0.682 0.9361
Neg_ctrl - TC_ctrl == 0 -0.5000 0.3624 -1.380 0.5114
D_112 - TC_ctrl == 0 -1.1667 0.3624 -3.219 0.0128 *
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
(Adjusted p values reported -- single-step method)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47416577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 3ds max script make group by parents Hy!
I am not so well experienced with max script, but I have written/modified an exporter that can export single meshes, groups using the built in obj exporter.
Now I want to select parents(usually theese are not 3Dobjects) in hierarchy and convert them to groups with their parrents, and I have no idea how exatly I should do it.
Any suggestions maybe script code you know?
Thanks in advanced
A: You can get the parent of any object in the scene by using
myParent = $myObject.parent
And you can use the following line to get all of a parent's children:
myParent.children
so in combination with select and group methods, you can do the following:
myParent = $myObject.parent
select myParent
selectmore myParent.children
group (GetCurrentSelection() as array) name:"myGroup"
And now you have a group named myGroup containing a parent object and all of its children. With a little tinkering you can turn this into a method and also iterate through every object in your scene. Hope this helps you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25927273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C miscalculating distances I wrote some code in C to convert your distance to other distance units but it seems to mix up the numbers and miscalculate the result.
I use a Windows 10 laptop, but, I don't think it matters because I used an online compiler (GDB) to write the code. I really don't even know where is the problem.
#include <stdio.h>
int main ()
{
float distance;
char in_unit[20];
printf("Enter your distance:\n");
scanf("%f", &distance);
printf("Enter the length unit of your distance.(C=centimeters, Ft=feet, Kg=kilometers, In=inches, M=miles, Mtrs=meters)\n");
scanf("%s", in_unit);
if (in_unit == "Cm");
{
printf("Your distance in feet is:%f", distance/30.48);
printf("\nYour distance in kilometers is:%f", distance/100000);
printf("\nYour distance in inches is:%f", distance/2.54);
printf("\nYour distance in miles is:%f", distance/160934.4);
printf("\nYour distance in meters is:%f", distance/100);
}
if (in_unit == "Ft")
{
printf("Your distance in centimeters is:%f", distance*30.48);
printf("\nYour distance in kilometers is:%f", distance/3280.84);
printf("\nYour distance in inches is:%f", distance*12);
printf("\nYour distance in miles is:%f", distance/5280);
printf("\nYour distance in meters is:%f", distance/3.281);
}
if (in_unit == "Kg")
{
printf("Your distance in centimeters is:%f", distance * 100000);
printf("\nYour distance in feet is:%f", distance * 3280.84);
printf("\nYour distance in inches is:%f", distance * 39370.079);
printf("\nYour distance in miles is:%f", distance / 1.609);
printf("\nYour distance in meters is:%f", distance * 1000);
}
if (in_unit == "In")
{
printf("Your distance in centimeters is:%f", distance*2.54);
printf("\nYour distance in feet is:%f", distance/12);
printf("\nYour distance in kilometers is:%f", distance/39370.079);
printf("\nYour distance in miles is:%f", distance/63360);
printf("\nYour distance in meters is:%f", distance/39.37);
}
if (in_unit == "M")
{
printf("Your distance in centimeters is:%f", distance*160934.4);
printf("\nYour distance in feet is:%f", distance*5280);
printf("\nYour distance in kilometers is:%f", distance*1.609);
printf("\nYour distance in inches is:%f", distance*63360);
printf("\nYour distance in meters is:%f", distance*1609.344);
}
if (in_unit == "Mtrs")
{
printf("Your distance in centimeters is:%f", distance*100);
printf("\nYour distance in feet is:%f", distance*3.281);
printf("\nYour distance in kilometers is:%f", distance/1000);
printf("\nYour distance in inches is:%f", distance*39.37);
printf("\nYour distance in miles is:%f", distance/1609.344);
}
return 0;
}
For example, this is one of the runs:
Enter your distance:
1
Enter the length unit of your distance. (C=centimeters, Ft=feet, Kg=kilometers, In=inches, M=miles, Mtrs=meters)
Kg
Your distance in feet is:0.032808
Your distance in kilometers is:0.000010
Your distance in inches is:0.393701
Your distance in miles is:0.000006
Your distance in meters is:0.010000
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54426794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET MVC Uploading with Extra Data and Jquery I am following an example from another question for uploading with jQuery.
http://aspzone.com/tech/jquery-file-upload-in-asp-net-mvc-without-using-flash/
I would like to extend this a bit to add more data to the upload though, through other form elements. Any idea how this could be done?
A: The website you have linked to does a post of the form ajaxUploadForm using the jQuery ajaxForm function. I would presume that extra input data will be included when you add input elements to the ajaxUploadForm form.
Try it out: change the markup to the following (borrowed from the site in question):
<script type="text/javascript"> 1:
$(function() {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function() {
$("#ajaxUploadForm").block({ message: '<h1><img src="/Content/busy.gif" /> Uploading file...</h1>' });
},
success: function(result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, result.message);
},
error: function(xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
$.growlUI(null, 'Error uploading file');
}
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Upload a file</legend>
<label>File to Upload: <input type="file" name="file" />(100MB max size)</label>
<input type="text" id="someOtherInputElement" value="Test" />
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
</form>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1380686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone to Mac Sync Over Wi-Fi I am writing an iPhone application and would like to sync data over Wi-Fi between the iPhone and a complementary Mac application which I will also be writing (much like what is accomplished with Things and 1Password). To provide specific context, I need to be able to upload a CSV file to the iPhone application, have the ability to edit the data on the iPhone, and then re-download that file to the computer.
I am familiar enough with the mechanics of parsing and editing the CSV file once on the iPhone, but I am unsure how to approach the Wi-Fi sync between the iPhone and Mac. Obviously this is possible, since other applications have achieved the same thing, but do I need to setup some kind of server on the iPhone (which the Mac can talk to) or maybe a server in the Mac-side application (which the iPhone can talk to).
Any suggestions would be greatly appreciated. Thanks in advance.
A: In my apps, I use CocoaHTTPServer to get local info into and off of the phone. You run the server and out-of-the-box, it indexes all the files in the documents directory.
To do what you want, you will need to edit the code to return some other kind of data format (xml probably is the easiest) the call this from inside your app to get that data. CocoaHTTPServer easily take POST right out of the box too, so you can post an xml response as well.
After thinking about it, CocoaHTTPServer is best run on the computer side behind the scenes. the iphone can then send info to the computer where handling the code should be easier and you have more options.
A: On top of this you will want to look into Bonjour, it will allow the computer and the iphone to discover each other without too much difficulty. (ie by advertising their info on the network)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1430130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to reference a custom DLL from an uncompiled .NET webservice For various reasons I'll not go into I need to write my .NET webservice outside of Visual Studio. This in itself is not difficult and the following works fine...
<%@ WebService Language="C#" Class="TestHW" %>
using System;
using System.Web.Services;
using System.Xml.Serialization
[WebService(Namespace="http://www.mydomain.com/services")]
public class TestHW : WebService {
[WebMethod()]
public string Add(int a, int b) {
return a + b;
}
}
I need to reference a custom .NET DLL from this webservice, but I can't get the .asmx to find the DLL (which resides in the same directory). Google is difficult because everyone apparently wants to reference a webservice from a DLL not the other way around. Everything is targeting .NET 2.0.
using websvc; //DLL is websvc.dll with namespace websvc
gives the error...
CS0246: The type or namespace name 'websvc' could not be found (are you missing a using directive or an assembly reference?)
Thanks for your time.
A: finally found at How do I reference a component in an inline web service?
<%@ Assembly Name="MyAssembly" %>
or
<%@ Assembly Src="path/myFile.cs" %>
The name syntax is for compiled DLLs and the src syntax is for open code. The dll seems to need to be in a bin directory under the root.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10918947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to express IN (list of argument) in a query LINQ? How do you write a linq query to express this:
Select * from Table
where column IN (some values);
By some values, I mean ('Value1', 'Value2', 'value3', ...).
Thanks for helping
A: Assuming
var some_values = new [] { "Value1", "Value2", "value3" };
Then:
data.Where(x => some_values.Contains(x))
Or:
from x in data
where some_values.Contains(x)
select x;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16511042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Pyfst install error I'm having trouble installing Pyfst, which is a Python wrapper for OpenFst. I've tried using
pip install pyfst
but always end up with an error about some "unordered_map" which can't be found. Here's part of the stack trace:
In file included from fst/_fst.cpp:321:
/usr/local/include/fst/symbol-table.h:26:10: fatal error: 'unordered_map' file not found
#include <unordered_map>
A: Figured out a solution...
Environment: Ubuntu Server 14.04
Build and install OpenFST:
mkdir openfst
cd openfst
wget http://www.openfst.org/twiki/pub/FST/FstDownload/openfst-1.5.0.tar.gz
tar zxf openfst-1.5.0.tar.gz
cd openfst-1.5.0
./configure
make
sudo make install
The Magic:
sudo CFLAGS="-std=c++0x" pip install pyfst
Hope this helps.
A: i also came across the problem,but i solved it easily!
https://github.com/UFAL-DSG/pyfst
You should install OpenFst first,then to install fst!For more details,look at the link above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32260968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to access Weave DNS-Server from external? I use the Weave network plugin on a Docker-Swarm.
I created a docker network with a specific IP-Range, different from the default Weave Network, to which I route from my internal network.
To make the containers even better accessible I use weave to attach DNS names like containername.auto.mycompany.de. Now I want to access those from my company Network. The Problem is, that weave only allows access to the weave DNS from the local host.
Like on one of my swarm nodes i can do:
host foobar.auto.mycompany.de 172.17.0.1
Using domain server:
Name: 172.17.0.1
Address: 172.17.0.1#53
Aliases:
foobar.auto.mycompany.de has address 10.40.13.3
Host foobar.auto.mycompany.de not found: 3(NXDOMAIN)
Host foobar.auto.mycompany.de not found: 3(NXDOMAIN)
But I don't find a way to make the weave container accessible on one of the IP's from this (10.40.130/24) docker network or expose the port to the swarm node.
The only way I can think of, but don't like, is doing something like this:
iptables -t nat -A DOCKER -p tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53
(this does not work, it's just the idea)
Or tamper with the weave script to make it expose the port on start of the weave container.
Does anybody know of a better solution?
A: In fact setting the rules
iptables -A DOCKER -p tcp -m tcp --dport 53 -j DNAT --to-destination 172.17.0.1:53
iptables -A DOCKER -p udp -m udp --dport 53 -j DNAT --to-destination 172.17.0.1:53
does it. When I first tried that, I simply missed to see, that my request would have come from "outside" the server to work, not from inside to the loopback device.
Still not a pretty solution but it does the job. I'm looking forward to see better solutions from you guys.
(Bounty stands!)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34786515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Create a file in the sdcard I'm trying to create a new file from a class that not implements an Activity. If I use the same code on a class that implements an activity the file is created but not if the class doesnt implement an activity. Whats wrong? Should I need the context? How can I do?
public class fileInfo {
File filename;
int indexfile;
public filesInfo(){
indexfile = 0;
String filepath = Environment.getExternalStorageDirectory().getAbsolutePath().toString() + "/MotionSensors/values.txt";
filename = new File(filepath);
}
}
..
}
A: What you have done above looks alright, but still if it doesn't work, then try this:
FileOutputStream fos = context.openFileOutput("filename", Context.MODE_PRIVATE);
This will create a file from non-activity class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13826076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: how to read the data from excel sheet using two @Test in same class in testng selenium webdriver In this below example program, is it possible to use two @ test in one class,and then i have to fetch the data from excel sheet for both @ test in same excel sheet.is it possible?.two methods can be used in same class? one excel can contains both data's of two@ test?.please give me some ideas or example to be used two @ test in same class fetching data from excel sheet. I am waiting for reply.please help me...thanks in advance.
public class Test1 {
@BeforeTest
@Test(groups = { "" }, dataProvider = "getTestData", description = "")
public void abc(String a, String b) {
}
@Test(groups = { "" }, dataProvider = "", description = "")
public void abcd(String c, String d) {
}
@AfterMethod
@DataProvider
public Object[][] getTestData() {
check = true;
return TestUtil.getData(Sprint1xls, this.getClass().getSimpleName());
}
}
A: Yes the above is possible. I still don't get it where is the problem statement. Did you try above? is it failing? if yes then what is the error?
1) Yes, You can have 2 @Test methods in one class using same data provider.
2) If in the same sheet if you are using same data for this tests then there is no problem at all. if there is different data for different test then in your data provider toggle between test data using method name.
Let me know if you need further help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26375492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I use a macro to expand a tuple to its members as function arguments? I have a function from an external library [1] like
fn set_color(r: f64, g: f64:, b: f64)
I would like to manage my colors in tuples like
let yellow = (1., 1., 0.);
I thought of a macro like:
macro_rules! rgb {
( $rgb:expr ) => { rgb.0, rgb.1, rgb.2 }
}
playground
and then
set_color(rgb!(yellow));
Unfortunately Rust then says: error: macro expansion ignores token ',' and any following.
How can I make this happen?
[1]: cairo::Context::set_source_rgb() and friends
A: You cannot do this. Rust macros are not C macros that perform dumb textual manipulation; Rust macros must result in valid Rust code and a, b, c is not valid.
The closest would be to pass in the function to the macro:
macro_rules! rgb {
($f:expr, $rgb:expr) => {
$f($rgb.0, $rgb.1, $rgb.2)
};
}
let white = (1., 1., 1.);
rgb!(set_color, white);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61637160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: With clean architecture do entities hold properties such a cursors? I have the following proto message
message ListGamesResponse{
repeated Game games =1;
string nextCursor =2;
string previousCursor =3;
}
So I have an entity for Game for example. But here I run into a scenatio where I also have cursors. Does this mean that I should make models and entities for responses and requests? In some implementations of this architecture that I used for reference I don't see responses or requests in the domain layer.
How can I avoid having request and response entities in the domain layer? But still pass on the cursors?
A: In Clean Architecture we would clearly separate between entities which are part of your domain model and request/response objects which are passed to/from the application logic. The request/response objects would be specific to some particular application logic (use case interactor) while the entities are representing "central business rules" which apply to all the use case interactors.
For further explanation check out this article:
http://www.plainionist.net/Implementing-Clean-Architecture-Controller-Presenter/
A: you will need to have an entity of a collection of entities that has the cursors in it
for example
message GamesList{
repeated Game games =1;
string nextCursor =2;
string previousCursor =3;
}
cause the entity you are dealing with on the domain layer is not just a list of games it's also the state of the list (offset, limit)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74304895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery: How do I sum a column of numbers with commas? I used the following function I found online and it works perfectly. However, when my user later asked for commas to be included in the numbers, it broke. It only adds the numbers preceding the comma.
Here is the function:
function sumOfColumns(tableID, columnIndex, hasHeader) {
var tot = 0;
$("#" + tableID + " tr" + (hasHeader ? ":gt(0)" : ""))
.children("td:nth-child(" + columnIndex + ")")
.each(function() {
tot += parseInt($(this).html());
});
Do I need to stop the 'parseInt' piece?
A: I'm assuming that you mean that the numbers now have commas as a thousands-separator, like this:
1234567 = "1,234,567"
You can remove all of those commas before you call parseInt, like this:
tot += parseInt($(this).html().replace(',',''));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2456195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is the lifetime of objects with explicit destructors extended? I have been learning C++ and programmed this out of curiosity:
#include <iostream>
class A {};
class B {
public:
~B() {}
};
A get_a() {
A a;
std::cout << &a << '\n';
return a;
}
B get_b() {
B b;
std::cout << &b << '\n';
return b;
}
int main() {
A a = get_a();
std::cout << &a << '\n';
B b = get_b();
std::cout << &b << '\n';
return 0;
}
I got this as the ouput:
0x61fedf
0x61ff0f
0x61ff0e
0x61ff0e
This implies that a new object is constructed in the case of A, but the lifetime of B is simply extended.
Can anyone explain this to me? I am currently writing a library and don't want to have any incorrect preconceptions.
A: This is most likely an optimization feature of your compiler. For example, when I compiled your code using CL (MSVC compiler) without any optimization option, I got the following results:
But turning on fast code option, resulted in a more optimized memory usage:
Commands for disabled and fast code options of CL, respectively:
>cl /OD app.cpp
>cl /O2 app.cpp
You should refer to your compiler documentations to figure out the optimization options.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61970271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Modal closes after opening I have a a picture in my localhost website. I want to show the full size of it by using a modal. It is working well, the picture is shown, but the problem is the after clicking the show modal, it automatically closes after maybe 2 seconds. Why is that?
A: I've seen this problem pop up before. Are you including bootstrap.js and bootstrap-modal.js? If so, remove the include for bootstrap-modal.js. See if that helps :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25132631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I format primefaces progressbar's value to always show 2 decimal digits? I cannot find a way to make the primefaces progress bar to show two decimal digits.
I have googled primefaces progress bar but I couldn't find anything related to format the output value.
Here is the code.
<p:progressBar
value="#{data.financingDataModel.mortgagePercentage}"
styleClass="animated ui-soba-progress-bar " global="false" style="overflow:hidden">
</p:progressBar>
The mortgagePercentage type is Double.
I want it to show 60.00% instead of just 60%.
A: Can you try this:
<p:progressBar
value="#{data.financingDataModel.mortgagePercentage}"
styleClass="animated ui-soba-progress-bar " global="false"
style="overflow:hidden"
labelTemplate="#{data.financingDataModel.mortgagePercentage}%">
</p:progressBar>
I only add the `labelTemplate'. It is working on me in PF 7
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57246782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Limit width and height of image on input field Is it possible to limit the width and height of the pic on input field by using html, css and javascript/jquery? I'm trying to limit it for profile photo upload (need the photo to be a perfect square, e.g. 200x200, 300x300)
A: PHP has a function called getimagesize().
list($width, $height, $type, $attr) = getimagesize("img.jpg");
as can be seen in the documentation:
http://php.net/manual/en/function.getimagesize.php
So, just check the height and width before submitting to the database
A: You can check the height of width of the image by creating an image from the uploaded file.
$("#fileUploadForm").submit(function(e){
var window.URL = window.URL || window.webkitURL;
var fileInput = $(this).find("input[type=file]")[0],
file = fileInput.files ? fileInput.files[0] : null;
if( file ) {
var img = new Image();
img.src = window.URL.createObjectURL( file );
img.onload = function() {
var width = img.naturalWidth,
height = img.naturalHeight;
window.URL.revokeObjectURL( img.src );
if( width == height) {//perfect square
this.submit();
}
else {
//fail
}
};
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51529796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue with nuxt/auth For auth I do use nuxt-auth, when the login is successful, I want to redirect to the main page using this.$router.push('/'), then I get a response like blank page with the following message
2021
,
// for login
<template>
<div class="limiter">
<div
class="container-login100"
:style="{
backgroundImage: 'url(' + require(`@/assets/login/images/bg-01.jpg`) + ')',
}"
>
<div class="wrap-login100 p-l-110 p-r-110 p-t-62 p-b-33">
<form class="login100-form validate-form flex-sb flex-w">
<span class="login100-form-title p-b-53"> Login Admin </span>
<a href="facebook.com" class="btn-face m-b-20">
<i class="fa fa-facebook-official"></i>
Facebook
</a>
<a href="google.com" class="btn-google m-b-20">
<img :src="require(`@/assets/login/images/icons/icon-google.png`)" alt="GOOGLE" />
Google
</a>
<div class="p-t-31 p-b-9">
<span class="txt1"> Email </span>
</div>
<div class="wrap-input100 validate-input" data-validate="Email is required">
<input v-model="auth.email" class="input100" type="email" name="email" />
<span class="focus-input100"></span>
</div>
<div class="p-t-13 p-b-9">
<span class="txt1"> Password </span>
<a href="#" class="txt2 bo1 m-l-5"> Forgot? </a>
</div>
<div class="wrap-input100 validate-input" data-validate="Password is required">
<input v-model="auth.password" class="input100" type="password" name="pass" />
<span class="focus-input100"></span>
</div>
<div class="container-login100-form-btn m-t-17">
<a href="javascript:void(0)" class="login100-form-btn" @click="submit">Login</a>
</div>
<div class="w-full text-center p-t-55">
<span class="txt2"> Not a member? </span>
<a href="#" class="txt2 bo1"> Register now </a>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
auth: false,
data() {
return {
auth: {
email: null,
password: null,
},
}
},
mounted() {
if (this.$auth.loggedIn) {
this.$router.push('/')
}
},
methods: {
async submit() {
try {
const response = await this.$auth.loginWith('local', { data: this.auth })
this.$router.push('/')
} catch (err) {
console.log(err)
}
},
},
}
</script>
store vuex index.js
export const getters = {
isAuthenticated(state) {
return state.auth.loggedIn
},
loggedInUser(state) {
return state.auth.user
}}
}
layout default.vue
<template>
<div class="wrapper">
<Sidebar v-if="isAuthenticated" />
<div :class="isAuthenticated ? 'main-panel' : ''">
<Navbar v-if="isAuthenticated" />
<Nuxt />
<Footer v-if="isAuthenticated" />
</div>
</div>
</template>
<script>
import Sidebar from '@/components/layout/Sidebar.vue'
import Navbar from '@/components/layout/Navbar.vue'
import Footer from '@/components/layout/Footer.vue'
import { mapGetters } from 'vuex'
export default {
components: { Sidebar, Navbar, Footer },
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser']),
},
}
</script>
// auth nuxt config
auth : {
strategies: {
local: {
token: {
property: 'token',
required: true,
type: 'Bearer'
},
user: {
property: 'user',
autoFetch: true
},
endpoints: {
login: { url: '/sign/login', method: 'post' },
logout: { url: '/sign/logout', method: 'post' },
user: { url: '/sign/user-login', method: 'get' }
}
}
}
}
base index ('/')
<template>
<div class="container">
<div>
<Logo />
<h1 class="title">Learn Nuxt</h1>
<div class="links">
<a href="https://nuxtjs.org/" target="_blank" rel="noopener noreferrer" class="button--green">
Documentation
</a>
<a
href="https://github.com/nuxt/nuxt.js"
target="_blank"
rel="noopener noreferrer"
class="button--grey"
>
GitHub
</a>
</div>
</div>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(['isAuthenticated', 'loggedInUser']),
},
}
</script>
A: In your vuex store, the state parameter in your getter only has access to local state. You can't access the auth state the way you tried.
In a vuex module, a getter gets 4 arguments, namely local state, local getters, root state and root getters. So if you would rewrite your getters like this it would probably work:
export const getters = {
isAuthenticated(state, getters, rootState) {
return rootState.auth.loggedIn
},
loggedInUser(state, getters, rootState) {
return rootState.auth.user
}}
}
But I still think it is a bit redundant doing it like that. I would replace isAuthenticated with this.$auth.loggedIn in your default layout. The nuxt-auth module globally injects the $auth instance, meaning that you can access it anywhere using this.$auth.
A: I had same problem after authorizing user and redirect user to the home page.
After many tries and doing many works, the right config of auth in nuxt.config.js seemed like this:
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access_token',
tokenType: false,
maxAge: 60 * 60
},
refreshToken: {
property: 'refresh_token',
data: '',
maxAge: 60 * 60
},
endpoints: {
login: {
url: 'url/of/token',
method: 'urlMethod'
},
refresh: {
url: 'url/of/refreshToken',
method: 'urlMethod'
},
logout: false,
user: false
}
}
},
cookie: false,
redirect: {
login: '/login/page',
logout: '/login/page',
callback: false,
home: '/home/page'
}
},
Note that I didn't have any refreshToken property, but I should set it as empty string in config to be able to work with nuxt/auth!
Hope I could help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67714376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to replace special characters from mysql string there is a table in mysql database and it has strings, datatype is text, and the data which is inserted is as below
HELLO+THIS+IS+OFFER!!%+HURRY!!%0ACall+US+NOW%
How do I remove % and + special characters from this string, it looks like encoded string.
Best Regards
CJ
A: Below mysql function removes special characters from a string:
DROP FUNCTION IF EXISTS replacespecialchars;
DELIMITER |
CREATE FUNCTION replacespecialchars( str CHAR(255) ) RETURNS CHAR(255) DETERMINISTIC
BEGIN
DECLARE i, len SMALLINT DEFAULT 1;
DECLARE ret CHAR(255) DEFAULT '';
DECLARE c CHAR(1);
SET len = CHAR_LENGTH( str );
REPEAT
BEGIN
SET c = MID( str, i, 1 );
IF c REGEXP '[[:alnum:]]' THEN
SET ret=CONCAT(ret,c);
END IF;
SET i = i + 1;
END;
UNTIL i > len END REPEAT;
RETURN ret;
END |
DELIMITER ;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52005057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FreeMarker error: For "-" left-hand operand: Expected a number, but this has evaluated to a string I am trying to compute sum of values in map and print line of "-"s (the length of this line should be sum-1).
This is the code of my function:
<#function getSeparatorLine map>
<#if !map?has_content>
<#return "">
</#if>
<#local borderLength = 0>
<#list map?keys as item>
<#local borderLength = borderLength + item + 1>
</#list>
<#return ""?right_pad(borderLength - 1, "-")>
</#function>
I get a freemarker error saying:
ERROR freemarker.runtime - Error executing FreeMarker template
freemarker.core.NonNumericalException: For "-" left-hand operand: Expected a number, but this has evaluated to a string (wrapper: f.t.SimpleScalar):
==> borderLength [in template "negative_events_report.template" at line 38, column 27]
Any suggestions?
A: item is a string, so borderLength + item + 1 actually does string concatenation instead of arithmetical addition. Assuming map contains numerical values, you should write map?values, not map?keys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34925404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Leetcode C++ for loop condition The error comes from one Leetcode test case for this problem. I copy my solution so that the particular test case will break.
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size() - 2; i++) {
cout << "nums.size(): " << nums.size() << endl;
if (i > 0 && nums[i] == nums[i-1])
continue;
int left = i + 1, right = nums.size() - 1;
while(left < right) {
int s = nums[i] + nums[left] + nums[right];
if (s > 0) right--;
else if (s < 0) left++;
else {
res.push_back({nums[i], nums[left], nums[right]});
while(left + 1 < right && nums[left] == nums[left+1]) left++;
while(right - 1 > left && nums[right] == nums[right-1]) right--;
left ++; right--;
}
}
}
return res;
}
};
Last executed input []
I'm confused because in this case, since nums is an empty vector, nums.size() should be 0, and since i < nums.size() - 2 = -2 is not met, the for loop shouldn't be executed but somehow I got a runtime error. Could someone please explain why this breaks? Thanks in advance!
A: nums.size() return a unsigned value,-2 cause overflow.
(int)nums.size()-2 can solve it.
A: The problem is that the size() function returns an unassigned int, and you're comparing it to i, which is a signed int.
Turn this line...
for (int i = 0; i < nums.size() - 2; i++) {
Into this...
for (int i = 0; i < ((int)nums.size()) - 2; i++) {
And here's a link to someone else with a similar problem, if you wanna read more about other solutions...
What is wrong with my For loops? i get warnings: comparison between signed and unsigned integer expressions [-Wsign-compare]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58887529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Git pull origin [branch name] vs git checkout -t origin/[branch name] I do jobs in local server and push them to the branch. after that, I would like to pull the branch from remote repository to webserver. When I would like to bring the jobs updated on the branch into the web server, which command on the following is correct?
git pull origin [branch name]
vs.
git checkout -t origin/[branch name]
The job I've done on branch is now totally different with the main one. I do not want any merge branch to main so now the job on branch is like other project, nothing to do with the original project on the main. let me call the jobs I've done on the branch 'B project'. I would like to manage B project only on the branch and original one still on main.
Is that a good idea? Or is there a better way for this plan?
A: You could use separate branches for each feature. I personally use a hierarchy similar to below.
/
|---features
|--- A
|--- B
That would result in /features/A and /features/B branches respectively. That way you could work on your features on separate branches and use main branch as stable version of your application.
After your last edit, I would definitely recommend the solution below.
Or a better solution for entirely different jobs, you could use git-worktree command.
git worktree add [-b <new-branch>] <path> [<the branch/tree you want to base this worktree>]
This is the best I could from what I've understand from your question.
A: For my understanding, you have a main project and a different project which is based on the main, while being significantly different.
If that's the case, I would have different repositories for the two, so to keep them more maintainable.
The main repo will stay as it is, while on the second one we want to add the main repo as a remote origin.
To do that let's first:
*
*Create a new repo at github
*Clone the main repo locally if not done already
You can then add the main repo as a remote origin:
*git remote rename origin upstream
*git remote add origin URL_TO_MAIN_GITHUB_REPO
*git push origin master
Now you can work with it just like any other github repo.
To pull in patches from upstream, simply run git pull upstream master && git push origin master.
To underline I would follow this solution if you have two different projects based on some common changes, as branches works well for features / patches you would then want to merge to master once they are completed.
If, on the other hand, you simply have the same project with different features, then @Deniz da King solution is great.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67956502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Excel Vba dictionary not looped
I have this code that is supposed to iterate through my folder and add the file names into the dictionary, however after adding my extraction code inside this for loop, only data from the last file in the folder will be extracted because everytime it collects data from the next file, it will overwrite the row and column "A2:M2" and not continue adding on.
UPDATED
Public Dict As Object
Sub EEE()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.DisplayStatusBar = False
Dim oFSO As Object, oFolder As Object, ofile As Object
Set oFSO = CreateObject("Scripting.fileSystemObject")
Set oFolder = oFSO.GetFolder("C:\Users\Desktop\file\")
If Dict Is Nothing Then
Set Dict = CreateObject("Scripting.Dictionary")
Dict.Add Key:="filename", Item:=ofile
End If
For Each ofile In oFolder.Files
If Not Dict.Exists(oFSO.GetBaseName(ofile)) Then
Dim basePath As Variant
basePath = "C:\Users\Desktop\file\"
Dim baseFolder As Scripting.Folder
With New Scripting.FileSystemObject
Set baseFolder = .GetFolder(basePath)
End With
Dim file As Scripting.file
For Each file In baseFolder.Files
Dim a As Range
Dim wkbData As Workbook
Set wkbData = Workbooks.Open(file.path)
Dim wksData As Worksheet
ActiveSheet.Name = "Book1"
Set wksData = wkbData.Worksheets("Book1") ' -> Assume this file has only 1 worksheet
Dim LastRow As Long
LastRow = wks.Range("A" & wks.Rows.count).End(xlUp).row + 1
wks.Cells(LastRow, 6).value = file.Name
Set a = wksData.Columns("A:A").Find(" test1234 : ", LookIn:=xlValues)
If Not a Is Nothing Then
wks.Cells(LastRow, 1) = Split(a.value, ":")(1)
End If
wkbData.Close False
Range("A:M").EntireColumn.AutoFit
Range("A1").AutoFilter
Debug.Print "A: " & oFSO.GetBaseName(ofile)
Dict.Add oFSO.GetBaseName(ofile), 1
Next file
Else
'skip
Debug.Print "E: " & oFSO.GetBaseName(ofile)
End If
Next ofile
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.DisplayStatusBar = True
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59816143",
"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.