text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
How to deploy next.js 9 to AWS Lambda without using Serverless Components
I would like to simply deploy my Next.js 9 to AWS Lambdas using just API Gateway in front and make a proxy to the static path pointing to S3, but the only available option (without having to write all the stuff from the scratch) is https://github.com/serverless-nextjs/serverless-next.js which is currently using a beta version of Serverless Components (very buggy and lack of control over resources created as it does not uses CloudFormation), also this SLS Component forces the user to use CloudFront which is not my need, I have PR environments created all the time and allocating CloudFront for that is just waste of time/money/resources.
I tried to use the old version of the plugin serverless-nextjs-plugin but it seems not to work with Next.js 9, it fails to create the Lambdas for .html generated pages.
Is there any light in the end of this tunnel?
https://github.com/serverless-nextjs/serverless-next.js/issues/296 by this issue it looks like there's no way to do that.
Hey Marcelo, I sympathize with you and understand what you're saying. I'm on the same boat.. What did you end up doing? Thanks!
I managed to make it work
serverless.base.yml file:
service: my-app
provider:
name: aws
runtime: nodejs12.x
timeout: 10 # seconds
memorySize: 1792 # Mb
custom:
webpack:
packager: yarn
includeModules:
forceInclude:
- chalk
functions:
nextJsApp:
handler: server.handler
events:
- http: 'ANY /'
- http: 'ANY {proxy+}'
server.js:
const { parse } = require('url');
const next = require('next');
const serverless = require('serverless-http');
const app = next({
dev: false
});
const requestHandler = app.getRequestHandler();
export const handler = serverless(async (req, res) => {
const parsedUrl = parse(req.url, true);
await requestHandler(req, res, parsedUrl);
});
wepback.config.js:
const CopyWebpackPlugin = require('copy-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
module.exports = {
...
externals: [nodeExternals()],
plugins: [
new CopyWebpackPlugin({
patterns: [
{ from: '.next', to: '.next' },
{ from: 'public', to: 'public' }
]
})
]
};
and here is the trick for working with serverless and webpack, use a serverless.js that modifies the serverless.base.yml and add all dependencies to the required dependencies to be included in the bundle:
const yaml = require('yaml-boost');
const minimist = require('minimist');
const path = require('path');
module.exports = (() => {
const params = minimist(process.argv.slice(2));
const serverless = yaml.load(path.join(__dirname, 'serverless.base.yml'), params);
const packageJson = require(path.join(__dirname, 'package.json'));
const dependencies = Object.keys(packageJson.dependencies);
serverless.custom.webpack.includeModules.forceInclude.push(...dependencies);
return serverless;
})();
Hey Marcelo,
Can you explain why the webpack config and serverless.js dependency injection are necessary?
For Lambdas I understand that the Next.js app must have a custom server to export its handler wrapped in serverless-http, but I don't see where webpack must come in.
I plan to deploy my Next.js SSR/SSG app to an AWS Lambda with API Gateway using AWS SAM as opposed to using serverless.yml. This makes me wonder what the webpack dependency injection in serverless.js is doing and whether I need to do this within my Next.js app served from a SAM template.
the reason is the the lambda bundle is made copying the bundled assets from next, but for unknown reasons for me next bundle does not includes the dependencies on it, so I need to force serverless framework to include the dependencies on the lambda bundle so the next runtime can access it.
| common-pile/stackexchange_filtered |
QGIS TimeManager with multiple features at one time?
Since the data I have to deal with is really large, it is not practical to separate every feature into one line in the CSV file.
Is there any way to animate them as a whole layer?
I have approximately 26000 features in one layer for each time interval, and 300 time intervals that i need to implement the animation.
EDIT:
I want to display links and animate their colour changes based on the magnitudes.
Basically, all links should show up at all time, but since their magnitudes change with time, and I colour coded the style, the colour of the links will change as time passes.
My previous data format is: magnitude; time; coordinates in WKT format. one example is: 4; 2015-01-01;<PHONE_NUMBER>161,<PHONE_NUMBER>144). However, in this form, if I need to include all the data, it requires 7,000,000 lines which exceeds the maximum row limit for excel. So now I want to know if there is any chances to animate them as a whole layer, or some ways to solve this problem.
Also if I input all the data, the program probably becomes really slow.
It is unclear to me what you are asking.
Please add more details about the current format of your data. Currently we can only guess what you are trying to work with.
My data format is: magnitude; time; coordinates in WKT format.
When the row limit of Excel is exceeded, this should be an indication to switch to a database. Use PostGIS, put an index on the timestamp and animating that table with QGIS Time Manager will be a breeze.
Is there any tutorial for establishing a database? especially the indexing. thanks in advance
Yes, google PostGIS + your operating system
| common-pile/stackexchange_filtered |
Rails 2.2.2 issue: undefined method `activate_bin_path' for Gem:Module (NoMethodError)
I am working on Rails 2.2.2 application. For this I installed rvm with Ruby version 1.9.3p551. There is no Gemfile for this application. So as mentioned in the environment.rb file I created a Gemfile with rails and sqlite3. While running rake db:create, I am facing the following issue.
whoami@myvm:~/Desktop/practice/store$ rake db:create
/home/whoami/.rvm/gems/ruby-1.9.3-p551/bin/rake:22:in `<main>': undefined method `activate_bin_path' for Gem:Module (NoMethodError)
from /home/whoami/.rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in `eval'
from /home/whoami/.rvm/gems/ruby-1.9.3-p551/bin/ruby_executable_hooks:15:in `<main>'
Please help me.
For me, (I am working with RVM) it worked just running:
gem update --system
gem update bundler
Thank you! Just confirmed with Rails <IP_ADDRESS> and Ruby 2.3.1 also.
It also appears to work on Rails 2.3.18 and Ruby 1.9.3. (Hooray for legacy code. :-p)
I tried this on macOS Sierra and due to system integrity protection the last command needs to be changed to gem install bundler -n /usr/local/bin
This normally occurs when you have multiple versions of RVM and gem sets and its normally comes for ruby 2.2.2 the best way to get rid of this ERROR is.
First Update your system gems by using the following
gem update --system
OR
update_rubygems --system
Then you have to update your bundler:
gem update bundler
Have you tried these commands
Rename /usr/lib/ruby/site_ruby/ to site_ruby.bak/
Run the following commands:
gem install rubygems-update
enter code here
update_rubygems
If you get error then try the following instead:
ruby --disable-gems -S update_rubygems
I am using rvm and there is no site_ruby folder/file.
you need to check where your ruby installed
I had a similar issue, when running the standalone passenger, it worked fine. However, running it using a systemd service gave the same error as the OP:
undefined method `activate_bin_path' for Gem:Module (NoMethodError)
I've managed to solve it using
env | egrep 'gem|rvm|ruby' > passenger.env
and adding it to the service file using EnvironmentFile=[...]/passenger.env.
Hopefully, this will be useful for other people stuck on this.
thanks. this solved my problem. Do you know why this is happening? My experience so far with systemd has been disappointing, and I want to go back to upstart.
It's because the environment variables weren't visible to systemd, but I don't know what's the root cause.
Try run through the bundle
cd myapp
gem install bundler
bundle install
bundle exec rake db:create
sudo chown -R $(whoami) /lib/ruby/gems/*
export GEM_HOME="$HOME/.gem"
Actually these steps worked for me.
Using syntax highlight makes your answer more clear :)
| common-pile/stackexchange_filtered |
Is comparing to a pointer one element past the end of an array well-defined?
I learned by this question that incrementing a NULL pointer or incrementing past the end of an array isn't well-defined behavior:
int* pointer = 0;
pointer++;
int a[3];
int* pointer2 = &a[0];
pointer2 += 4;
But what If the pointer pointing to a invalid place is only used for comparison and memory at his location is never accessed?
Example:
void exampleFunction(int arrayLen, char** strArray)
{
for(char** str = strArray; str < strArray + arrayLen; str++) //or even str < &strArray[arrayLen]
{
//here *str is always a pointer to the first char of my string
}
}
Here I compare my pointer to a pointer one element past the end of the array. Is this well-defined behavior?
When would the expression *argv + argc ever make sense? The length of argv[0] isn't related to argc. If you meant argv + argc, it's fine AIUI because pointers "one element past the end of the array" are well-defined and can be compared to other pointers in the same array. (Or argv + argc + 1 because, as chux mentioned, argv ends with NULL.)
@chux Good to know ! I just have to use <= then. But the original question shouldn't take my mistake in consideration. Updated with better example
Your second code is OK as str is always a valid pointer. It last value is not de-reference-able though.
The edited expression *strArray + arrayLen still doesn't make sense.
Incrementing one step past the end of the array is fine. Incrementing any further is not. pointer2 += 4 is undefined behavior, but pointer2 += 3 would not be, even though it would cause pointer2 to point past the end of the array.
Note that "Is comparing to a pointer one element past the end of an array well-defined?" does not apply to the UB of int* pointer = 0; pointer++;.
@chux The point was "does it matter if I create a pointer pointing to nothing as long as I don't use it to access" but the question was narrowed a bit to the example I provided.
Comparing to a pointer one step past the end of an array is well defined. However, your pointer and pointer2 examples are undefined, even if you do literally nothing with those pointers.
A pointer may point to one element past the end of the array. That pointer may not be dereferenced (otherwise that would be undefined behavior) but it can be compared to another pointer within the array.
Section 6.5.6 of the C standard says the following regarding pointer addition (emphasis added):
8 If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array
object, the evaluation shall not produce an overflow; otherwise, the
behavior is undefined. If the result points one past the last element
of the array object, it shall not be used as the operand of a unary *
operator that is evaluated.
Section 6.5.8 says the following regarding pointer comparisons (emphasis added):
5 When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two
pointers to object types both point to the same object, or both point
one past the last element of the same array object, they compare
equal. If the objects pointed to are members of the same aggregate
object, pointers to structure members declared later compare greater
than pointers to members declared earlier in the structure, and
pointers to array elements with larger subscript values compare
greater than pointers to elements of the same array with lower
subscript values. All pointers to members of the same union object
compare equal. If the expression P points to an element of an array
object and the expression Q points to the last element of the same
array object, the pointer expression Q+1 compares greater than P. In
all other cases, the behavior is undefined.
In the case of pointer1, it starts out pointing to NULL. Incrementing this pointer invokes undefined behavior because it don't point to a valid object.
For pointer2, it is increased by 4, putting it two elements past the end of the array, not one, so this is again undefined behavior. Had it been increased by 3, the behavior would be well defined.
Is not the "one passed" rule applies to non-array objects too? int x; int *p = &x+1;
@chux You may be right. Section 6.5.8 part 4 says "For the purposes of these operators, a pointer to an object that is not an element of an
array behaves the same as a pointer to the first element of an array of length one with the
type of the object as its element type." Section 6.5.6 part 7 has the same wording.
The quoted 6.5.8 applies to <, <=, >=, and >. The == and != operators never yield Undefined Behavior when given pointers to objects, pointers "just past" objects, or null pointers. A comparison between a pointer "to" one object and a pointer "just past" another may report equality, but that does not imply the pointers may be used interchangeably.
Does this also apply to the element one before the array? I'm asking because I'm needing to iterate in reverse and the nicest idiom would be a pointer one step before the first element.
@LeviMorrison it does not
@LeviMorrison: IMHO, the best way to understand the allowance for "just-past" pointers is to recognize that each object has two associated addresses: one for the start and one for the end. An array of three elements will have four associated address: start of first, between first and second, between second and third, and end of third.
@LeviMorrison Start with one-past-the-end, pre-decrement instead of post-decrementing, and use >= start instead of < end as the loop predicate.
| common-pile/stackexchange_filtered |
search xml elements with if statement in C#
I have different xml files and would like to get one specific value from each xml.
what i'm trying to do is to search some of the elements in the xml and then when there is specific value or reference, then get the value of this reference.
for example one xml has this:
<textInfo>
<freeText>
<informationType>15</informationType>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>47</informationType>
</freeText>
<freeText>some text</freeText>
</textInfo>
<textInfo>
<freeText>
<informationType>733</informationType>
<status>1</status>
</freeText>
</textInfo>
other xml has more than that, for example:
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>15</informationType>
<status>0</status>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>47</informationType>
</freeText>
<freeText>some text</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<status>0</status>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>61</informationType>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>39</informationType>
</freeText>
<freeText>some text</freeText>
<freeText>some other text</freeText>
</textInfo>
so what i tried to do is to first find the Length and how many tags in the xml and then use Foreach or While and then IF statement where tag equals 39 then get the value of the freeText tag
foreach (search all <textInfo>)
{
if (<informationType> ==39)
{
do get the value of <freeText> of that <informationType>
}
}
my problem is i don't know which to use in this case, should i use Foreach or while. and how to use it.
Note: i'm only getting the xml from webservice. i'm not storing it somewhere or have it as xml file. i'm just handling all the xml in my project and only stuck on this searching multiple tags to find one value
EDIT/update
i have tried below two codes but both are returning a Null value
XmlDocument doc = new XmlDocument();
doc.LoadXml(requestInterceptor.LastResponseXML);
foreach (XmlNode node in doc.SelectNodes("//textInfo/freeText[informationType>=39]/informationType"))
{
Object.Type = node.InnerText;
}
other code:
XDocument doc1 = XDocument.Parse(requestInterceptor.LastResponseXML);
var query = doc1.Descendants("textInfo").Where(ft => ((int?)ft.Element("informationType")).Equals("39"));
from c in doc1.Root.Descendants("textInfo")
where (c.Attribute("informationType").Equals("39"))
select c.Element("freeText");
Object.Type = query.ToString();
Linq to XML can help you to query the content of the file in an easy way. But your structure is not fixed (freeText sometimes has a string or other fields) so I could become a mess to work with ...
https://stackoverflow.com/questions/642293/how-do-i-read-and-parse-an-xml-file-in-c
thank you @lordvlad30, but i'm only getting the xml from webservice. i'm not storing it somewhere or have it as xml file. i'm just handling all the xml in my project and only stuck on this searching multiple tags to find one value
@Ghaly_m you can use the Linq to XML without having the file, like Jon Skeet said in his comment.
LINQ to XML makes this sort of query simple. I believe you're trying to find all <freeText> elements which have a direct <informationType> child element with a value of 39. Assuming every <informationType> element actually contains an integer, you could use:
XDocument doc = ...;
var freeTextsWithInfoType39 = doc
.Descendants("freeText")
.Where(ft => ((int?) ft.Element("informationType")) == 39);
You can then use that however you want - perhaps with another query to transform the results, or a foreach loop.
is there a way to use this without the LINQtoXML as i don't have the XML file stored with me, i'm only getting it from a webservice and reading it and trying to get the required values.
@Ghaly_m: I don't understand - if you've got the XML, it doesn't matter where you got it from, you can still load it into an XDocument. If you've got it as a string, just use XDocument doc = XDocument.Parse(text); for example.
it is returning a Null... XDocument doc1 = XDocument.Parse(requestInterceptor.LastResponseXML);
var query = doc1.Descendants("textInfo").Where(ft => ((int?)ft.Element("informationType")).Equals("39"));
from c in doc1.Root.Descendants("textInfo")
where (c.Attribute("informationType").Equals("39"))
select c.Element("freeText");
@Ghaly_m: That's not what the query was in my answer though. I looked for freeText elements which have a child informationType element with a value of 39, and I also didn't compare an integer with a string. The query that's actually in my answer finds a single freeText element. To get the informationType element, just ask for the parent.
my mistake, i edit it based on the answer, the exact code of yours returns System.Linq.Enumerable+WhereEnumerableIterator`1[System.Xml.Linq.XElement]
@Ghaly_m: Well yes, that's a sequence of freeText elements. So then do whatever you want with those elements, e.g. via a foreach loop.
In addition to using XDocument, you can also use XmlDocument and XPath.
XmlDocument doc = new XmlDocument();
doc.Load(@"sample.xml");
foreach(XmlNode node in doc.SelectNodes("//textInfo/freeText[informationType>=39]/informationType"))
{
Console.WriteLine(node.InnerText);
}
//the print out should be:
//47
//61
//39
For more infomation about XPath, please refer to:https://www.w3schools.com/xml/xpath_intro.asp
The sample xml string doesn't have a root element, if you want to load such xml string, you should format the xml string first.
var xml = @"<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>15</informationType>
<status>0</status>
</freeText>
</textInfo>
<textInfo>
<freeText>
<textSubject>4</textSubject>
<informationType>47</informationType>
</freeText>
<freeText>some text</freeText>
</textInfo>"
var validXml = $"<resp>{xml}</resp>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(validXml);
//The other code is the same as before.
i have tried the following but it is returning a Null ..... XmlDocument doc = new XmlDocument();
doc.LoadXml(requestInterceptor.LastResponseXML);
foreach (XmlNode node in doc.SelectNodes("//textInfo/freeText[informationType>=39]/informationType"))
{
EMD_Object.infoType = node.InnerText;
}
@mylahg hi, mylahg, I just update my answer, I think you can refer to the latest answer.
| common-pile/stackexchange_filtered |
Search behavior Individual/Household
I have a individual contact called: "John Wayne".
He is connected to a household called "John and Margret Wayne".
When I search now for "John Wayne" in the simple search an in the advanced search, it only returns the household. Is this a normal behavior? Our NGO workers get super confused about this, is there a way to get the individual and household contact in the result table?
I found a way to get this work. I don't know if it's quite a hack, but it works at least.
Change this line in the "CRM/Contact/BAO/Query.php": public function sortName(&$values):
if ($fieldName == 'sort_name') {
$wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
} else {
$wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
}
to:
$wc = self::caseImportant($op) ? "LOWER(contact_a.sort_name)" : "contact_a.sort_name";
$fieldsub[] = " ( $wc $op $value )";
$wc = self::caseImportant($op) ? "LOWER(contact_a.display_name)" : "contact_a.display_name";
$fieldsub[] = " ( $wc $op $value )";
If this is indeed a bug then please open a ticket in JIRA and try to provide a patch - https://issues.civicrm.org/jira
It should show up both contacts, I suspect there might be something in the setup of your sort name. Could you attach some screen prints so I can see what happens?
When I search for "John Wayne" I get this result:
http://goga.ch/tmp/iogt/screen1.png
When I serach for "Wayne" this:
http://goga.ch/tmp/iogt/screen2.png
But if I check for "Wayne, John" I only get the Individual:
http://goga.ch/tmp/iogt/screen3.png
The settings for the sort name in the display preferences look like this:
http://goga.ch/tmp/iogt/screen4.png
@woistjadefox, what is your Automatic Wildcard set to? (Administer > Customize Data and Screens > Search Preferences)
@AllenHutchison, it's set to "Yes". Tried it with "No" but it didn't have any effect.
I have just tried your search on the demo site after adding your examples, and I get both contacts if I search for John Wayne in both Advanced Search and Search Contacts.
I think this is your desired behaviour?
Yes exactly. But what could be the reason that It doesn't show both on my installation? I didn't change anything in the sort name settings.
just tried the same on the demo of the CiviCRM v4.6 on Drupal version: http://d46.demo.civicrm.org
I can reproduce the behavior of my installation. On which demo site did you try it?
Concur with Mr Fox. searching "john wayne" on demo via QuickSearch, Find, or Adv Search all return a single result of the household, whereas searching for just "wayne" returns both results
I tried on the 4.5 demo, so it smells like a 4.6 bug?
Argh.. any idea in which modul/file I could fix this my-self?
| common-pile/stackexchange_filtered |
Storing coordinates in HashSet
I am trying to store coordinates in a HashSet and checking whether a coordinate exist inside my set.
HashSet<int[]> hSet = new HashSet<>();
hSet.add(new int[] {1, 2});
hSet.add(new int[] {3, 4});
System.out.println(hSet.contains(new int[] {1, 2}));
>>> false
I am rather new to Java and from my understanding the output of the above is false is due to comparing the references of the int[] arrays rather than the logical comparison of their values. However using Arrays.equals() would not be making use of the hashing of the hashset as I would have to iterate over all its elements.
I have also read on other questions that it is not recommended to use arrays inside collections.
So if I wish to store coordinate pairs inside a HashSet, what data structure should I use so that I can search for an element using the hashcode?
Create your own Coordinate class, and implement equals and hashcode?
So there is no built in classes for such purpose?
Possibly java.awt.Point. It depends on the context in which you intend to use this class.
You could (better ... should) create an own class that holds those coordinates:
public class Coordinates {
private final int x;
private final int y;
public Coordinates(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
Now, the most important thing is to implement equals and hashCode:
public class Coordinates {
...
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Coordinates other = (Coordinates) obj;
return this.x == other.x && this.y == other.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}
}
With that preparation, you can change your code to:
public static void main(String[] args) {
HashSet<Coordinates> hSet = new HashSet<>();
hSet.add(new Coordinates(1, 2));
hSet.add(new Coordinates(3, 4));
System.out.println(hSet.contains(new Coordinates(1, 2)));
}
This prints out
true
as wanted.
Create a class for store Coordinate data
class Coordinate{
Integer x;
Integer y;
}
And implement equals and hashcode for the class.
Or you can use List<Integer> instead of int[] this way.
HashSet<List<Integer>> hSet = new HashSet<>();
hSet.add(List.of(1, 2));
hSet.add(List.of(3, 4));
System.out.println(hSet.contains(List.of(1, 2)));
The equals() method of List interface compares the specified object with this collection for equality. It returns a Boolean value true if both the lists have same elements and are of the same size.
| common-pile/stackexchange_filtered |
Hide List Content Type via CSOM
How to programmatically (using CSOM/JSOM) uncheck the Visible checkbox for a content type:
so that the content type (Document Set above) is not anymore visible in FILES > New Document:
In order to verify that the solution would work:
Do the change
Manually add the content type back and verify that it is shown again.
Have you tried setting Hidden property? http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.client.contenttype.hidden(v=office.15).aspx
Yes. The Content Type gets hidden but the Visible checkbox seems to stop having any effect after setting the Hidden property; changing it seems to do a different thing but I don't know where can we do or undo the same in UI.
+1 As always a good question :)
You need to set uniqueContentTypeOrder on the root folder of the list. Check SP.Folder.uniqueContentTypeOrder property here at msdn. Even though you need to do it
in JSOM or CSOM, I will share a server object model code which may help you in resolving this issue:
using (SPSite site = new SPSite("http://aissp2013/sites/t1"))
{
SPWeb web = site.RootWeb;
SPList list = web.Lists["Hardware And Sanitary Products"];
SPFolder folder = list.RootFolder;
IList<SPContentType> uniqueContentTypeOrder = new List<SPContentType>();
SPContentTypeCollection listContentTypes = list.ContentTypes;
foreach (SPContentType ct in listContentTypes)
{
if (ct.Name == "SanitaryItems")
{
uniqueContentTypeOrder.Add(ct);
}
else if (ct.Name == "HardwareItems")
{
uniqueContentTypeOrder.Add(ct);
}
}
if (uniqueContentTypeOrder.Count > 0)
{
folder.UniqueContentTypeOrder = uniqueContentTypeOrder;
}
list.Update();
}
See here for more details.
This does not seem to hide any content types for me. It shows the content types listed in UniqueContentTypeOrder first, but lists all the rest of the content types afterwards. Is this not the case for you?
Add only required list content types in UniqueContentTypeOrder.
The following example demonstrates how to accomplish it via CSOM:
/// <summary>
/// Hide the content type from List
/// </summary>
/// <param name="ctx"></param>
/// <param name="listTitle"></param>
/// <param name="ctName">The name of content type to hide</param>
private static void HideContentTypeFromList(ClientContext ctx, string listTitle,string ctName)
{
var list = ctx.Web.Lists.GetByTitle(listTitle);
//List Content Types
ctx.Load(list, l => l.ContentTypes, l => l.RootFolder.UniqueContentTypeOrder);
ctx.ExecuteQuery();
var contentTypeOrder = (from ct in list.ContentTypes where ct.Name != ctName select ct.Id).ToList();
list.RootFolder.UniqueContentTypeOrder = contentTypeOrder;
list.RootFolder.Update();
ctx.ExecuteQuery();
}
Usage
using (var ctx = new ClientContext(webUri))
{
HideContentTypeFromList(ctx, listTitle, "Workflow Task (SharePoint 2013)");
}
| common-pile/stackexchange_filtered |
Redux - How to await getting the state from useSelector
What is the best way to await the data coming from useSelector. What I mean by this is that I have a async action which is being dispatched using redux-thunk or to be precise createAsyncThunk. Everything works really fine with dispatch but the problem I am having is that I want to show certain component and pass the state from the useSelector as a prop.
Since it is the async action it needs to wait a little bit to get me the data, but I need that data to show the users a certain component just like I said, so I am passing the state as a prop, but I end up having a null value since I passed the prop before I got the data back. I am also using the Firebase as a, lets say API.
This is my code:
const ProfileSection = () => {
const [account, setAccount] = useState([]);
const user = useSelector((state) => state.user.user);
useEffect(() => {
onAuthStateChanged(authFirebase, (user) => {
if (user) {
dispatch(getUser(user.email));
setAccount(user);
}
});
}, [user]);
console.log(account);
return (
<>
{account && (
<Container className="py-5">
<div className="profile-section">
<Row>
<ProfileData user={account[0]} />
<ProfileForm user={account[0]} />
</Row>
</div>
</Container>
)}
</>
);
};
As you can see the components ProfileData and ProfileForm are using this state as a prop.
I have an idea where I would just use the useEffects on both of the components.
Also, I need this state to get default value to a useState state.
This is what I mean by this:
const initialState = {};
if (user) {
initialState.firstName = user.firstName;
initialState.email = user.email;
initialState.lastName = user.lastName;
}
const [formData, setFormData] = useState(initialState);
There is no waiting in React. Your component has to render the instant the parent component renders a <ChildComponent>. That will change in the future with React Suspense, but at the moment that is how React works.
Your component will have to take in account that it will be rendered before data is ready, check for that and in that case do something like return <div>loading...</div> instead of trying to access the data.
| common-pile/stackexchange_filtered |
boost ASIO server segmentation fault
I created a server using Boost ASIO. It builds fine but as soon as I run it, it gives segmentation fault. Can't really figure out this behaviour.
Also, I read that this may be due to me not initialising the io_service object explicitly. If, that's the case then how do I modify this code so that I don't have to pass io_service object from outside the class.
Below is my code:
#include <iostream>
#include <string>
#include <memory>
#include <array>
#include <boost/asio.hpp>
using namespace boost::asio;
//Connection Class
class Connection : public std::enable_shared_from_this<Connection>{
ip::tcp::socket m_socket;
std::array<char, 2056> m_acceptMessage;
std::string m_acceptMessageWrapper;
std::string m_buffer;
public:
Connection(io_service& ioService): m_socket(ioService) { }
virtual ~Connection() { }
static std::shared_ptr<Connection> create(io_service& ioService){
return std::shared_ptr<Connection>(new Connection(ioService));
}
std::string& receiveMessage() {
size_t len = boost::asio::read(m_socket, boost::asio::buffer(m_acceptMessage));
m_acceptMessageWrapper = std::string(m_acceptMessage.begin(), m_acceptMessage.begin() + len);
return m_acceptMessageWrapper;
}
void sendMessage(const std::string& message) {
boost::asio::write(m_socket, boost::asio::buffer(message));
}
ip::tcp::socket& getSocket(){
return m_socket;
}
};
//Server Class
class Server {
ip::tcp::acceptor m_acceptor;
io_service m_ioService ;
public:
Server(int port):
m_acceptor(m_ioService, ip::tcp::endpoint(ip::tcp::v4(), port)){ }
virtual ~Server() { }
std::shared_ptr<Connection> createConnection(){
std::shared_ptr<Connection> newConnection = Connection::create(m_ioService);
m_acceptor.accept(newConnection->getSocket());
return newConnection;
}
void runService() {
m_ioService.run();
}
};
int main(int argc, char* argv[]) {
Server s(5000);
auto c1 = s.createConnection();
//do soething
s.runService();
return 0;
}
You are facing initialisation order issues. In your class Server, you have declared m_acceptor before m_ioService and using the uninitialized io_service object to construct the acceptor.
Just reorder the declarations inside the class. Surprisingly clang did not give any warning for this.
class Server {
io_service m_ioService ;
ip::tcp::acceptor m_acceptor;
public:
Server(int port):
m_acceptor(m_ioService, ip::tcp::endpoint(ip::tcp::v4(), port)){ }
virtual ~Server() { }
std::shared_ptr<Connection> createConnection(){
std::shared_ptr<Connection> newConnection = Connection::create(m_ioService);
m_acceptor.accept(newConnection->getSocket());
return newConnection;
}
void runService() {
m_ioService.run();
}
};
| common-pile/stackexchange_filtered |
some people abroad cannot access my website
I get signals that people outside my country (nl) can not access my website. they say they see the Apache placeholder. It is just in some cases.
Is there something wrong with my dns?
m.skiweather.eu<IP_ADDRESS>A
skiweather.eu<IP_ADDRESS>A
mail.skiweather.eu<IP_ADDRESS>A
skiweather.eumail.skiweather.euMX (10)
smtp.skiweather.eu<IP_ADDRESS>A
pop.skiweather.eu<IP_ADDRESS>A
www.skiweather.eu<IP_ADDRESS>A
skiweather.eudns1.vpshosting.nlNS
skiweather.eudns2.vpshosting.nlNS
skiweather.eudns1.vpshosting.nl<EMAIL_ADDRESS>2014081800 14400 3600<PHONE_NUMBER>SOA
skiweather.eudns3.vpshosting.nlNS
*.skiweather.eu<IP_ADDRESS>A
gfx.skiweather.eu<IP_ADDRESS>A
cdn.skiweather.eu<IP_ADDRESS>A
skiweather.eugoogle-site-verification=gtRAq2UWkOKRq1ITaaUuUhxqDh077OwH5aadHCX7TbcTXT
@.skiweather.euv=spf1 a mx ip4:<IP_ADDRESS> include:_spf.google.com ~allSPF
skiweather.eu2a01:7c8:aabb:5e4:5054:ff:fe74:b8cdAAAA
Your DNS seems fine. Checking all your 3 nameservers return the same, correct, IP:
dig @dns1.vpshosting.nl skiweather.eu
dig @dns2.vpshosting.nl skiweather.eu
dig @dns3.vpshosting.nl skiweather.eu
In addition, https://intodns.com/skiweather.eu doesn't report any problems.
A problem though is that the https site (https://skiweather.eu/) returns:
Welcome to skiweather.eu
To change this page, upload a new index.html to your private_html folder
This is unrelated to DNS and regards configuration on your webserver which seems to be Apache httpd. So you'll have to check the <VirtualHost> block for port :443. You should make it look like the one for :80 (but do not remove the certificate related directives).
p.s your SSL certificate is self signed and not good. If you care to have proper https on your site have a look at https://letsencrypt.org/
| common-pile/stackexchange_filtered |
Exception in Install4j when creating an 32 bit Installer with bundled JRE
Using Apache ANT I create a JRE bundle of a 32 bit JRE 1.8.202 using createbundle.exe:
<property name="CREATEBUNDLE" value="${install4j.path}/bin/createbundle.exe" />
<exec executable="${CREATEBUNDLE}">
<arg value="-o" />
<arg value="${install4jJREBundleDir}/${CURRENT_JRE_NAME}/" />
<!-- input -->
<arg value="${unzippedJREDirectory}/${JREDirName}/" />
</exec>
<!-- Get filename of created JRE Bundle -->
<fileset id="contents" dir="${install4jJREBundleDir}/${CURRENT_JRE_NAME}/" includes="*.tar.gz" />
<pathconvert property="INSTALL4J_JREBUNDLE" refid="contents" />
Using this bundle I try to create a 32 bit installer for my application:
<target name="installer.internal">
<install4j projectfile="${i4jprojectfile}" verbose="true" mediatypes="${i4jmediatypes}" destination="${dist}" >
<vmParameter value="-Dinstall4j.timestampUrl=${INSTALL4J_TIMESTAMP_URL}"/>
<variable name="BUILD_VERSION" value="${BUILD_VERSION}" />
<variable name="SOFTWARE_VERSION" value="${SOFTWARE_VERSION}" />
<variable name="PLATFORM_DETAIL_STRING" value="${PLATFORM_DETAIL_STRING}" />
<variable name="INSTALL4J_JREBUNDLE" value="${INSTALL4J_JREBUNDLE}" />
</install4j>
</target>
The following error is thrown when creating the installer:
350 [install4j] com.exe4j.a.d: Cannot bundle a 64-bit JRE with a 32-bit media file.
351 [install4j] at com.install4j.b.g.g.a(ejt:97)
352 [install4j] at com.install4j.b.b.a(ejt:175)
353 [install4j] at com.install4j.b.i$a.c(ejt:846)
354 [install4j] at com.install4j.b.i$a.b(ejt:837)
355 [install4j] at com.install4j.b.i.b(ejt:163)
356 [install4j] at com.install4j.Install4JApplication.c(ejt:479)
357 [install4j] at com.exe4j.a.a(ejt:342)
358 [install4j] at com.install4j.Install4JApplication.main(ejt:94)
359 [install4j] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
360 [install4j] at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
361 [install4j] at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
362 [install4j] at java.lang.reflect.Method.invoke(Unknown Source)
363 [install4j] at com.exe4j.runtime.LauncherEngine.launch(LauncherEngine.java:85)
364 [install4j] at com.exe4j.runtime.WinLauncher.main(WinLauncher.java:94)
365 [install4j] at com.install4j.runtime.launcher.WinLauncher.main(WinLauncher.java:25)
366 [install4j] install4j: compilation failed. Reason: Cannot bundle a 64-bit JRE with a 32-bit media file.
The JRE in the bundle is 32 bit, so the error doesn't really make sense.
Edit: I tried using install4j v7.0.18 and Install4j8.
What is the name of the JRE bundle file?
createbundle.exe -o c:\jres\jre-8u202-windows-i586 c:\temp\tmp_jre_package-cbuild\jre1.8.0_202 The bundle file created is called windows-x86-1.8.0_202.tar.gz
Are you sure that you are actually using that bundle file? This message is only displayed if the file name contains "x64", "amd64", "arm64" or "aarch64".
We set the "INSTALL4J_JREBUNDLE" property to the windows-x86-1.8.0_202.tar.gz bundle path. So yes, I think we are using that bundle. So install4j just parses the bundle file name to check for 64- or 32 bit JRE?
INSTALL4J_JREBUNDLE must be one of your variables, do you use that in the manual configuration on the "Bundled JRE" step of the media wizard? Try adding the path explicitly. And yes, the architecture is determined from the file name.
I think I solved it. The architecture is determined from the absolute path of the bundle file. Our bundle file resides in a folder called 'c:\src\Windows10_x64...' Because of the 'x64' in the path install4j thought the bundle is 64 bit.
The architecture is determined from the absolute path of the bundle file. Our bundle file resides in a folder called 'c:\src\Windows10_x64...' Because of the 'x64' in the path ('Windows10_x64') Install4j thought the bundle is 64 bit.
Edit: The solution was to use a relative path for the bundle file omitting the 'Windows10_x64' folder.
Thank you, we will fix this for the next bugfix release
| common-pile/stackexchange_filtered |
debugPrint works in release version in flutter
in flutter when I run the app in release mode the debugPrint statements print data which I don't want to appear any ideas why this is happening ?
https://stackoverflow.com/q/76931009/12349734
debugPrint will print values in release mode. Its purpose is not to avoid print commands in release mode.
DebugPrint aims to avoid dropping messages on platforms that rate-limit their logging (for example, Android).
for example, you are trying to print a huge API response but it will not print full values because there is a set limit of statement length in a simple print command. Now, using debugPrint, you can print the whole response without limit.
Example
print("THIS IS A VERY BIG RESPONSE...") - Output THIS IS A VE....
debugPrint("THIS IS A VERY BIG RESPONSE...") - Output THIS IS A VERY BIG RESPONSE...
Note: In above example instead of "THIS IS A VERY BIG RESPONSE..." assume a very big value.
for more infor please reffer to docs.
If you want to avoide print values in production. Create a method and use it.
void customPrint(String input)
{
if(kDebugMode) print(input);
}
That's how it is supposed to work. Maybe the name got you confused, but the docs are pretty clear:
The debugPrint function logs to console even in release mode. As per convention, calls to debugPrint should be within a debug mode check or an assert
You can disable all the debugPrint logs into production build by adding following code
void main() {
if (kReleaseMode) {
debugPrint = (String? message, {int? wrapWidth}) => null;
}
runApp(
MyApp()
);
}
| common-pile/stackexchange_filtered |
Retrieve related table and select fields from primary table using Laravel Artisan
In the following code, The Users table has a related table phoneNumbers. When I retrieve a list of all users like this,
return Person::with('phoneNumbers')->get();
everything works fine. However, when I attempt to specify a list of columns to return from the Person table, the phone_number returns empty.
return Person::with('phoneNumbers')
->get(['fname','lname', 'email']);
If I add the number field or phone_number.number to the get array, then I get an error as an undefined column. What is the laravel way of handling this.
Try this:
return Person::select(['your_foreign_key', 'fname','lname', 'email'])
->with('phoneNumbers')get();
I'm still getting an empty array for phone_numbers
What is the fk for the relation? Place it inside the select and it should work
Thanks Giovanni, You are correct. For anyone who stumbles upon this, both of the following work. return Person::with('phoneNumbers')
->get(['id','fname','lname', 'email']);
return Person::select(['id', 'fname','lname', 'email'])
->with('phoneNumbers')->get();
| common-pile/stackexchange_filtered |
Parralex scroll is not working in Mobile and tabs ( Laravel )
I am having parallax website in laravel, it working fine in desktop version but when i open the website in Devices. Its effect is not working. Zoomed images are shown but page scrolling is not working.
| common-pile/stackexchange_filtered |
Why is the amu of chlorine-35 less than 35?
My book says that a proton weighs 1.0073u, a neutron weighs 1.0087u, and an electron weighs 0.00055u.
Now, why is the mass of chlorine-35 equal to 34.969? Are there not 17 protons, 18 neutrons, and 17 electrons? I calculated it and it sums to around 35.29. Where did I go wrong?
It did not go wrong. The average mass per nucleon decreases toward iron, and then increases toward uranium. Where do you think nuclear fusion and fission take their energy from ? Check masses of 4He and 16O, or Fe isotopes.
hi! my book said that all protons are the same weight, so goes with neutrons and electrons. where did i go wrong when I simply added the weights?
You have not counted mass loss due their bound energy. $\Delta E = \Delta m \cdot c^2$
oh cool! my book did not teach about that yet, so good to know. Thanks for helping me! :)
Related question and answer.
E.g. hydrogen to helium stellar fusion means loss of 0.7% of the mass.
Every proton and neutron is loosing a small part of their masses when they are included in a nucleus.
You need to account for the energy released when nucleons and electrons come together and form a Cl-35 atom. Its called the Binding Energy.
This sort of equation can help to explain :
(Rest Mass Energy of Individual nucleons,electrons*) - (Various Binding Energies) = (Rest Mass Energy of Natural)
*edit
ok thanks! i get it now, since the book did not say anything about binding energy.
Also, I used the term mass-energy. You can interpret it as actual mass, according to the mass-energy equivalence ( the famous E=mc^2 ).
@12345bird As mass of subatomic particles is used to be expressed in equivalent units of energy, usually MeV.
should be: (Rest Mass Energy of Individual particles, neutons, protons and electrons) - (Various Binding Energies) = (Rest Mass Energy of Natural Nucleus) // The electron binding energies are small compared to the nuclear binding energies, but easily measurable today.
Oh noted, I'm not really up to date on new technologies. I'll make the appropriate edit. Thanks!
| common-pile/stackexchange_filtered |
discord.py message.channel.send not working
I am making a blackjack game using discord.py, I am changing the value of Ace from 11 to 1 instead but no message is being sent to the channel and I am not getting any errors.
def ask_A(self):
num_A = []
for c in range(0, len(self.deck)):
if self.deck[c].get_value() == "A" and self.deck[c].get_points() == 11:
num_A.append(c)
for i in num_A:
message.channel.send(
"Your current cards are " + str(self.print_cards()) + ", Total is " + str(self.sum_cards()) + "\n")
self.deck[i].change_points(1)
message.channel.send("Changed value of Ace to prevent loss")
message.channel.send("Your cards are " + str(self.print_cards()) + ", Total is " + str(self.sum_cards()) + "\n")
Are you sure you are appending entries into num_A (have you verified with print statements or similar)?
There are no entries. Previously I made it so that the system prints into the console whether or not to switch the value of Ace. That was dumb because everyone will switch to Ace to prevent loss.
I made it an async method and await message.channel.send everything I wanted to change.
You're forgetting to await your statements. Anything in the docs that is a coroutine needs to have await expression.
Example:
await message.channel.send("Hello! This is my message")
Read up about Async IO here.
| common-pile/stackexchange_filtered |
Does this non-negative function, with no stationary points, have only descent directions close to a constraint set?
Suppose $P: \mathbb{R}^n \rightarrow \mathbb{R}_{\ge 0} $ is a differentiable map, with $P(x) = 0 \ \forall x \in \mathcal{X}$ and $P(x) > 0 \ \forall x \in \mathcal{X}^c$. Further, suppose $P$ has no stationary points in $\mathcal{X}^c$, i.e. $\nabla P(x) \ne 0 \ \forall x \in \mathcal{X}^c$.
My intuition is that $P$ eventually has a descent direction when we approach $\partial \mathcal{X}$ from $\mathcal{X}^c$. I need to make this more precise! For example, can we show that
$$ \forall x \in \partial \mathcal{X} ~ \exists \varepsilon >0 : \forall y \in \mathcal{X}^c ~ \lVert x-y\rVert<\varepsilon \Rightarrow \nabla P(y)^T(x-y)<0 ?$$
Here is what I thought of:
For $x\in \partial \mathcal{X}$ and $y \in \mathcal{X}^c$ Taylor tells us that
$$0 = P(y) + \nabla_xP(y)^\top(x-y) + o(\lVert x-y\rVert). $$
So this is almost what I need. However, I don't see that I can conclude here using $P(y) > 0$ that
$$ \nabla_xP(y)^\top(x-y) < 0 $$
for $y$ close to $x$. Because, although $0 \approx P(y) + \nabla_xP(y)^\top(x-y)$, we also have that $P$ and all differentials decay to zero as we approach the boundary. I also thought about the MVT, but this doesn't seem to help since I need to keep my $y$ (as above) flexible.
It would be helpful if someone could point out whether this is obvious or whether I need additional assumptions. You may assume $\mathcal{X}$ to be compact.
I reposted this from https://math.stackexchange.com/posts/4055496/edit.
I welcome suggestions to improve the title. Thanks.
Why not the mean value theorem? For every $y \in \mathcal{X}^c$, there is $\lambda \in (0,1)$ such that $P(x) = 0 = P(y) + \nabla P(y + \lambda(x-y))^\top(x-y)$. Hence $x-y$ is a descent direction in the intermediate point $y + \lambda(x-y)$.
The problem is, the point where I have the descent direction is $z=y+\lambda(x-y)$.
However, for my problem, I need that $z$ is a specified point or at least arbitrarily close to some other point $z'$ (we can use continuity), which we can make arbitrarily close to the boundary.
Alright so a degree of explicitness is needed. I suppose you would need to assume some more on the function $P$ then. For instance, if you require the norm of $\nabla^2 P$ to be bounded on a neighborhood of $\mathcal{X}$, then you get a uniform estimate on the $o(|x-y|)$ term and this should lead to a more explicit result.
It is unclear what you want to show. Is it the following: $\forall x\in\partial X\ \exists\epsilon>0\ \forall y\in X^c\ |y-x|<\epsilon\implies\nabla P(y)^T(x-y)<0$? Here $X:=\mathcal X$. Placing the quantifiers $\forall$ and $\exists$ correctly and unambiguously is usually very important.
Yes, you are right, this would be sufficient for my problem. Thanks. I edited the question.
$\newcommand\R{\mathbb R}\newcommand\ep\epsilon\newcommand\bad{\text{bad}}$One would think that the answer is "of course no, descent does not have to monotonic". However, the no stationary points condition is a strong one. So, the answer actually is "no, but the effect seems to be small and require fine tuning to be seen".
Indeed, let $n=2$, $f:=P$, and $X:=\mathcal X=\{0\}$, so that $X^c=\R^2\setminus\{0\}$. Let us seek the counterexample of the form
\begin{equation*}
f(r,t)=g(r)\Big(2+\sin\frac{h(r,t)}r\Big),\tag{1}
\end{equation*}
where $r\in(0,\infty)$ and $t\in\R$ are the polar coordinates of a point in $X^c$; $g$ is differentiable, with $g(0+)=0$, $g'>0$, and $g'(0+)=0$; and $h(r,t)$ is differentiable in $(r,t)\in X^c$ and periodic in $t$ with period $2\pi$; we also assume that $h(r,t)\to1$ uniformly in $t$ as $r\downarrow0$, so that $\sin\frac{h(r,t)}r$ in (1) is highly oscillating as $r\downarrow0$. Here we identify $X^c$ with the set $(0,\infty)\times(-\pi,\pi]$ of the pairs $(r,t)$ of polar coordinates.
The partial derivatives of $f(r,t)$ in $r$ and $t$ are
\begin{equation*}
f'_r(r,t)=g'(r) \Big(2+\sin\frac{h(r,t)}r\Big) \\
+\frac{g(r)}{r^2}\,(r h'_r(r,t)-h(r,t))
\cos\frac{h(r,t)}r\tag{2}
\end{equation*}
and
\begin{equation*}
f'_t(r,t)=\frac{g(r)}r\,h'_t(r,t)\cos\frac{h(r,t)}r.\tag{3}
\end{equation*}
We need to ensure the no stationary points condition, that is, the condition that, for any $(r,t)\in X^c$, either $f'_r(r,t)\ne0$ or $f'_t(r,t)\ne0$. If $f'_t(r,t)=0$ for some $(r,t)\in X^c$, then either (i) $\cos\frac{h(r,t)}r=0$ or (ii) $h'_t(r,t)=0$. In case (i), $f'_r(r,t)=g'(r) \big(2+\sin\frac{h(r,t)}r\big)>0$.
Consider now case (ii), which will necessarily occur for each real $r>0$, at least for two values of $t\in(-\pi,\pi]$, where the maximum and minimum of $h(r,t)$ in $t$ occur. Note that
\begin{equation*}
k:=\max_{t\in(-\pi,\pi]}\Big|\frac{\cos u}{2+\sin u}\Big|=\frac1{\sqrt3},\tag{4}
\end{equation*}
with the maximum attained at $u\in\{-\pi/6,-5\pi/6\}$. So, by (2), for $f'_r(r,t)\ne0$ it is enough that
\begin{equation*}
\frac{r^2g'(r)}{g(r)}>\max_{t\in(-\pi,\pi]}|r h'_r(r,t)-h(r,t)| \tag{5}
\end{equation*}
(for real $r>0$).
At the points $t$ where the extrema of $|h(r,t)|$ in $t$ occur, we have $r h'_r(r,t)=0$ and hence $|r h'_r(r,t)-h(r,t)|=|h(r,t)|$. At all points $(r,t)\in X^c$ with such $t$, we want $h'_r(r,t)$ to have the same sign as $h(r,t)$, to make the restriction (5) as weak as possible.
Certain considerations suggest that it may make sense to define the differentiable $2\pi$-periodic in $t$ function $h$ by the formula
\begin{equation*}
h(r,t):=1-\frac{r^2}{1+r^2}\, t^2 (\pi -| t| )^2\tag{6}
\end{equation*}
for $t\in(-\pi,\pi]$. Then case (ii) $h'_t(r,t)=0$ (for $t\in(-\pi,\pi]$) means that $t\in\{0,\pi\}$, and
\begin{equation*}
f'_r(r,t)\big|_{t\in\{0,\pi\}}=g'(r) \Big(2+\sin\frac1r\Big)
-\frac{g(r)}{r^2}\,\cos\frac1r.\tag{7}
\end{equation*}
If $g$ solves the ODE $g'(r)=k\frac{g(r)}{r^2}$ (with $k$ as in (4)) -- e.g. when $g(r)=e^{-k/r}$, then, by (7), we will have $f'_r(r,t)\ge0$. Now, to ensure that $f'_r(r,t)>0$ (still in case (ii) $h'_t(r,t)=0$), it is enough to let
\begin{equation*}
g(r):=(1+cr)e^{-k/r}
\end{equation*}
for any fixed real $c>0$ and all real $r>0$. Indeed, then
\begin{equation*}
r^2e^{k/r}\,f'_r(r,t)\big|_{t\in\{0,\pi\}} \\
=
\Big(2+\sin\frac1r\Big) (k(1+cr)r+c r^2)-(1+c r) \cos\frac1r \\
\ge\Big(2+\sin\frac1r\Big)c r^2>0.\tag{8}
\end{equation*}
Thus, we have a nonnegative differentiable function on $\R^2$ vanishing only on $X=\{0\}$, with no stationary points in $X^c$.
On the other hand,
\begin{equation*}
\bad(r):=f'_r(r,1)\,\frac{kr^2 e^{k/r}}{k + c k r + c r^2} \\
=
k(2+\sin u_r) -q(r) \cos u_r,\tag{9}
\end{equation*}
where
\begin{equation*}
u_r:=\frac1r-\frac{(\pi -1)^2 r}{1+r^2}\sim\frac1r\tag{10}
\end{equation*}
and
\begin{equation*}
q(r):=\frac{k (1+(3-2 \pi +\pi ^2) r^2-(\pi -2) \pi r^4) (c r+1)}{(1+r^2)^2(c k r+c r^2+k)} \\
=1+((\pi -1)^2-c\sqrt3) r^2+O(r^3)
\end{equation*}
as ($r\downarrow0$), so that
\begin{equation*}
q(r)>1+4r^2>1\tag{11}
\end{equation*}
eventually (that is, for all small enough $r>0$) if $c=1/10$ (say).
Moreover, in view of (10), the equation $u_r=-\pi/6+2\pi m$ has solutions $r_m\sim1/(2\pi m)$ for all large enough natural $m$. So (cf. (4)), for such $m$, by (11),
\begin{equation*}
\bad(r_m)=
\frac{\sqrt3}2(1-q(r_m))<-\frac{\sqrt3}2\,4r_m^2<0,
\end{equation*}
whence, by (9), the radial derivative $f'_r(r_m,1)$ is strictly negative, whereas $r_m\downarrow0$. $\Box$
Here is the graph $\{(r,\bad(r))\colon0<r<1/10,-1/100<\bad(r)<1/100\}$:
Thanks a lot for your counter-example. I will go through it and come back to you soon!
Set for instance, in polar coordinates:
$$P(r,\theta):=e^{-\frac1{4r}}\Big(2+\cos\big(\theta+\frac1r\big)\Big).$$
It is quickly checked that this defines a $C^\infty$ function on $\mathbb{R^2}$ which is strictly positive on $\mathbb{R^2}\setminus\{0\}$ and vanishes at the origin, with $ \partial_r P $ changing sign in any nbd of the origin, and such that $\nabla P$ vanishes only on the origin (if $r>0$, and $\partial_\theta P$ vanishes, certainly $\partial_r P$ does not).
| common-pile/stackexchange_filtered |
list is showing incorrect entry using MVVM and sqlite
im using sqlite with mvvm..but when i click add new and submit comming back to listing page it is not updated record in list.but when i kill app again come to list page it is showing record with duplicate entries of same record.i dont know where my code is getting wrong..plz help
db helper:-
public class DbHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2;
static final String DATABASE_NAME = "kuncorosqlite.db";
public static final String TABLE_SQLite = "sqlite";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ADDRESS = "address";
ArrayList<HashMap<String, String>> listofMaps = new ArrayList();
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String SQL_CREATE_MOVIE_TABLE = "CREATE TABLE " + TABLE_SQLite + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY autoincrement, " +
COLUMN_NAME + " TEXT NOT NULL, " +
COLUMN_ADDRESS + " TEXT NOT NULL" +
" )";
db.execSQL(SQL_CREATE_MOVIE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SQLite);
onCreate(db);
}
public MutableLiveData<ArrayList<HashMap<String, String>>> getAllData() {
MutableLiveData<ArrayList<HashMap<String, String>>> wordList;
wordList = new MutableLiveData<ArrayList<HashMap<String, String>>>();
String selectQuery = "SELECT * FROM " + TABLE_SQLite;
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put(COLUMN_ID, cursor.getString(0));
map.put(COLUMN_NAME, cursor.getString(1));
map.put(COLUMN_ADDRESS, cursor.getString(2));
listofMaps.add(map);
wordList.postValue(listofMaps);
} while (cursor.moveToNext());
}
Log.e("select sqlite ", "" + wordList);
database.close();
return wordList;
}
public void insert(String name, String address) {
SQLiteDatabase database = this.getWritableDatabase();
String queryValues = "INSERT INTO " + TABLE_SQLite + " (name, address) " +
"VALUES ('" + name + "', '" + address + "')";
Log.e("insert sqlite ", "" + queryValues);
database.execSQL(queryValues);
database.close();
}
public void update(int id, String name, String address) {
SQLiteDatabase database = this.getWritableDatabase();
String updateQuery = "UPDATE " + TABLE_SQLite + " SET "
+ COLUMN_NAME + "='" + name + "', "
+ COLUMN_ADDRESS + "='" + address + "'"
+ " WHERE " + COLUMN_ID + "=" + "'" + id + "'";
Log.e("update sqlite ", updateQuery);
database.execSQL(updateQuery);
database.close();
}
public void delete(int id) {
SQLiteDatabase database = this.getWritableDatabase();
String updateQuery = "DELETE FROM " + TABLE_SQLite + " WHERE " + COLUMN_ID + "=" + "'" + id + "'";
Log.e("update sqlite ", updateQuery);
database.execSQL(updateQuery);
database.close();
}
}
viewmodel:-
public class Viewmodell extends AndroidViewModel {
private DbHelper repository ;
MutableLiveData<ArrayList<HashMap<String, String>>> allNotesLivedata;
public Viewmodell(@NonNull Application application) {
super(application);
repository = new DbHelper(application);
allNotesLivedata = repository.getAllData();
}
void insert(String name,String Address) {
repository.insert(name,Address);
}
void update(int id, String name, String address) {
repository.update(id,name,address);
}
void delete(int id) {
repository.delete(id);
}
public LiveData<ArrayList<HashMap<String, String>>> getAllNotes() {
return allNotesLivedata;
}
}
mainactivity (listing page):-
public class MainActivity extends AppCompatActivity {
ListView listView;
AlertDialog.Builder dialog;
List<Data> itemList = new ArrayList<Data>();
Adapter adapter;
DbHelper SQLite = new DbHelper(this);
Viewmodell viewmodell;
public static final String TAG_ID = "id";
public static final String TAG_NAME = "name";
public static final String TAG_ADDRESS = "address";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
SQLite = new DbHelper(getApplicationContext());
viewmodell = ViewModelProviders.of(this).get(Viewmodell.class);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
listView = (ListView) findViewById(R.id.list_view);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AddEdit.class);
startActivity(intent);
}
});
adapter = new Adapter(MainActivity.this, itemList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final String idx = itemList.get(position).getId();
final String name = itemList.get(position).getName();
final String address = itemList.get(position).getAddress();
Intent intent = new Intent(MainActivity.this, DetailsAct.class);
intent.putExtra(TAG_ID, idx);
intent.putExtra(TAG_NAME, name);
intent.putExtra(TAG_ADDRESS, address);
startActivity(intent);
}
});
getAllData();
}
private void getAllData() {
viewmodell.getAllNotes();
viewmodell.allNotesLivedata.observe(this, new Observer<ArrayList<HashMap<String, String>>>() {
@Override
public void onChanged(ArrayList<HashMap<String, String>> hashMaps) {
for (int i = 0; i < hashMaps.size(); i++) {
String id = hashMaps.get(i).get(TAG_ID);
String poster = hashMaps.get(i).get(TAG_NAME);
String title = hashMaps.get(i).get(TAG_ADDRESS);
Data data = new Data();
data.setId(id);
data.setName(poster);
data.setAddress(title);
itemList.add(data);
}
adapter.notifyDataSetChanged();
}
});
}
@Override
protected void onResume() {
super.onResume();
itemList.clear();
getAllData();
}
it is inside onchanged only..see properly @a_local_nobody
ahh i see, my bad
You need to debug your code in order to know what is the fault happening . There is nothing wrong with the code
@KaruneshPalekar if replace by postvalue by setvalue then duplication issue gone...but on resume the list not updating...only after killing application and then opening app then shows record in list
@a_local_nobody having issue in onResume now
This has something to do with your LiveData . debug liveData and see whether it is returning data when your data is updated .
@KaruneshPalekar i debug this line return allNotesLivedata; the new record is not returning
for example :-onresume it returning 6 record...after oncreate this livedata line returns 7 records
Viewmodel constructor is only is getting call on oncreate
Here I see you are having problems with LiveData.
Your LiveData seems to be having problems calling viewModel.getAllNotes() on the onResume() of your activity.
With you calling viewModel.getAllNote(), it actually returns LiveData, you don't set the value for that LiveData. That's why when you call viewModel.getAllNote() the LiveData allNotesLivedata is not triggered.
LiveData allNotesLivedata only actually triggers in Constructor of ViewModel via repository.getAllData(). repository.getAllData() is actually where you set the value for LiveData.
Replace the function getAllNotes() in the ViewModel in the following way:
public LiveData<ArrayList<HashMap<String, String>>> getAllNotes() {
return repository.getAllData();
}
Edit 1:
I am seeing you have duplicate entity. it's onResume() that is called multiple times in the Activity's lifecycle.
And when you call onResume(), you call the function getAllData() in DbHelper. You are setting the value for LiveData to listofMap.
I see you are not resetting the old list, and you are adding each new item received from SQLite to the old list. That results in listofMap consisting of old item + new item of SQLite (includes all previous record + new record). So please reset listofMap before adding new item from SQLite.
public class DbHelper extends SQLiteOpenHelper {
public MutableLiveData<ArrayList<HashMap<String, String>>> getAllData() {
...
if (cursor.moveToFirst()) {
listofMap = new ArrayList();
// Continue your code
do {
...
}
}
}
}
duplicates entries are getting on oncreate(first time)
after adding new records when comming back to list activity the new recored is seen n also again duplicates enteries enter...now total 4 times duplicate plus one new record is seen onResume
what might be the issue? @Duong
Because you call it at onResume(). And in getAllData() function of DbHelper, you are saying that every time you call getAllData() you are adding new values to listofMaps. You should clear listofMaps before adding it.
@IRONMAN I have updated the comment already.
@IRONMAN Happy to help!
hi can u help me out here -> https://stackoverflow.com/questions/76480901/facing-issue-while-making-dynamic-views-using-relative-layout
| common-pile/stackexchange_filtered |
Can we define name as array in submit button?
Can we define name of a submit button as list of array??. If yes then if S1 was clicked the values of the text input should be transfer to one of the input box provided in new div and if S2 was clicked then value should be go below the previous input box. and number of input box in new div depend upon the number of submit button.
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
name="Main" method="POST">
<input type="text" name="p1[]" value="">
<input type="text" name="p1[]" value="">
<button type="submit" name="S[]">S1</button>
<button type="submit" name="S[]">S2</button>
<button type="submit" name="S[]">S3</button>
</form>
<?php
if (isset($_REQUEST['submit'])) {
foreach($_POST['p1'] as $i)
{
echo "Hobbies are :".$i."<br>";
}
}
?>
Not getting any output from this.
You don't have $_REQUEST['submit'] maybe $_REQUEST['S']? Also, why mixing $_REQUEST and $_POST?
@AbraCadaver $_REQUEST['S'] also not working.. using $_POST to get value from textbox.
print_r($_POST); but you'll not be able to distinguish between the 3 buttons, you'd need: name="S[1]" name="S[2]" name="S[3]" or something.
Instead of checking for isset($_REQUEST['submit']), have you considered instead checking $_SERVER['REQUEST_METHOD'] === 'POST'?. This may be more appropriate.
Separate the value attribute of your submit-buttons, and check which one was submitted - do the actions needed based on which one was selected.
@B.Fleming I just use your method its showing my output. but suppose i want to check the value of text box and depend upon that value should be display.
| common-pile/stackexchange_filtered |
What should a literary writer read?
Everyone knows that a writer should read, but the question is what?
The question I would like to ask here is: what books should a literary writer have read? What are the critical reference points that anyone in the game needs to have exposure to? What are perhaps lesser known works that are nevertheless important?
This is an open-ended question and clearly will entail a great deal of subjectivity, but writing is like that anyway.
So I don't actually think anyone could provide you with a useful list of books here, because individuality, different approaches, style, subjectivity, blah blah all that.
But an approach that works is this: read what you like, be it sci fi, fantasy, whatever. Harry Potter. Then sift through interviews and wikis of the authors you admire, and find their influences and teachers. Then read the stuff written by those. And enjoy it, but also, once you're done, ruminate on how they connect to the writing that brought you to them in the first place. Read them more than once if you have to. Good books generally need to be read more than once anyway.
This approach lets you get more directly at what you want to do, and leave out all the classic junk you don't really need.
Yes, it does take a little bit of effort - but hopefully you read enough for fun to have a list of authors you can siphon information from, even if one of them doesn't have a lot available. I mean reading a lot for fun is how you get to be a good writer. The best writers tend to read a lot.
It feels like you're asking for a literary canon, but really, I don't think there is one any more. Things are a lot more wide-open, with a lot less dead-white-male worship.
In terms of books that were really important to me (not that I'm a literary writer, but I tend to be a literary reader)... they've changed as time goes on. When I first read The Color Purple I was blown away by the dialect and the honesty, but it's not a book I've gone back to very often. I love re-reading Austen (Persuasion is my favourite) but I'm reading for the characters, not for the writing style, so I'm really not sure they'd help someone trying to read as a writer, rather than as a reader.
I agree with the other poster who suggested you try to narrow things down a little. Literary Fiction is a really broad category, but it can be broken down into sub-categories that might make more sense for you. Different cultural groups have different prominent writers - if you're African American, you should probably read Walker, Angelou, Morrison, Hughes, Wright, Du Bois, etc.. And it certainly wouldn't hurt for anyone else to read them, but if you're writing magical realism you might focus on just Morrison from that list and come to the others later, after you've read Gabriel Garcia Marquez and Haruki Murakami.
If you're writing some other sub-genre, I'd say you want to focus on other authors. So, really, it's pretty hard to pick one list that's going to be useful to everyone. Never hurts to read some Shakespeare, though!
It isn't what you read, but what you write that makes you great.
What do you mean by 'literary writer'? Do you mean James Joyce? Also, although we can identify loads of popular fiction that is bad writing, surely agreeing what is good writing and therefore choosing a list of novels is extremely subjective.
I mean 'literary' with the same level of detail as anyone who uses the term. I don't think genres are well-defined categories as much as nebulous guides. And as for the point of subjectivity, I already admitted that in my question. I was hoping instead of shooting the question down you would list a few books that blew your hair back. Maybe the question is badly stated? This is the second answer not to have answered it.
I take your comment on board. 'For Whom the Bell Tolls', '1984', 'Pride and Prejudice', 'Vanity Fair', 'Little Dorrit', 'Catch 22', 'Riders of the Purple Sage', novels by Evelyn Waugh, Dorothy L Sayers and Raymond Chandler -- might be starters on my list, but there are many others.
Thanks for your comment. FYI, the lack of response to this question really disappointed me and showed me that I'm probably wasting my time on this site, so I'm going to delete it.
Inferring that reading the right books can save someone from being a bad writer is ludicrous. Only repeatedly writing, and finishing, story after story can save someone from being a bad writer.
That said, all writers (all humans, really) should read equal parts fiction and non-fiction.
Fiction shows you how to write. As for specific titles, read whatever piques your interest, or is recommended based on your favorites. Setup a Goodreads account, add and rate the books you've read, and check out the recommendations.
Non-fiction shows you what to write. Read philosophies, histories, biographies, essays, and anything else of interest that exposes you to what individuals and communities think about their setting. This is food for original story ideas.
Which novels/stories you read is arguably less important than how you read. That's a topic for another thread.
'Inferring that reading the right books can save someone from being a bad writer is ludicrous.' Cool, you can take that up with Bolaño. I don't disagree with anything you said, but you have missed the point of the question. Perhaps the question is expressed badly. This site is a great means to tap into the resources of the community, which is what I was trying to do, kind of like in this question http://mathoverflow.net/questions/23478/examples-of-common-false-beliefs-in-mathematics
The point of your question is to compile a reading list that can save a writer from writing poorly. That's like asking for a list of paintings that could save a painter from painting poorly. No such thing! Further, if I had responded with titles from Allende, you would have scoffed at my recommendation. Therefore, to you I said, "Go read what you love. Nothing else matters."
Telling me the point of my own question? Telling me I would scoff at people? How dare you? You are acting like a total jerk. I already admitted the question could have been badly posed. You started with an ungenerous and superficial reading of my question and now you're trying to defend a bad answer. Read the very simple question again, including the title, this time without the Bolano quote and the single sentence afterwards you keep getting hung up on.
| common-pile/stackexchange_filtered |
babel-node no longer working in different directory
import credentials from '../config/credentials'
^^^^^^
SyntaxError: Unexpected reserved word
Yesterday babel-node was working fine. Today, in my testing directory, it no longer works. Oddly enough, it runs my app which uses ES6 no problem.
Version: 5.6.14
No idea what's causing this to happen.
I had the following .babelrc file
{
"stage": 0,
"ignore": [
"node_modules",
"bower_components",
"testing",
"test"
]
}
Which disallowed babel-node from working in the testing directory.
| common-pile/stackexchange_filtered |
Parallax effect on tile map layers
i am using three layers of tiled map and i want to give parallax effect on these layers.
my code is:
CCTMXTiledMap *city = CCTMXTiledMap::create("City.tmx");
CCTMXLayer* ForegroundLayer = city->layerNamed("ForeGround");
CCTMXLayer* BackgroundLayer1 = city->layerNamed("Background1");
CCTMXLayer* BackgroundLayer2 = city->layerNamed("Background2");
CCParallaxNode* voidNode = CCParallaxNode::create();
// NOW add the 3 layers to the 'void' node
voidNode->addChild(BackgroundLayer2, -1, ccp(0.4f,0.5f), CCPointZero);
voidNode->addChild(BackgroundLayer1, 1, ccp(2.2f,1.0f), ccp(0,-200) );
voidNode->addChild(ForegroundLayer, 2, ccp(3.0f,2.5f), ccp(200,800) );
voidNode->runAction(temp); //some action temp
addChild(voidNode);
It gives assertion failed: child->m_pParent==0
Same code works if we use sprites instead of TMXLayers.
what I have done wrong in this code?
The layers are already child nodes of the CCTMXTiledMap. A node can only have one parent.
You can try removing each layer from its parent first, the add them to voidnode. However chances are this won't work because the layers may depend on their tilemap parent.
great answer. this really worked. Thanks for your help. There is lot less information given on internet that's why your answer is very useful. Thanks again.
try this code
backgroundLayer->retain();
backgroundLayer->removeFromParentAndCleanup(false);
parallaxNode->addChild(backroundLayer, 0, Vec2(0, 0), Vec2(0, 0));//some points
backgroundLayer->release();
| common-pile/stackexchange_filtered |
How to use a declarative pattern on Observables that watch the network?
I have been trying to learn about the declarative pattern/approach in rxjs, which from my understanding it to not use .subscribe() directly in the typescript itself and use the async pipe instead.
I have a class that holds data about an image, and some of that data is a tags property which is an array of strings. Through the UI you can add/remove tags to this property. When you save a new item the value goes to the server via a websocket, and the socket will send a list of all the items tags back (including the newly added one).
So, I created a listener that listens for when the websocket responds with data related to the image tags. When it sees this message it should update all the tags in the object for this image.
Something like this pseudo code below:
interface FileInfo {
tags: string[];
}
@Component({
template: `
<div *ngIf="image$ | async as image">
<div *ngFor="let tag of image.tags">{{tag}}</div>
</div>
`
})
export class MyComponent {
image = new BehaviorSubject<FileInfo | null>(null);
image$ = this.image.asObservable();
ngOnInit() {
this.websocket.on('tags:image').pipe(
map(i => i.data) // i.data is an array of strings
tap(strs => this.image.value = strs)
);
}
}
Now when a message comes back it should update the image object and re-render the component.
Without using a subscribe on the this.websocket.on() how can this pattern/approach be possible? All this does is watch the network and modify a property on an object.
I modified the above to to this pattern, but I don't really like that I have to manage more than one property now when doing .next(), this approach doesn't seem right and seems like it is easy to get image.tags out of sync the value of tags$.
@Component({
template: `
<div *ngIf="image$ | async as image">
<div *ngFor="let tag of tags$ | async">{{tag}}</div>
</div>
`
})
export class MyComponent {
image = new BehaviorSubject<FileInfo | null>(null);
image$ = this.image.asObservable();
tags = new BehaviorSubject<string[]>([]);
tags$ = merge(this.tags, this.websocket.on('tags:image')).pipe(
map(i => i.data) // i.data is an array of strings
);
ngOnInit() {
// I want to get rid of this subscribe too
// However this is the next
this.manageService.$collectionEvents.subscribe(event => {
this.image.next(event.image);
this.tags.next(event.image.tags);
});
}
}
Instead of making a behaviorsubject and use asObservable, you can assign the observable you have built to this.image$ directly.
It would be like this (I've just made an observable data$ to simulate your web socket response):
image$ = new Observable<FileInfo>();
ngOnInit() {
const data$ = of({ data: ['string1', 'string2', 'string3'] });
this.image$ = data$.pipe(
map((i) => {
return { tags: i.data };
})
);
}
In your context
image$ = new Observable<FileInfo>();
ngOnInit() {
this.image$ = this.websocket.on('tags:image').pipe(
map((i) => {
return { tags: i.data };
})
);
}
The async pipe will automatically subscribe to image$ and also unsubscribe when the component is destroyed. It also handles updating html whenever the observable receives a new value.
Here's a stackblitz where I simulate the observable value changing every second: https://stackblitz.com/edit/angular-ivy-m2digv?file=src/app/app.component.ts
But this will never execute because it isn't subscribed to....
The async pipe automatically subscribes - try it : )
but I don't want to subscribe to the socket in the template
that will cause FileInfo.tags in the image subscription to get out of sync with the server
Your template remains exactly the same, that's why I didn't include it in my answer, I can make a stackblitz. The async pipe will update html whenever the observable receives a new value.
yes please, a stackblitz would be helpful!
Here you go: https://stackblitz.com/edit/angular-ivy-m2digv?file=src/app/app.component.ts
huh... I didn't know you could do what you did with data$ and image$ on line 26 I thought that you always had to subscribe to each one (one for data and one for image).
Yeah it's pretty neat. Nothing actually gets executed until something subscribes, each observable is just a code block to be executed later. pipe just tacks on more code to the end of it. So you just subscribe when you have your fully constructed code block.
I also didn't know that re-assigning to image$ would trigger the template rebuild, I thought it was just on a .next() call. Very cool!
Yeah that's the async pipe subscribing and then triggering a template render on change. Magic.
So, when I have more data in the object, it seems to just replace it with what is in there, so {url:'...', exif:[], tags:['a','b']} all seem to get replaced with {tags:['a','b','c']} can I merge the current value with the new value?
Yeah I think you're looking at the mergeMap pipe operator, might want to open a whole new question for that.
zip might also work too
Yeah I'm not too familiar with all the operators, you might be able to find someone that knows more if you open another question.
| common-pile/stackexchange_filtered |
How to remove all other users access from Shared workbook by using VBA?
I have shared workbook (Office 2016 ) ,
when I need to remove all other users from user access list
, I did manually and it takes long time.
Now, I found the below code to do that, but the problem in code is trying to remove me from this list
and this in not allowed and I got the error found in below photo.
Sub Remove_All_Users()
Dim UsrList()
UsrList = ThisWorkbook.UserStatus
For i = 1 To UBound(UsrList)
ThisWorkbook.RemoveUser (i)
Next
End Sub
Does this answer your question? How do I get the current user name in VBA?, and skip that user in the loop.
No it doesn't answer
Please [edit] your question and provide more details about why the earlier comment does not answer this question.
Is the issue due to the fact you need to remove all users, including yourself?
@Luuk , your provided answer give only current username and not remove other users from shared workbook.
As @Luuk suggested, get your username with Application.UserName (see MS documentation) or Environ ("UserName") and skip that user in the loop.
As described in MS documentation, Workbook.UserStatus property returns a 2D array containing:
1st element : user's name as a String
2nd element: last date of modification
This allows to test each User based on its name and delete it only if it's not you:
Sub Remove_All_Users()
Dim UsrList()
UsrList = ThisWorkbook.UserStatus
For i = 1 To UBound(UsrList,1)
If Not(UsrList(i,1) = Application.UserName) Then ThisWorkbook.RemoveUser (i)
Next
End Sub
If my userName is "Waleed" , how to skip from the loop?
Add a condition for deleting user from UsrList: If Not(UsrList(i) = Application.UserName) Then ThisWorkbook.RemoveUser (i)
@ Vincent ,this is not logic question , if you have answer it will be good from you , otherwise let other people try to help me .
@Waleed_wwm Try replacing this line ThisWorkbook.RemoveUser (i) in your code with the one I gave in my previous comment. It will delete users only if the user name isn't yours.
I tried and got this error "Subscript out of range" on this line: If Not(UsrList(i) = Application.UserName) Then
From what I can see, UsrList is populated as a 2D Array. As the name is the first element, try changing it to ThisWorkbook.RemoveUser (i, 1).
@SamuelEverson I was about to write this. It's explained in MS documentation about Workbook.UserStatus property: https://learn.microsoft.com/en-us/office/vba/api/excel.workbook.userstatus
@Waleed_wwm I edited my answer to include last comments.
Now works perfectly , Many thanks "Vincent" and everyone helped on this question.
@Waleed_wwm Don't take what I'm about to say in the wrong way, as I am trying to give you an advice. You come here with an issue about a shared workbook and some code. Primary purpose of StackOverflow is to help people when they have something they don't understand with conding, but it is NOT a way to get a piece of code perfectly written by others to solve your problem. We're here to give advices, and indicate things that may solve your issue, but NOT to write a complete code for you. If you're not familiar with coding, you should say it because it can change how people answer your questions.
@Waleed_wwm Based on your question and comments, either you're not familiar with coding, or you haven't look for a solution by yourself. At first I didn't know how to solve your issue, since I never wrote any code about user rights for shared workbook. But by just doing some google searches, looking for Workbook.UserStatus documentation, and trying to understand where the issue came from, the solution was in the end not very difficult to figure out. So if you ever face an issue, try to understand 'what does what', read documentation, and you should be able to solve most of your problems.
@Vincent. Right , I am not familiar with complex coding. I searched throughly until I found that code in my question. Anyway , many thanks for your patience and helpful answer.
I know this is an older thread but felt I needed to point out an error. In the line If Not(UsrList(i,1) = Application.UserName) Then ThisWorkbook.RemoveUser (i) the RemoveUser(i) eventually causes an error as i increments and the list gets shorter, causing i to go out of bounds. This is fixed by changing RemoveUser(i) to RemoveUser(1) as this will always remove the first user in the list regardless of list size.
| common-pile/stackexchange_filtered |
Ways to deal with es6 module paths and dependencies
What are some ways to deal with es6 modules and dependencies?
In particular I have 1 library i'd like to split into 3 modules. Let's call the library "salad" and uses "utensils" and "ingredients". Right now all 3 parts are part of the same library but I'd like to separate them. "utensils" is useful on its own. "ingredients" should be separate if only because it only includes a few common ingredients. It's perfectly valid to use the "salad" library with your own ingredients.
So, in actually trying to do it I run into issues. Utensils is easy, it has no dependencies
// utensils.js
export { fork, knive, spoon, }
salad is also easy, it has no dependences
// salad.js
export { chop, toss, dice }
but ingredients is where the issues show up
// ingredients.js
import { knive } from './utensils.js'; // what path here?
import { chop, dice } from './salad.js'; // what path here?
export { choppedLettuce, dicedTomates } // they use 'chop' and 'dice'
If everything is local and in my own project this is not so difficult but I want all 3 projects to be publically available and easily usable.
Use cases include
using with rollup/webpack
using live in the browser no build
using via npm with rollup/webpack
using in node no build
If I use npm based paths (assuming the packages are named 'utentils' and 'salad'
import { knive } from 'utensils';
import { chop, dice } from 'salad';
Then ingredients.js is no longer usable without npm and pacakge.json. No more live import in a browser
If I use local paths
import { knive } from './utensils.js';
import { chop, dice } from './salad.js';
It only works if I put all the files in the same folder which kind of defeats the purpose of separating them.
In other languages I'd probably end up adding include paths or some other way for ingredients.js be able to reference paths that are resolved later. I think webpack has some @symbol solution but that's webpack specific.
One other solution which seemed less than desirable was to have a setup function in ingredients.js to pass in the dependencies
// ingredients.js
export { setup, choppedLettuce, dicedTomates }
which would then be used like
import { knive } from './utensils.js';
import { chop, dice } from './salad.js';
import { setup, choppedLettuce, dicedTomates } from 'ingredients.js';
// pass in the deps so no paths needs to be ingredients.js
setup({knive, chop, dice});
That seems like a non-scalable solution.
It could also be that every function in ingredients takes needs to be passed salad and utensils. That seems yuck.
Is there a solution? Do I just need to have multiple versions of the libraries, some for npm based inclusion, others for live inclusion? Am I overlooking some obvious solution?
It's a nice use of metaphors, but I think the metaphor is a little bit off. An alternative might be that of a chef and a knife. Where the knife can chop(), slice(), and dice(). The chef can use any knife as long as it supports these methods. If you are okay with introducing a kitchen, you could leave it up to the developer to stock the kitchen with their choice of knife. The chef would no longer just have a knife, instead, the chef would have to go to the kitchen to get a knife.
maybe I chose bad example names but you can come up with dependencies that demo the issue. A physics library depends on a collison library. Both depend on math library. So what should the paths be on the import statements in the physics library?
apparently this is a known issue. .one proposed solution: import maps
IMO, the physics library and the collision library should manage their own math dependencies. They could very well end up being the same library, but ultimately it shouldn't matter if they are the same or if they are different as long as they produce the correct behaviour.
That's arguably the worst of all worlds. You'd get bloated code (multiple math libraries) and slow code (having to convert from one math library to the other). Physics requires collision therefore it has to interface with the collision library. If it uses it's own math library that just worse. But your comments are entirely irrelevant to the question
| common-pile/stackexchange_filtered |
JPA Unidirectional @OnetoMany fails
I have couple of failure cases for Unidirectional JPA2 @OnetoMany relationship
below is the code snippet
@Entity
@Table(name="CUSTOMER")
@Access(AccessType.FIELD)
public class Customer {
@OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
@JoinColumn(name="CUSTOMER_ID", referencedColumnName="CUSTOMER_ID")
private List<Address> customerAddresses;
....
}
In this case it fails to create Entity manager factory during server startup with the following error
DEBUG - Second pass for collection: xx.xxx.xxxxxxx.core.domainmodel.customerinfo.Customer.customerAddresses
DEBUG - Binding a OneToMany: xx.xxx.xxxxxxx.core.domainmodel.customerinfo.Customer.customerAddresses through a foreign key
DEBUG - Mapping collection: xx.xxx.xxxxxxx.core.domainmodel.customerinfo.Customer.customerAddresses -> CUSTOMER_ADDRESS
DEBUG - Unable to build entity manager factory
java.lang.NullPointerException: null
at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1456) ~[hibernate-core-4.3.6.Final.jar:4.3.6.Final]
The server startup is all good when I remove the referencedColumnName attribute from the @JoinColumn annotation
But when I try to persist the entity it fails below are the Hibernate generated traces for the failure(CUSTOMER_ID is the name of the identity generated PK column in CUSTOMER table and FK in the CUSTOMER_ADDRESS table)
DEBUG - Executing identity-insert immediately
DEBUG - insert into CUSTOMER (ESTABLISHMENT_DATE, ESTABLISHMENT_PLACE, MAJOR_PRODUCT, PAID_UP_CAPITAL, TYPE_OF_BUSINESS, COMPANY_REGISTRATION_NUMBER, CUSTOMER_TYPE, FAX_NUMBER, ID_EXPIRY_DATE, ID_ISSUE_DATE, ID_ISSUE_PLACE, ID_NUMBER, ID_TYPE, TELEPHONE_NO, ENGLISH_NAME, RACE, NATIONALITY, MALAY_NAME) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
DEBUG - Natively generated identity: 6
DEBUG - Executing identity-insert immediately
DEBUG - insert into CUSTOMER_ADDRESS (COUNTRY, ADDRESS_LINE1, ADDRESS_LINE2, ADDRESS_LINE3, ADDRESS_LINE4, PINCODE, STATE, ADDRESS_TYPE) values (?, ?, ?, ?, ?, ?, ?, ?)
DEBUG - could not execute statement [n/a]
com.microsoft.sqlserver.jdbc.SQLServerException: Cannot insert the value NULL into column 'CUSTOMER_ID', table 'xxxxxxx.xxx.CUSTOMER_ADDRESS'; column does not allow nulls. INSERT fails.
What is the reason for failure in the first case, and how to get it to work either way, any help is much appreciated.
Can you confirm that your annotation @JoinColumn with "name" and "referencedColumnName" is fine? Example:
name: If the join is for a unidirectional OneToMany mapping using a foreign key mapping strategy, the foreign key is in the table of the target entity.
referencedColumnName: When used with a unidirectional OneToMany foreign key mapping, the referenced column is in the table of the source entity.
If you really want to have a unidirectional OneToMany mapping, you shoud check One-To-Many Relationship with Join Table.
@Mário Kapusta: The foreignkey is in the target entity while I placed the Joincolumn in the source entity here. Since I want to retreive address only from Customer entity not and as a stand alone data, in which case it may not have any value as a data. So as per your comment JoinColumn(name="CUSTOMER_ID", referencedColumnName="CUSTOMER_ID")
private List customerAddresses; is supposed to cause an error in this case?
hello(sorry that i am so late)...answer: yes...you should have "referencedColumnName" - column of source entity ,,,,, "name" - fk in target entity. In your case it seems like bug is here.
I had the same issue. Adding @JoinColumn(nullable = false, ...) fixed it.
Even this fixed for me, but what did it do to fix it? What is the meaning of this configuration.
@LokeshAgrawal - (optional) Whether the foreign key column is nullable - is sated in the documentation for the attribute nullable. if you constrain the foreign key to not null, you must specify @JoinColumn(nullable = false). Otherwise it is not needed.
Probably the links below could give you more information on oneToMany relationship.
It indicates to use mappedBy at parent side and use JoinColumn at childs.
JPA JoinColumn vs mappedBy
He is talking about an unidirectional link. In that case it makes no sense to use a mappedBy - because that one is used in bidirectional links.
My apologies; I just missed Unidirectional part. Thanks for pointing that out.
| common-pile/stackexchange_filtered |
Structure parting a variable
I am trying to part a int16_t variable inside a structure. This structure is persisted in disk and loaded back across reboot.
the old structure is
struct details
{
int a;
int16_t var1;
int16_t b;
} details_t
The new one i changed is
struct details
{
int a;
int16_t var1:15;
unit16_t var2:1;
int16_t b;
}details_t;
The new changes are working fine across reboot.But is this correct way of doing?.
what i want to achieve is to have a dual meaning of variable var1 based on var2 is set or cleared. since var2 stores binary values, I declared it as uint16_t. Is it legal to separate a variable and declare it as two different datatype (int16_t and uint16_t ). This is going to be the update in existing stack, which should work seamlessly after update.
Also i couldn't use kernel functions like set_bit and clear_bit on these parted variables var1 and var2. My machine is little endian
You want to keep the backwards compatibility. But unfortunately C standard gives implementations a lot of room on how they should handle the bit fields. var1 and var2 could end up as 2 16-bit variables, which you likely what you don't want.
I recommend using manual bit masking and shifting instead. Just be careful about the signed variable when using bit shifting. Use unsigned temporary variable if necessary.
But is this correct way of doing?
Bit-fields is almost certainly the incorrect way of doing anything, particularly if portability is desired. Please read this.
What happens if you declare int16_t var1:15; is not specified by the standard, there is no telling where the sign bit will end up, where the msb will go, or anything else. It is not even specified whether this bit field will be treated as signed or unsigned.
Is it legal to separate a variable and declare it as two different datatype
It will compile but the results will depend on system and compiler. Basically you just created a random goo of 16 bits, of which you cannot predict any given behavior, unless one specific compiler document says otherwise.
This is going to be the update in existing stack, which should work seamlessly after update.
Then don't do this. Chances are you'll break the program or at least introduce vulnerablities for future maintenance. Instead, forget you ever saw something called bit-fields and use bit-wise operators to manipulate the original int16_t.
How it makes sense to smuggle in a boolean flag in the middle of this data type, I have no idea, but that's up to your program to handle.
I can handle it with using bit wise operators on var1 , since var1 would need a maximum of 10 bits, the remaining bits I can use it to handle things. Thanks for the details. it helps me a lot to avoid screwing up later.
@VigneshKViki The strange thing here is that you have declared this variable as signed. If it is indeed a signed variable in two's complement, then you are using all 16 bits. If it is not a signed variable, then why are you used a signed type? Picking the right type for the task is very important in C.
yes . i will set var1 into -1 to denote it as invalid.So i need it to be signed type.
@VigneshKViki So... then you are using 16 bits and nothing of what you are trying to do here makes any sense. http://en.wikipedia.org/wiki/Two%27s_complement
I don't understand what you are coming to say @Lundin. if var1 is +ve then i will check for 15th bit of var1 , depending on that bit is set or not i can mask the last 10 bits of var1 and use in different context.if the signed bit is set, i am not going to proceed at all. kindly explain what is wrong in this?. any example case would be appreciated.
@VigneshKViki I'm not following... what seems to be the problem then? Why can't you simply do if(val < 0) { do_this(); } else { do_that(); }. Why would you need to change the data structure?
| common-pile/stackexchange_filtered |
One large machine or cluster of small machines for Jmeter load generator in load testing?
I want to simulate up to 100,000 requests per second and I know that tools like Jmeter and Locust can run in distributed mode to generate load.
But since there are cloud VMs with up to 64 vCPUs and 240GB of RAM on a single VM, is it necessary to run in a cluster of smaller machines, or can I just use 1 large VM?
Will I be able to achieve more "concurrency" with more machines due to a network bottleneck coming from the 1 large machine?
If I just use one big machine, would I be limited by the number of ports there are?
In the load generator, does every simulated "user" that sends a request also require a port on the machine to receive a 200 response? (Sorry, my understanding of how TCP ports work is a bit weak.)
Also, we use Kubernetes pretty heavily, but with Jmeter or Locust, I feel like it'd be easier to run it on bare VM, without containerizing (even in distributed mode) while still maintaining reproducibility. Should I be trying to containerize Jmeter or Locust and running in Kubernetes instead?
Do you want to test it from inside or outside of the cluster?
The test load will come from outside of our dev cluster. Testing from within the cluster seems unrealistic
According to KISS principle it is better to go for a single machine assuming it is capable of conducting the required load.
Make sure you're following JMeter Best Practices
Make sure you have monitoring of baseline OS health metrics (CPU, RAM, swap, network and disk IO, JVM statistics, etc.)
Start with low number of users and gradually increase the load until you reach the desired throughput or limit of any of the monitored metrics, whatever comes the first. If there will be a lack of CPU or RAM or something - see what could be done to overcome the limitation.
More information: What’s the Max Number of Users You Can Test on JMeter?
| common-pile/stackexchange_filtered |
How to style mentions tag in react using rc-mentions
Example Text:- HI This is @Shubham
In above sentence i want to color @Shubham green and other text black only. can anyone help me with that?
Please provide enough code so others can better understand or reproduce the problem.
This is rc-mentions not react-mentions
| common-pile/stackexchange_filtered |
Moon's Proof of Matrix-Tree Theorem
I'm reading the following proof of the matrix-tree theorem:
https://www.sciencedirect.com/science/article/pii/0012365X9200059Z
in particular, his Theorem 3.1.
I was not able to validate the last part:
The last lines about equation (3.5)
How do I show the identity $(-1)^{\nu(D)-|W|}=\epsilon(gf)$?
Here $\nu(D)$ stands for the number of connected components of a functional digraph $D$ with $n$ nodes.
(A functional digraph is a directed graph whose nodes are all out-degree one.)
$|W|$ is, I believe, $t$ of the number of sub-nodes $W=\left\{i_1,\cdots, i_t\right\} \subset \{1,\cdots, n\}$, $L=\left\{j_1,\cdots, j_t\right\} \subset \{1,\cdots, n\}$, and $f\colon W\to L;i_k \mapsto j_k$.
The definition of $g$ is slightly involved:
Definitions of $W,L,f,g$, and the like
In general, the sign of a permutation of size $n$ is the same as the $(-1)^{n-\text{#cycles}}$ where $\text{#cycles}$ is the number of cycles in the permutation. This can be seen by observing that even-length cycles change the sign while odd-length cycles do not, and that the sum of lengths of cycles is $n$, so the sign of a permutation is determined by the parity of $\sum_C \text{length}(C) - 1 = (n-\text{#cycles})$.
Here $n=|W|$ (by definition) and $\nu(D)=\text{#cycles}(fg)$ (because cycles of the permutation correspond exactly to cycles in the functional graph).
Thank you so much, Marcin. It becomes now crystal clear.
| common-pile/stackexchange_filtered |
Namespace vanilla JavaScript events like in jQuery
In jQuery, when you set an event, you are able to namespace it. This means (if you want) you can have multiple resize window events, for example, and be able to unbind them individually without unbinding all events on that selector.
Example of jQuery namespacing:
$(window).on('scroll.myScrollNamespace, function() ...
I'm wondering how I can create a namespace in plain JavaScript. This obviously would not work:
window.addEventListener('resize.myScrollNamespace', function() ...
If instead of an anonymous function:
window.addEventListener('resize', function () {...});
you use a named function:
window.addEventListener('resize', function myScroll() {...});
then you may be able to use:
window.removeEventListener('resize', myScroll);
Make sure that you have myScroll in scope. When you remove the listeners in a different place than you add them, maybe you should define your functions in some outer scope and use their names in addEventListener in the same way as in the removeEventListener:
function myScroll() {
// ...
}
window.addEventListener('resize', myScroll);
window.removeEventListener('resize', myScroll);
If you want to be able to remove many listeners at once, then you will have to store them in some array and call removeEventListener for each of its elements.
See the EventTarget.removeEventListener() documentation.
This doesn't really answer the OP's question with event namespacing.
As @rsp answer correctly solves the problem of unbinding the correct handler, it doesn't really answer the problem of namespacing.
To handle this you would need to do a bit more coding like this:
function on(elm, evtName, handler) {
evtName.split('.').reduce(function(evtPart, evt) {
evt = evt ? evt +'.'+ evtPart : evtPart;
elm.addEventListener(evt, handler, true);
return evt;
}, '');
}
function off(elm, evtName, handler) {
evtName.split('.').reduce(function(evtPart, evt) {
evt = evt ? evt +'.'+ evtPart : evtPart;
elm.removeEventListener(evt, handler, true);
return evt;
}, '');
}
// Your handler
function onScroll(e) { ... }
// To bind it
on(window, 'scroll.myScrollNamespace', onScroll);
// To unbind it
off(window, 'scroll.myScrollNamespace', onScroll);
So to sum up: this actually sets several event listeners - one for each part of your namespacing. This functionality is unfortunately not natively supported, but as you can see it can be achieved relatively simple. Just be wary that even though this script support deep namespacing (eg. scroll.parent.child) it would bind a lot of event listeners (3 in this case), and thus is inadvisable.
You could possibly do this more performant, but this gets it done.
| common-pile/stackexchange_filtered |
Injective Functions into Free Modules
As a follow-up to this question, I am trying to prove the following:
If $F$ be a free $R$-module on a set $S$ via the function $i:S \longrightarrow F$ then $i$ is necessarily injective.
Attempted Proof:
This means that for every $R$-module $X$ and every function $f:S \longrightarrow X$ there exists a unique $R$-linear function $\tilde{f}:F \longrightarrow X$ such that $\tilde{f} \circ i = f$. So, consider the function $f:S \longrightarrow X$ defined by $f(x) := 0_X \;\forall\; x \in S$ where $0_X$ denotes the additive identity in $X$. Then, by definition of a free module,
$$
\tilde{f} \circ i = f \implies \tilde{f} \circ i = 0_X
$$
But, this means that $\tilde{f}$ is a left-inverse for $i$ and $i$ has a left-inverse if and only if it is injective. Therefore, $i$ must be injective.
So, my question is, does this proof work?
No, if the composition is the zero function, then this does not mean that $\tilde{f}$ is a left inverse of anything; you would need the composition to be the identity function to get that conclusion.
Note that if you have a composition $\overline{f}\circ i$, you want to show that the composition is one-to-one in order to conclude that $i$ is one-to-one. But if the composition is the zero function, then the composition is certainly not one-to-one, you cannot conclude anything about the first function being applied.
To show that $i$ is injective, consider $R$ as a module over itself. Then $R$ is cyclic, generated by $1_R$.
Now, let $s,t\in S$ such that $i(s)=i(t)$. Define $f\colon S\to R$ by
$$f(u) = \left\{\begin{array}{ll}
1_R &\text{if }u=s,\\
0 &\text{if }u\neq s.
\end{array}\right.$$
Then $f$ extends to a module homomorphism $\overline{f}\colon F\to M$. Then
$$1_R = f(s) = \overline{f}(i(s)) = \overline{f}(i(t)) = f(t).$$
(If your rings don't have identity, then pick any $x\in R$, $x\neq 0$, and consider ideal generated by $x$, $\{nx + rx\mid n\in\mathbb{Z}, r\in R\}$; then map $s$ to $x$ and everything else to $0$).
| common-pile/stackexchange_filtered |
Angular Universal (SSR) cache don't update
Good,
I have a web with Angular Universal on an Apache server executed through PM2.
When making changes, I generate the new version of the web, upload the files to the hosting and restart the pm2 task
But when accessing the web the changes are not shown. For them to be displayed I have to clear data from the site or force the cache to be cleared.
For example, in a browser that I haven't used for 2 months, I still get the look it had then, even if I refresh the page.
How can I solve that?
Please provide enough code so others can better understand or reproduce the problem.
| common-pile/stackexchange_filtered |
What is Ubuntu's equivalent of an exe file?
Sometimes I want to install a program when offline. But apt-get downloads as you install.
Is there a way to install a program, like you would install a .exe, on Ubuntu?
Yes you can. Instead of a .exe file it is a .deb file.
@Tim please explain how to do? I am a newbie as mentioned in the original question...
@karel http://askubuntu.com/questions/40779/how-do-i-install-a-deb-file-via-the-command-line may be better
@Tim I think you missed the target.
@karel he wants ubuntu's exe equivalent?
You can use:
apt-get install -d
To download software and dependencies without installing them. The .deb files (pretty much equivalent to Windows .exe installers), are then downloaded to /var/cache/apt/archives/
Unless you've issued apt-get clean pretty much anything you've ever installed via apt-get should have the .deb files stored there.
Also you can install the .deb files via dpgk -i but you have to remember to install the dependencies (and their dependencies and so on), first. Or you should also just be able to double click a .deb file in your file browser and Software Center should take care of it for you.
For example: I want to install gedit (which is included with Ubuntu normally so it won't download tons of dependency .deb files). But I have a system that, for whatever reason, doesn't have gedit and has no internet connect.
So first, on a computer connected to the internet, I run apt-get install --reinstall -d gedit (because if you try running apt-get install -d gedit on a system with gedit already installed to the latest version it just tells you it is already installed), which then goes through the normal process of downloading the package (in this case there are no dependencies), and then stops.
Then I locate the file under /var/cache/apt/archives/ ...
... and move it to the computer which needs gedit installed and install it, in this case using the Software Center.
Or I could install it using cd /var/cache/apt/archives and dpkg -i gedit_3.10.4-0ubuntu4_amd64.deb
Good answer :) Explaining how to then install these .deb file from command line or GUI would make it even better!
@Ian Lantzy please give me an example.. :)
Alright give me a minute let me take some screenshots...
@IanLantzy Lovely to see a new user with a good answer! +1, and more if I could!
@MikeFriedman there are an infinite number of potential examples that could be used. For instance, I could use nginx and nginx-common and nginx-core or similar as examples if my system needed an offline method to install the NGINX web server. Essentially, it's impossible to create 'one example' that would work everywhere. The tricky part is because of dependencies - a lot of 'regularly used' Desktop programs have a lot of dependencies that you would also have to download.
@IanLantzy Thanks for helping me out. I really appreciate it. I just can't upvote you as my reputation is not high. I would request you to upvote my question so that in future I can appreciate anyone for helping me or for making an useful question/answer to anyone.
| common-pile/stackexchange_filtered |
Recursion and return statements
I'm fairly new to Python and recursive functions as a whole, so pardon my ignorance.
I am trying to implement a binary search tree in Python and have the following insert method (taken out of a class):
def insert(self, key, root=None):
'''Inserts a node in the tree'''
if root == None:
root = self.root
if root.key == None:
self._update(root, key)
return 0
else:
tmp = root
if key > tmp.key: # we work with the right subtree
self.insert(key, root=tmp.right)
elif key < tmp.key: # we work with the left subtree
self.insert(key, root=tmp.left)
else: # key already exists
return 0
I'm not sure if this is legible, but it traverses the tree until it gets to a None value and updates the node with the key to insert.
Now, the method works nicely and correctly creates a BST from scratch. But there's a problem with the return statements, as it only returns 0 if there is no recursion performed.
>>> bst.insert(10)
0
>>> bst.insert(15)
>>> bst.root.right.key
15
>>>
"Inserting" the root key again returns 0 (from line 15) the way it should.
>>> bst.insert(10)
0
I can't figure out why this happens. If I put a print statement in line 6, it executes correctly, yet it just won't return anything past the first insertion. Why is this? (I'm pretty sure I'm missing some basic information regarding Python and recursion)
Thanks for your help,
Ivan
P.S.: I've read that recursion is not the best way to implement a BST, so I'll look into other solutions, but I'd like to know the answer to this before moving on.
I'm not sure what you think it should return, other than 0. Can you show what you're expecting?
@imiric: I think you have gotten some helpful pointers from others, but I would also like to point out that your instinct to leave out the return statement might suggest you think in expressions rather than statements. If so, perhaps a language like Scheme would suit you. You certainly don't have to give up on Python, but keep your mind open to functional programming languages.
On your recursive lines, you do not return anything. If you want it to return 0, you should replace them with lines like:
return self.insert(key, root=tmp.left)
instead of just
self.insert(key, root=tmp.left)
You are inside a function and want to return a value, what do you do? You write
def function():
return value
In your case you want to return the value returned by a function call, so you have to do.
def function():
return another_function()
However you do
def function():
another_function()
Why do you think that should work? Of course you use recursion but in such a case you should remember the Zen of Python which simply says:
Special cases aren't special enough to break the rules.
You need a return statement in your recursive case. Try this adjustment.
def insert(self, key, root=None):
'''Inserts a node in the tree'''
if root == None:
root = self.root
if root.key == None:
self._update(root, key)
return 0
else:
tmp = root
if key > tmp.key: # we work with the right subtree
return self.insert(key, root=tmp.right)
elif key < tmp.key: # we work with the left subtree
return self.insert(key, root=tmp.left)
else: # key already exists
return 0
| common-pile/stackexchange_filtered |
How can I get all files in directory and then display them in an image gallery?
I have the code bellow...in short it is mean't to generate a list of all files in a directory and then for every file in the list it would add a new gallery element to the page.
<!DOCTYPE html>
<html>
<head>
<title></title>
<style media="screen">
div.gallery {
margin: 5px;
border: 1px solid #ccc;
float: left;
width: 180px;
}
div.gallery:hover {
border: 1px solid #777;
}
div.gallery img {
width: 100%;
height: auto;
}
div.desc {
padding: 15px;
text-align: center;
}
</style>
</head>
<body>
<h1>Test</h1>
<script type="text/javascript">
var fs = require('fs');
var files = fs.readdirSync('uploads/');
for (item in files) {
document.write('<div class="gallery">');
document.write('<a target="_blank" href="uploads/'+item+'">');
document.write('<img src="uploads/'+item+'" width="600" height="400">');
document.write('</a>');
document.write('<div class="desc">'+item+'</div>');
document.write('</div>');
}
</script>
</body>
</html>
From some quick research var fs = require('fs'); and var files = fs.readdirSync('uploads/'); are supposed to get the files in the directory into the list and then the for statement is mean't to add them to the page. However when I reload the page it remains blank. Does anyone have any ideas?
var fs = require('fs'); that's nodejs - you can't do that in a browser - are you trying to access files on the client or on the server?
You can't use require and FileSystem on Client Side
https://stackoverflow.com/questions/19059580/client-on-node-uncaught-referenceerror-require-is-not-defined/19059825
The uploads/ folder in on the web server same as the js file. I'm trying to get a list of all the files in a directory on the server.
| common-pile/stackexchange_filtered |
Traefik in microk8s allways 404 trought HTTPS
I deployed a microk8s single node cluster on a simple & small VPS.
At the moment I running without cert SSL (Traefik cert by default).
The http:80 version of ingress is working correctly, I can browse the webpages at the correct ingress from HTTP, but when I try to run in https, Traefik is showing a 404.
I appreciate it if anyone can help me.
Many thanks
This is my Traefik config & my ingress config.
Traefik:
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: ingressroutes.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: IngressRoute
plural: ingressroutes
singular: ingressroute
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: middlewares.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: Middleware
plural: middlewares
singular: middleware
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: ingressroutetcps.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: IngressRouteTCP
plural: ingressroutetcps
singular: ingressroutetcp
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: ingressrouteudps.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: IngressRouteUDP
plural: ingressrouteudps
singular: ingressrouteudp
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: tlsoptions.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: TLSOption
plural: tlsoptions
singular: tlsoption
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: tlsstores.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: TLSStore
plural: tlsstores
singular: tlsstore
scope: Namespaced
---
apiVersion: apiextensions.k8s.io/v1beta1
kind: CustomResourceDefinition
metadata:
name: traefikservices.traefik.containo.us
spec:
group: traefik.containo.us
version: v1alpha1
names:
kind: TraefikService
plural: traefikservices
singular: traefikservice
scope: Namespaced
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: traefik-ingress-controller
rules:
- apiGroups:
- ""
resources:
- services
- endpoints
- secrets
verbs:
- get
- list
- watch
- apiGroups:
- extensions
resources:
- ingresses
verbs:
- get
- list
- watch
- apiGroups:
- extensions
resources:
- ingresses/status
verbs:
- update
- apiGroups:
- traefik.containo.us
resources:
- middlewares
- ingressroutes
- traefikservices
- ingressroutetcps
- ingressrouteudps
- tlsoptions
- tlsstores
verbs:
- get
- list
- watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1beta1
metadata:
name: traefik-ingress-controller
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: traefik-ingress-controller
subjects:
- kind: ServiceAccount
name: traefik-ingress-controller
namespace: default
---
apiVersion: v1
kind: ServiceAccount
metadata:
namespace: default
name: traefik-ingress-controller
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
namespace: default
name: traefik
labels:
app: traefik
spec:
selector:
matchLabels:
name: traefik
template:
metadata:
labels:
name: traefik
spec:
terminationGracePeriodSeconds: 60
# hostPort doesn't work with CNI, so we have to use hostNetwork instead
# see https://github.com/kubernetes/kubernetes/issues/23920
dnsPolicy: ClusterFirstWithHostNet
hostNetwork: true
serviceAccountName: traefik-ingress-controller
containers:
- name: traefik
image: traefik:v2.2
args:
- --ping
- --ping.entrypoint=http
- --api.insecure
- --accesslog
- --entrypoints.web.Address=:80
- --entrypoints.websecure.Address=:443
#- --providers.kubernetescrd
- --providers.kubernetesingress
- forwardedHeaders.trustedIPs:["Public IP VPS running microk8s"]
#- --certificatesresolvers.default.acme.tlschallenge
#-<EMAIL_ADDRESS> #- --certificatesresolvers.default.acme.storage=acme.json
# Please note that this is the staging Let's Encrypt server.
# Once you get things working, you should remove that whole line altogether.
#- --certificatesresolvers.default.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory
ports:
- name: web
containerPort: 80
- name: websecure
containerPort: 443
- name: admin
containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: traefik
spec:
ports:
- protocol: TCP
name: web
port: 80
- protocol: TCP
name: admin
port: 8080
- protocol: TCP
name: websecure
port: 443
selector:
app: traefik
Ingress:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: front
annotations:
kubernetes.io/ingress.class: traefik
traefik.ingress.kubernetes.io/redirect-permanent: "true"
ingress.kubernetes.io/ssl-redirect: "true"
ingress.kubernetes.io/ssl-temporary-redirect: "false"
ingress.kubernetes.io/ssl-proxy-headers: "X-Forwarded-Proto: https"
spec:
rules:
- host: front-dev.mgucommunity.com
http:
paths:
- path: /
backend:
serviceName: front
servicePort: 80
Looks like you are missing the entrypoint websecure annotation so that Traefik also works on port 443
traefik.ingress.kubernetes.io/router.entrypoints: web, websecure
Note that if you want to redirect all your traffic to HTTPS you would have to have this in your DaemonSet config:
...
- --entrypoints.web.http.redirections.entryPoint.to=websecure
- --entrypoints.websecure.http.tls.certResolver=default
....
This might help a write up on how to use a K8s ingress with Traefik v2.
✌️
Thank you for your response. The annotation to add the websecure entrypoint is not working. By default, as I can see in the dashboard, the ingress has the two values. I tried to put but I has the same result. I worked the https with the annotation of Tls true, but in that case, the http entrypoint is stoping working. Finally, the best solution is your second part of the response: force redirection to https
| common-pile/stackexchange_filtered |
How best to show message that browser does not support HTML5 <range> element?
The element, which is not supported in IE below 9, is displayed as a default text-field in IE8. For my application, which also has intended text fields as well as other user controls, this is worse than displaying nothing or showing a “little red X icon”, as the user would be confused, at best!
Some ‘non-text’ HTML5 elements, such as and , pair with a closing tag that allows text between the tags to display a message to users whose browsers do not support these elements. (I wonder why doesn’t have this feature/form.)
Is there a simple way to get around this? (I’ve used conditionals of the form “if (navigator.userAgent.indexOf("MSIE")!=-1) …” previously to get around a different inter-browser issue, but that doesn’t specify the IE version, and I’m pretty hazy about that sort of detection method.)
(Greetings StackOverflowers – first-time poster here. Background: been self-teaching JavaScript magpie-like for a short time, after learning a little HTML/CSS, and have only a tiny amount of experience with other languages over the years.)
Don't browser detect - feature detect, browser detection is usually bad. Also note that you can shim HTML5 elements like range with a polyfill and get them to work just fine in IE9.
Check the type of the element, if it says range it is supported. http://modernizr.com/
Thanks Benjamin. (My previous use of browser detection was to deal with the fact that browsers other than IE made text fields wider than I specified, to allow for a scroll bar they added on overflow, so I don’t know if this behaviour could have been detected as a feature.)
The problem you have here has been solved in a more general way:
There are libraries that help you with feature detection and with replacing elements with more modern versions on browsers that support them.
Have a look at http://modernizr.com/
Javascript-Snippets that can be used as drop-in replacements for new features in old browsers are called poly-fills. What you are looking for is a poly-fill for the range element, e.g. this:
https://github.com/freqdec/fd-slider
Thanks, bjelli - I was just becoming aware of modernizr, and may learn to use it if I can't find a simpler solution
| common-pile/stackexchange_filtered |
Aggregate, Collate and Transpose rows into columns
I have the following table
Id Letter
1001 A
1001 H
1001 H
1001 H
1001 B
1001 H
1001 H
1001 H
1001 H
1001 H
1001 H
1001 A
1001 H
1001 H
1001 H
1001 B
1001 A
1001 H
1001 H
1001 H
1001 B
1001 B
1001 H
1001 H
1001 H
1001 B
1001 H
1001 A
1001 G
1001 H
1001 H
1001 A
1001 B
1002 B
1002 H
1002 H
1002 B
1002 G
1002 H
1002 B
1002 G
1002 G
1002 H
1002 B
1002 G
1002 H
1002 H
1002 G
1002 H
1002 H
1002 H
1002 H
1002 H
1002 M
1002 N
1002 G
1002 H
1002 H
1002 M
1002 M
1002 A
1002 H
1002 H
1002 H
1002 A
1002 B
1002 B
1002 H
1002 H
1002 H
1002 B
1002 H
1002 H
1002 H
1002 A
1002 A
1002 A
1002 H
1002 H
1002 H
1002 H
1002 B
1002 H
1003 G
1003 H
1003 H
1003 N
1003 M
And I'm trying to transpose it to make each different id in the first column and all the letters in the second column with one blank space for each blank row in the original table:
1001 AHHH BHHH HHH AHHHB AHHHB BHHHB H AGHHAB
1002 BHHB GH BGGH BGHH GHH HHHMN GHHMM AHHHAB BHHH BHHHAA AHHHHB H
1003 GHHNM
I have about 100 different id. I tried to do with a formula using TRANSPOSE and TRIM. I also tried with a macro and VLOOKUP seems to be the easiest way but can't find out how.
The concatenation of random length groups of values is virtually impossible and certainly impractical. I see VBA as the only realistic avenue to pursue a solution through.
Performance in mind. This option incorporates arrays. From performance point of view, it is much faster to once read data in the worksheet to an array, do your procedures directly in VBE and write the results back to the worksheets as compared to doing procedures in the worksheet cell by cell.
Sub transposing()
Const sDestination As String = "D2"
Dim ar1() As Variant
Dim ar2() As Variant
Dim i As Long 'counter
ar1 = ActiveSheet.Range("A2:B" & ActiveSheet.UsedRange.Rows.Count).Value
ReDim ar2(1 To 1, 1 To 2)
ar2(1, 1) = ar1(1, 1): ar2(1, 2) = ar1(1, 2)
For i = 2 To UBound(ar1, 1)
If ar1(i, 1) = ar2(UBound(ar2, 1), 1) Then
ar2(UBound(ar2, 1), 2) = ar2(UBound(ar2, 1), 2) & ar1(i, 2)
ElseIf ar1(i, 1) = vbNullString Then
ar2(UBound(ar2, 1), 2) = ar2(UBound(ar2, 1), 2) & " "
Else
ar2 = Application.Transpose(ar2)
ReDim Preserve ar2(1 To 2, 1 To UBound(ar2, 2) + 1)
ar2 = Application.Transpose(ar2)
ar2(UBound(ar2, 1), 1) = ar1(i, 1)
ar2(UBound(ar2, 1), 2) = ar2(UBound(ar2, 1), 2) & ar1(i, 2)
End If
Next
ActiveSheet.Range(sDestination).Resize(UBound(ar2, 1), UBound(ar2, 2)).Value = ar2
End Sub
The result will look like this:
The line Const sDestination As String = "D2" states the beginning of the output. Change it to whichever cell you want.
THANKS A LOT!! Both answers were really perfect I should tick both as useful and give more points to both but don't know how
Thanks :) Just to inform you for future - doing procedures directly in VBE is a lot faster than looping through cells in the worksheet.
The user has posted a new question asking why your macro gives Error 13. It fails when the concatenated cell has a length of 733 characters. My understanding is that WorksheetFunction.Transpose does not work if a element has a length of 255 characters. Certainly, I can clear the error by reducing the length to 255. Note that WorksheetFunction.Transpose is a slow function and ReDim Preserve gets steadily slower so I think you will get a faster routine that does not fail if you output directly to the worksheet.
@ZygD - I took a stab at overcoming the error reported but wanted to check to see how you would feel about me posting a modification of your sub. Unfortunately, cannot really show you my effort short of posting it as there is no 'sandbox' that I am aware of.
@Jeeped you can post a modification. I'd be really thankful for that.
@TonyDallimore in my sub I use Application.Transpose instead of WorksheetFunction.Transpose. I don't know the actual difference between them (I think that the one coming from Application should be faster), but, well, they both cause the error 13 as I see.
@ZygD - I've put it in the new thread here.
@ZygD. I cannot find anything that states that [Application.]WorksheetFunction.Transpose is different from Application.Transpose although I can find something that implies they are the same.
@ZygD The experts have always said that Worksheet.Functions are faster than the same functionality coded with VBA. I have recently discovered that this is not true for any of the functions I have timed. For example, two nested for-loops will create a new transposed array over 3 times faster than Transpose. I find it difficult to believe the Excel functions are slow so assume the interface from VBA to an Excel function has a heavy overhead like the interface from VB.Net is Excel.
@ZygD See Convert 2 dimensional array to one dimensional (without Looping) for more info and a VBA equivalent to Transpose that I assume will not hit the Error 13 limitation..
@TonyDallimore I would agree that the interface adds the significant overhead. I've read that it's recommended (in relation to performance) to create VBA-created equivalents at least over these worksheet functions: Min(), Max(), Average(), Match(), NormSInv() and StDev(). Thanks for the input!
For tasks like this Microsoft added "Get&Transform" to Excel 2016. In order to use this functionality in earlier versions, you have to use the Power Query Add-In.
The M-code is very short:
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
FillIdDown = Table.FillDown(Source,{"Id"}),
ReplaceNull = Table.ReplaceValue(FillIdDown,null," ",Replacer.ReplaceValue,{"Letter"}),
Transform = Table.Group(ReplaceNull, {"Id"}, {{"Count", each Text.Combine(_[Letter])}})
in
Transform
Your data should sit in "Table1".
https://www.dropbox.com/s/bnvchofmpvd048v/SO_AggregateCollateAndTransposeColsIntoRows.xlsx?dl=0
| common-pile/stackexchange_filtered |
iOS segue twice screen
I have simple app. My tableViews contains some words; I post data in post screen and I want to get back to the first tableView screen. I have use a segue for this. The problem is that each time after posting, clicking the post button opens a new tableView over the post screen. I want to return to the original.
Table View Screen -> Post Screen -> New Table View Screen
But I want
Table Vievscreen <-> Post Screen
Are you looking for self.navigationController.popViewControllerAnimated(true)?
I think my problem is similar to that one: http://stackoverflow.com/questions/26337304/view-appearing-twice-when-performing-segue
Use an unwind segue - http://stackoverflow.com/questions/36824524/programmatically-defining-a-new-navigation-controller-order-stack/36829034#36829034
Fixed grammar; cleaned up word flow a little.
I had the same issue.It is resolved now. Please let me know if this helps.
I already have a segue linked from table view cell to another view with name DynamicSuperView
func tableView(_tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
//Remove the below line from this function as it will perform segue.
//performSegue(withIdentifier: "DynamicSegue", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
// This will actually perform your segue
var DestViewController = segue.destination as! DynamicSuperView
let selectedRow = tableView.indexPathForSelectedRow?.row
DestViewController.labelText = names[selectedRow!]
}
Hope this helps to somebody.
We need a LOT more information to what is provided. However this may get you started in the right way.
If you are using a navigation controller, put this in your posting view code:
navigationController!.popViewControllerAnimated(true)
If you are NOT using navigationController but instead showing the view modally, then use the following in your posting view code:
dismissViewControllerAnimated(true, completion: nil)
I am using navigation controller, I tried it now it is like Table View -> Table View after posting the data. If I delete popViewController it is like, Table View Screen -> Post Screen -> New Table View Screen
You have 2 view controllers, one with the tableView the other with some post data. In your view controller where the post data is. Please copy / paste your code to where you are dismissing the view controller.
sure but I create segue by right clicking the button and creating action segue "show", therefore there is nothing in the code related with the segue.
I am interested in the other view controller code. What do you code to get back to the main window? What code does the "Post Screen" have to get back to the "Table View Screen"? You need to have a code like this: navigationController!.popViewControllerAnimated(true)
Most segues create a new instance of a view controller and display it on top of existing view controllers.
If you are adding a view controller to a navigation stack with a push, you want to do a pop as described in JAL's comment.
If your segue is modal, you want to do a dismissViewController:animated:
You could also set up an unwind segue, although that might be overkill for this simple case.
I'm getting the same issue here, but I realize that I just did wrong on control+click, I dragged from cell, the correct must be from tableview
I hope this help some one
| common-pile/stackexchange_filtered |
How to see if a result from the database matches my values in the array
Hi guys i have been trying to rap my head around this for some time now. What I'm trying to achieve is get some data from my database, store it in a variable and compare it to a value that is stored in my array.
Problem is it keeps returning the wrong output. From the SQL query below, the mysql_result $total_cat returns a value of 16. Once this value is stored, the code is meant to output echo "this value is in the array"; but its not working.
Where am i going wrong?
This is my Code
Create an array to store my values in
$lunchbox = array(12,13,14,16,20,24,33,32);
Set up my SQL database query
$query = mysql_query("SELECT * FROM table WHERE id = '$the_persons_id'");
Catch my result and store it in a variable
$total_cat = mysql_result($query,0,"category_id");
Clean my result
$total_cat = str_replace("|", " ", $total_cat);
Check if my sql result matches my any of my results stored in my array
if (in_array($total_cat, $lunchbox)) {
echo "this value is in the array";
}else{
echo "this value is not in the array";
do you mean to say there is only one column in the table that has a value of 16 for your query parameters? curious since i see you are doing a select *
how does category_id looks like in the database? Your "cleaning" makes me assume, it might look like 1|2|16 ... So, you would actually generate "1 2 16" by "cleaning" it, which is not in the array...
Sidenote: $total_cat = str_replace("|", " ", $total_cat); you're replacing | with a space and your array doesn't contain any spaces. In doing so, you'd either need to do $total_cat = str_replace("|", "", $total_cat); or use trim().
There is more than one column in the table but I'm just testing the first value that i displayed on the screen
the value prints out like this 9|16. but im only worried about finding 16
@dognose yes that how the data gets displayed if i run echo "$total_cat";
This Q&A http://stackoverflow.com/q/23270686/ might be of help and http://stackoverflow.com/q/23260372/
However, you may have better luck using IN or FIND_IN_SET() directly from your query.
@Fred-ii- how would i write that query can you give me an example
For FIND_IN_SET() see http://stackoverflow.com/q/23504764/ and http://stackoverflow.com/q/22480418/ and http://stackoverflow.com/q/19602637/ and http://stackoverflow.com/q/19462626/ and for IN() see http://www.tutorialspoint.com/mysql/mysql-in-clause.htm I hope this helps.
found the answer guys thanks for the help. All i needed to do was use php function substr so it would look like this $total_cat = substr($total_cat, 1);
echo "$total_cat"; and the result will display as 16 making my end result evaluate to true causing my value to be found in my array. :)
Great, glad to hear it. You can post it as an answer yourself you know ;-)
I found the answer.
This is my code:
Create an array to store my values in
$lunchbox = array(12,13,14,16,20,24,33,32);
Set up my SQL database query
$query = mysql_query("SELECT * FROM table WHERE id = '$the_persons_id'");
Catch my result and store it in a variable
$total_cat = mysql_result($query,0,"category_id");
Clean my result
$total_cat = str_replace("|", " ", $total_cat);
This will output as 9 16
Now we run the php function substr to remove the first part of the string.
$total_cat = substr($total_cat, 1);
This will give us the output of 16
Now we check if my SQL result matches my any of my results stored in my array
if (in_array($total_cat, $lunchbox)) {
echo "this value is in the array";
}else{
echo "this value is not in the array";
Which it does and now my IF statement evaluates to TRUE and the code is complete.
Thanks for all the help team.
Happy Coding :)
Accept your answer if it's solution. :)
| common-pile/stackexchange_filtered |
Transformation from one basis to another
I have a 3D point $X_1$ in basis $1$. The origin of basis $1$, $O_1$, has a translation of 't' with respect the origin of basis $2$, $O_2$. Also basis $1$ has a relative rotation with basis $2$, given by the rotation matrix $R$.
How do I go about converting $X_1$ from basis $1$ to basis $2$ ?
Rotate, translate
Call the target vector $Q$. Rotate by the angle $\theta$ in the first coordinate system.
$$
R Q.
$$
Translate the rotated vector to the second reference frame:
$$
\tilde{Q} = RQ + P.
$$
A pictorial follows. The black vectors mark the first coordinate system. The blue vectors mark a coordinate system which has been rotated by $\theta$, and translated by a vector $P$.
The target vector $Q$ is located in the first coordinate system and the steps to transform to the second coordinate system follow.
First, rotate the vector by the angle $\theta$.
Translate the rotated vector by $P$.
| common-pile/stackexchange_filtered |
How to open specific activity via ID
I have a project with matches. In the project, I use the room database. I have three records in my database that have an ID and contain the fields imgTeamOne, imgTeamTwo, titleTeamOne, titleTeamTwo, itemDate. I have prepared a certain activity for each of the match (ActivityDetailOne, ActivityDetailTwo, ActivityDetailThree) and I want that when I clicked on the first card - ActivityDetailOne opened, when I clicked on the second card - ActivityDetailTwo opened, etc. How do I do this? How do I write a code so that a card with ID=0 opens ActivityDetailOne, please help. I'm a beginner and I don't understand
FragmentMatch.kt
class FragmentMatch : Fragment() {
private lateinit var _binding: FragmentMatchBinding
private val binding get() = _binding
private val matchViewModel: ViewModelMatch by activityViewModels()
private lateinit var recyclerView: RecyclerView
private var adapter: RecyclerAdapter? = RecyclerAdapter(emptyList())
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentMatchBinding.inflate(inflater, container, false)
recyclerView = binding.passRecyclerView
recyclerView.layoutManager =
LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
recyclerView.adapter = adapter
requireActivity().title = "Игры"
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
matchViewModel.matchListLiveData.observe(
viewLifecycleOwner,
Observer { receipts -> receipts?.let { updateUI(receipts) } }
)
}
private fun updateUI(matches: List<MatchModel>) {
if (matches.isEmpty()){
initialDb()
}
adapter = RecyclerAdapter(matches)
recyclerView.adapter = adapter
}
private fun initialDb(){
val match = MatchModel(UUID.randomUUID(), "25 сентября 2021", "Chelsea", "Manchester City")
val match2 = MatchModel(UUID.randomUUID(), "25 сентября 2021", "Everton", "Norvich City")
val match3 = MatchModel(UUID.randomUUID(), "25 сентября 2021", "Brentford", "Liverpool")
matchViewModel.addMatch(match)
matchViewModel.addMatch(match2)
matchViewModel.addMatch(match3)
}
private inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
private lateinit var match: MatchModel
private val titleTeamOne: TextView = itemView.findViewById(R.id.titleTeamOne)
private val imgTeamOne: ImageView = itemView.findViewById(R.id.imgTeamOne)
private val titleTeamTwo: TextView = itemView.findViewById(R.id.titleTeamTwo)
private val imgTeamTwo: ImageView = itemView.findViewById(R.id.imgTeamTwo)
private val dateGame: TextView = itemView.findViewById(R.id.dateGame)
private val favBtn: Button = itemView.findViewById(R.id.favBtn)
private val btnDetail: Button = itemView.findViewById(R.id.btnDetail)
init {
itemView.setOnClickListener(this)
}
fun bind(match: MatchModel) {
this.match = match
titleTeamOne.text = (match.firstCommand)
titleTeamTwo.text = (match.secondCommand)
dateGame.text = (match.date)
when (match.firstCommand) {
"Everton" -> {
imgTeamOne.setImageResource(R.drawable.image_3)
}
"Brentford" -> {
imgTeamOne.setImageResource(R.drawable.image_4)
}
"Norwich" -> {
imgTeamOne.setImageResource(R.drawable.image_5)
}
"Liverpool" -> {
imgTeamOne.setImageResource(R.drawable.image_6)
}
}
when (match.secondCommand) {
"Everton" -> {
imgTeamTwo.setImageResource(R.drawable.image_3)
}
"Brentford" -> {
imgTeamTwo.setImageResource(R.drawable.image_4)
}
"Norwich" -> {
imgTeamTwo.setImageResource(R.drawable.image_5)
}
"Liverpool" -> {
imgTeamTwo.setImageResource(R.drawable.image_6)
}
}
favBtn.setOnClickListener {
val match = MatchModel(match.id, match.date, match.firstCommand, match.secondCommand, true)
matchViewModel.saveMatch(match)
}
btnDetail.setOnClickListener {
val intent = Intent(context, DetailActivity::class.java)
startActivity(intent)
}
}
override fun onClick(v: View) {
}
}
private inner class RecyclerAdapter(private var matches: List<MatchModel>) :
RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): MyViewHolder {
val itemView =
LayoutInflater.from(parent.context)
.inflate(R.layout.item_match, parent, false)
return MyViewHolder(itemView)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val match = matches[position]
holder.bind(match)
}
override fun getItemCount() = matches.size
}
}
i would open a new field in the room db like "val type: Int" and check the type to open the new activity. But in my opinion you could create only one activity and make it generic for each match
After all, you can somehow make a check, if Id = 1 - open specific activity, or is it impossible? I need to do just that
you can do like if (id == 1){
startActivity(Intent(this, newActivity::class.java))
}
should I write this in my btnDetail.setOnClickListener ?
yep, when you click check the id and then call the activity you want
Since I initially did not want to create a separate field in the database, and I used UUID.randomUUID() in the ID field - this complicated my work, I wrote code that checked the name of the command and opened the activity with this command. This is not quite correct, but if you use an ID without randomness in your code, you can do a check by ID. Here is the solution I made:
btnDetail.setOnClickListener {
if (match.firstCommand == "Chelsea") {
val intent = Intent(context, DetailActivity::class.java)
startActivity(intent)
}else if (match.firstCommand == "Everton"){
val intent = Intent(context, SecondDetailActivity::class.java)
startActivity(intent)
}else if(match.firstCommand== "Brentford"){
val intent = Intent(context, ThirdDetailActivity::class.java)
startActivity(intent)
}
| common-pile/stackexchange_filtered |
How the terminal can run programs and show its output?
I'm slowly creating a mental model of how linux works, and I've tried to simplify the most, my model of how linux works. Let's assume that the kernel boots and inits the only software it's gonna run: the terminal. Let's assume that this terminal has the capabilities of appearing on the screen and rendering some text, and also, of course, getting input from the keyboard. Let's also assume that I type the name of an executable, and it knows where it's in memory. Now, how is the terminal able run this program? In my mental model, I thougth of the following:
The terminal is a program, which means it can do system calls. So it uses the fork() system call and creates a new process in the kernel. Then, it somehow makes this process run the code of my program. Now, how it printf() able to show text on my terminal live while the program runs?
See What is the exact difference between a 'terminal', a 'shell', a 'tty' and a 'console'?
Your understanding is fairly accurate. The shell uses the clone() system call to create a new process. The manpage describes it's difference from fork():
Unlike fork(2), clone() allows the child process to share parts of its
execution context with the calling process, such as the memory space,
the table of file descriptors, and the table of signal handlers.
(Note that on this manual page, "calling process" normally
corresponds to "parent process".
It then uses an execve() system call to replace the current child process image with a new process image. This system call is what makes the process run the code of your program.
When a process forks the file descriptors of the parent are copied. From the fork(2) manual page:
The child inherits copies of the parent's set of open file descriptors.
Each file descriptor in the child refers to the same open file
description (see open(2)) as the corresponding file descriptor in
the parent. This means that the two descriptors share open file
status flags, current file offset, and signal-driven I/O attributes
(see the description of F_SETOWN and F_SETSIG in fcntl(2)).
This is why text is displayed to your terminal when a program writes to stdout. You can see this process happen using the strace program in Linux. Here are the main excerpts from running strace on a bash process in Linux and executing /bin/echo foo within the shell.
21:32:20 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f3f419f19d0) = 32036
Process 32036 attached
[pid 32017] 21:32:20 wait4(-1, <unfinished ...>
[pid 32036] 21:32:20 execve("/bin/echo", ["/bin/echo", "foo"], ["XDG_VTNR=8", "KDE_MULTIHEAD=false", "XDG_SESSION_ID=5512", "SSH_AGENT_PID=30259", "DM_CONTROL=/var/run/xdmctl", "TERM=xterm", "SHELL=/bin/bash", "XDM_MANAGED=method=classic", "XDG_SESSION_COOKIE=5c78dafb330601d94d7556bb52a6a2a6-1450467466.154128-547622992", "HISTSIZE=50000", "KONSOLE_DBUS_SERVICE=:1.160", "GTK2_RC_FILES=/etc/gtk-2.0/gtkrc:/home/jordan/.gtkrc-2.0:/home/jordan/.kde/share/config/gtkrc-2.0", "KONSOLE_PROFILE_NAME=Shell", "GTK_RC_FILES=/etc/gtk/gtkrc:/home/jordan/.gtkrc:/home/jordan/.kde/share/config/gtkrc", "GS_LIB=/home/jordan/.fonts", "WINDOWID=92274714", "SHELL_SESSION_ID=5b72a0038b0c4000a9299cae82f340a2", "KDE_FULL_SESSION=true", "USER=jordan", "SSH_AUTH_SOCK=/tmp/ssh-JEjo6RVmNhvR/agent.30205", "SESSION_MANAGER=local/tesla:@/tmp/.ICE-unix/30329,unix/tesla:/tmp/.ICE-unix/30329", "PATH=/home/jordan/.gem/ruby/1.9.1/bin:/home/jordan/.gem/ruby/1.9.1/bin:/home/jordan/bin:/home/jordan/local/packer:/home/jordan/local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/sbin:/usr/local/sbin:/usr/sbin:/home/jordan/.rvm/bin:/home/jordan/prog/go/bin:/home/jordan/.rvm/bin:/home/jordan/prog/go/bin", "DESKTOP_SESSION=kde-plasma", "PWD=/home/jordan/games", "WORKING=/home/jordan/prog/greenspan", "KONSOLE_DBUS_WINDOW=/Windows/1", "EDITOR=emacs -nw", "LANG=en_US.UTF-8", "KDE_SESSION_UID=1000", "PS1=\\[\\033[01;32m\\]\\u@\\h\\[\\033[01;34m\\] \\w\\[\\033[1;31m\\]$(__git_ps1)\\[\\033[01;34m\\] \\$\\[\\033[00m\\] ", "KONSOLE_DBUS_SESSION=/Sessions/1", "SHLVL=2", "XDG_SEAT=seat0", "COLORFGBG=15;0", "HOME=/home/jordan", "LANGUAGE=", "KDE_SESSION_VERSION=4", "GOROOT=/home/jordan/local/go", "XCURSOR_THEME=oxy-zion", "LOGNAME=jordan", "DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-onouV6Cc66,guid=bcdceeabe7aa00a28d55899f5674608a", "XDG_DATA_DIRS=/usr/share:/usr/share:/usr/local/share", "GOPATH=/home/jordan/prog/go", "PROMPT_COMMAND=history -a", "WINDOWPATH=8", "DISPLAY=:0", "XDG_RUNTIME_DIR=/run/user/1000", "PROFILEHOME=", "QT_PLUGIN_PATH=/home/jordan/.kde/lib/kde4/plugins/:/usr/lib/kde4/plugins/", "XDG_CURRENT_DESKTOP=KDE", "HISTTIMEFORMAT=%F %T: ", "_=/bin/echo"]) = 0
[pid 32036] 21:32:20 write(1, "foo\n", 4) = 4
[pid 32036] 21:32:20 exit_group(0) = ?
[pid 32036] 21:32:20 +++ exited with 0 +++
21:32:20 <... wait4 resumed> [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], WSTOPPED|WCONTINUED, NULL) = 32036
I got a question too: does the output of the child pass through the shell itself? I think that since the child inherits the file descriptors from the shell, the kernel sends its output directly to the terminal, and the shell can't even know what the output is, but I don't know if I'm right. (unless, of course, the program is called through $(program), or anything like that)
| common-pile/stackexchange_filtered |
Delete a Class Instance
I'm trying to delete an instance of a class.
I have a <button> tag with an event listener a class method remove:
<msg-item>
<span>username: {{this.username}}</span>
<p>message: {{this.message}}</p>
<button ng-click="$ctrl.remove()">delete</button>
<msg-item>
<msg-item>
<span>username: {{this.username}}</span>
<p>message: {{this.message}}</p>
<button ng-click="$ctrl.remove()">delete</button>
<msg-item>
<msg-item>
<span>username: {{this.username}}</span>
<p>message: {{this.message}}</p>
<button ng-click="$ctrl.remove()">delete</button>
<msg-item>
The class:
class msgItemCtrl{
constructor(){
this.username = "johndoe";
this.message = "hello world";
}
remove(){
console.log('FIRING: Class Method (remove)');
delete this;
}
}
Question: How can I delete the instance of the class as well as the associated HTML from the interface?
What delete does https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
You can't delete variables or object instances (like delete this or delete myVariable), you can only remove properties from an object (like delete this.something or delete myVariable.something).
Javascript uses a garbage collector, you don't need to worry about deleting to save memory etc.. if nothing references this class, then the class will destroy on it's own.
@adeneo no this references the object
@Frxstrem yeah thats what I read on MDN but I need it to be removed from the interface. If I delete the object.props like username,password the html is still on the interface
@Keith Yeah I've also read that but, again it doesn't remove it from the interface, so even if delete all props referencing it, the html is still there.
@adeneo it's not Angular that does it, it's the new ES6 Classes, it handles the this variable differently.
What interface?.. If you mean the HTML, then it's the HTML part you delete,.. I must admit I'm not an anuglarjs user, but no matter what back end framework you use, you don't delete classes.. ES6 classes, are just sugar on top on Javascript function prototypes, nothing more.
@Keith nor am I, I like coding to js standards but manager at work only can code w/ angular lol.... anyway, yeah interface I meant HTML.
So are you trying to just remove the button
@adeneo I'm trying to delete the "component" angular term... which basically means a block of HTML <div>[span,button,etc..]</div> ...so deleting the div parent deleting all of it.
Removing the element is generally just element.remove();, no need to do anything to the class ?
@adeneo yeah no shit lol, but you would need to pass reference of the element to do so, in classes you instantiate the object, so you don't need to run reference. It should know already that the element.remove is applied to the root component tag for that particular instance, in this case msg-item.
Well, Angular is the devils work, and using classes for something as simple as an event handler that removes an element, sure does complicate things, doesn't it.
Anyway, I guess you have to pass the event, use $event.currentTarget etc. and go from there.
@adeneo completely agree about angular! lmao. Yes this is a simple example, but no the whole reason of classes is so you don't need to pass reference to the parent-node object.
@adeneo yeah I have in the pass been passing e.target then traversing upward from the trigger element and returning the first occurrence of whatever pattern, so in this case it would return msg-item the tag then I can preform a document.removeElement but thats the old school way now.
I have no idea how to get that parentNode inside the class, but someone else probably does, and once you have it, it should work with jQLite's remove() as well
@adeneo forsure yeah me either thats why I'm asking I've seen others do it, and I've done it myself... but again with pure JS, not something created by the Devil himself lmao.
| common-pile/stackexchange_filtered |
How to get reference to unnamed array from json
I am getting this back from the server:
{"Message":"The request is invalid.","ModelState":{"":["Name<EMAIL_ADDRESS>is already taken.","Email<EMAIL_ADDRESS>is already taken."]}}
How do I reference the first item of the array in JS? The debugger tells me that ModelState is an object, but there seems to be no name for the array.
You can reference the first item of your unnamed array like this:
var jsonString = {"Message":"The request is invalid.","ModelState":{"":["Name<EMAIL_ADDRESS>is already taken.","Email<EMAIL_ADDRESS>is already taken."]}};
console.log('first item: ', jsonString.ModelState[''][0]);
if test = {"Message":"The request is invalid.","ModelState":{"":["Name<EMAIL_ADDRESS>is already taken.","Email<EMAIL_ADDRESS>is already taken."]}}
then your array is at test['ModelState'][""]
| common-pile/stackexchange_filtered |
Exactness of $A\to A\amalg B\underset{(0,1)}\leftrightarrows B$
In a pointed category, the sequence $A\overset{(1,0)}\to A\times B\overset{(0,1)}\leftrightarrows B$ is always exact.
However, the "dual" sequence $A\to A\amalg B\underset{(0,1)}\leftrightarrows B$ is generally far from exact. Its exactness hints at a commutative situation. Consider for instance the category of monoids. The arrow $(0,1)$ acts on a reduced word via
$bab^\prime\mapsto bb^\prime$. If $bb^\prime=1\in B$ then $bab^\prime\in \operatorname{Ker}(0,1)\setminus A$, so the sequence is not exact.
Does the exactness of $A\to A\amalg B\underset{(0,1)}\leftrightarrows B$ in fact imply $A\amalg B\cong A\times B$? If not, what does it imply along this direction?
Update. As Eric Wofsey's answer points out, this is not true e.g for pointed sets. What if the category is assumed unital?
Can I ask for the definition of exactness in a pointed category?
@Randall I don't know of a good definition for images in this generality. Usually images are given by mono factors of some epi/mono factorization. In the first sequence of my question the left arrow is a split mono, so should equal its any useful notion of its image. By exactness I just meant to say the first arrow is the kernel of the second.
In the category of pointed sets, $A\to A\amalg B\to B$ is always exact, but coproducts and products are not isomorphic. What you can say is that if $A\to A\amalg B\to B$ is always exact, then the natural map $A\amalg B\to A\times B$ always has trivial kernel. Indeed, the kernel of $A\amalg B\to A\times B$ is just the pullback of the kernels of the two component maps $A\amalg B\to A$ and $A\amalg B\to B$, which by assumption are the inclusions $i:A\to A\amalg B$ and $j:B\to A\amalg B$. Now suppose $f:C\to A$ and $g:C\to B$ are maps such that $if=jg$. Composing $if=jg$ with the map $(1,0):A\amalg B\to A$ we find $f=(1,0)if=(1,0)jg=0$. Similarly, $g=0$. This shows that the pullback of $i$ and $j$ is $0$, as desired.
As for a unital example, I believe you can take the category of all monoids with the property that $xy=1$ implies $x=1$ and $y=1$. Such monoids are closed under limits and coproducts, and $A\to A\amalg B\to B$ is always exact for them. The map $A\amalg B\to A\times B$ is not typically an isomorphism for such monoids though: it is surjective and has trivial kernel, but it is not injective.
Great! The canonical map $A\amalg B\to A\times B$ is extremally epic by definition in unital categories. So in the finitely complete pointed protomodular case, where monomorphy is determined by kernels, the exactness of the sequence does imply it's a biproduct diagram.
Can anything be said in the unital case if only one of the sequences is exact?
No, I don't think so, or at least nothing interesting comes to mind.
| common-pile/stackexchange_filtered |
Multiply arrays to make matrix gives unexpected result
Suppose I have this code:
dim = 3
eye = [[0] * dim] * dim
and it is a list of list, I checked
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Now, if I do this, I get:
eye[1][2] = 1
eye
[[0, 0, 1], [0, 0, 1], [0, 0, 1]]
However, if I manually put in this expression, the above code works as expected:
eye2=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
eye2[1][2] = 1
eye2
[[0, 0, 0], [0, 0, 1], [0, 0, 0]]
What is the difference between the two ?
Update: Thanks for all the explanations, suppose I have this code:
a = [0]
type(a)
b = a * 3 # or b = [[0] *3]
So, b holds the 3 references to a. And I expect changing b[0] or b[1] or b[2] will change all 3 elements.
But this code shows the normal behavior, why is that ?
b[1] = 3
b
[0, 3, 0]
Someone taught me that I can do that kind of scalar multiplication to lists. If it turns out so weird, what is the application of this method ?
Any array entry is as a label of memory address and when you multiple it with a variable actually you create a pointer to 3 palace in your array ! you can figure it out with a list comprehension as below :
Matrix = [[0 for x in xrange(3)] for x in xrange(3)]
dim = 3
eye = [[0] * dim] * dim
print id(eye[0])
print id(eye[1])
print id(eye[2])
Ouput:-
139834251065392
139834251065392
139834251065392
So when you are doing eye = [[0] * dim] * dim it actually refrencing
refrencing three list to same object that is eye.
while in other case
eye2=[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
print id(eye2[1])
print id(eye2[2])
print id(eye2[0])
ouput:-
139863345170480
139863260058256
139863260067240
Here everytime refrence id is diffrent.
Very persuasive, thanks
@user1502776 Go through https://docs.python.org/2/reference/datamodel.html#objects-values-and-types. this will illustrate it.
dim = 3
eye = [[0] * dim] * dim
its make the copy of same, of if you change at one place it will be reflected to all
| common-pile/stackexchange_filtered |
Fokker-Planck confusion
So, I understand that solving the Fokker-Planck / Kolmogorov Forward equation gives the time-dependent probability density $p(x,t)$ in 1-D let's say.
My question is, how do you use this? Let's say, I wanted to find the probability of a particle being at a position $x = a$, at time $t = \tau$, how would you calculate this from $p(x,t)$?
Thanks!
It should be $0$, for a specific $x$.
But you can find the probability that the particle will be located in $[a-\delta/2;a+\delta/2]$ by integrating the equation.
Okay. thanks. But, that interval you cite is a spatial interval, I believe. How do you deal with the time variable in the integration?
| common-pile/stackexchange_filtered |
Differences between 'instrument' vs 'instrumentality', when used in the same sentence?
Source: (Page number unprinted), Chapter 2, Acing Your First Year of Law School ..., by Shana Connell Noyes, Henry S. Noyes
Delair v. McAdoo, Supreme Court of Pennsylvania, Nov 23 1936.
[Author:] KEPHART, Chief Justice.
... Any ordinary individual, whether a car owner or not,
knows that when a tire is worn through to the fabric, its further use is
dangerous and it should be removed. When worn through several plies, it
is very dangerous for further use. All drivers must be held to a knowledge
of these facts. An owner or operator cannot escape simply because he says
he does not know. He must know. The hazard is too great to permit cars in
this condition to be on the highway. It does not require opinion evidence to
demonstrate that a trigger pulled on a loaded gun makes the gun a
dangerous instrument when pointed at an individual, nor could one escape
liability by saying he did not know it was dangerous. The use of a tire
worn through to the fabric presents a similar situation. The rule must be
rigid if millions are to drive these instrumentalities which in a fraction of a second may become instruments of destruction to life and property. There
is no series of accidents more destructive or more terrifying in the use of
automobiles than those which come from "blow-outs."
Hereafter, I singularise the bold nouns above, because I ask about their differences in general.
1. What would change if I reversed instrumentality with instrument above?
2. What of using only instrumentality twice?
3. What of using only instrument twice?
It's just an example of the clunky language which results from a lawyer trying to write like a journalist. It's best to leave it aside and move on.
Like a bad journalist. "dangerous for further use"?
I think the usage is defensible. The cars are instrumentalities (defined by OED's sense 2 with pl. That which serves or is employed for some purpose or end; a means, an agency) with the explicitly-acknowledged "purpose or end" of getting people from place to place. Using two different word forms highlights the contrast between that "purpose by design" and the "accidental side-effect" encapsulated in the cliched instruments of destruction (with its overtones of being unwitting tools under the control of some higher entity such as Fate or the Devil).
I was commenting on the writing style. But the author is trying to make a little parable to show the legal difference between instrument and instrumentality. Not the clearest parable I've ever heard.
It appears the book is quoting a 1936 ruling from the Pennsylvania Supreme Court. "Dangerous for further use" appears to be a legalism going back to the 1800s. In everyday English, one would expect "Too dangerous for further use".
@TRomano Thanks for the elucidation. Yes it is. I had forgotten to cite this but have done so now.
It's not clunky. It scholarly legal writing.
Instrumentality simply means that it can become (or be used as) as instrument. An instrumentality is that which can be wielded as an instrument, i.e. perceived in terms of its capacity to be wielded.
Not all instruments can be held in the hand, of course; some can be abstractions, such as a legal entity, which can be "wielded" by another legal entity. A parent corporation can "wield" a subsidiary as if it were an "instrument".
| common-pile/stackexchange_filtered |
Setting up an s3 event notification for an existing bucket to SQS using cdk is trying to create an unknown lambda function
I am trying to setup an s3 event notification for an existing S3 bucket using aws cdk.
Below is the code.
bucket = s3.Bucket.from_bucket_name(self, "S3Bucket", f"some-{stack_settings.aws_account_id}")
bucket.add_event_notification(
s3.EventType.OBJECT_CREATED,
s3n.SqsDestination(queue),
s3.NotificationKeyFilter(
prefix="uploads/"
),
)
The stack creation fails and I am seeing below error on cloudformation console.
User: arn:aws:sts::<account>:assumed-role/some-cicd/i-8989898989xyz
is not authorized to perform: lambda:InvokeFunction on resource:
arn:aws:lambda:us-east-1:<account_number>:function:<some name>-a-BucketNotificationsHandl-b2kDmawsGjpL
because no identity-based policy allows the lambda:InvokeFunction action (Service: AWSLambda;
Status Code: 403; Error Code: AccessDeniedException; Request ID: c2d91744-416c-454d-a510-ff4cce061b80;
Proxy: null)
I am not sure what this lambda is. I am not trying to create any such lambda in my cdk app.
Does anyone know what is going on here and if there is anything wrong with my code ?
The ability to add notifications to an existing bucket is implemented with a custom resource - that is, a lambda that uses the AWS SDK to modify the bucket's settings.
CloudFormation invokes this lambda when creating this custom resource (also on update/delete).
If you would like details, here's the relevant github issue, you can see the commit that added the feature.
| common-pile/stackexchange_filtered |
How to clear interval in functional component if interval is set in a function?
I know that starting an interval in useEffect is easy to be cleared like this:
useEffect(() => {
const interval = setInterval(some function, time);
return () => clearInterval(interval)
})
But what if i have to set an interval inside a function, how to clear interval in that case, or simply i don't have to??
const startGame = () => {
const interval = setInterval(some function, time);
}
useEffect(() => {
startGame()
})
You can use clearInterval(interval) anywhere whether in. a function or useEffect. What does it have to do with it?
const interval = setInterval(interval); inside setInterval you need to provide a callback not the same assignment
@ABGR
I am creating a game and i have to set some intervals that should work at the start of the game in a function!
You can use thw useEffect hook to clear the interval
import React, { useEffect } from "react";
const Timer = () => {
const interval = React.useRef();
const startGame = () => {
interval.current = setInterval(() => {
//code
}, 3000);
};
React.useEffect(() => {
return () => {
clearInterval(interval.current);
};
}, []);
};
export default Timer;
what if i have several setInterval statments?
You can assign them to different properties of interval object like interval.a, interval.b and so on and then clear them too separately
@CodeEagle I'm not too sure if this will clear though. Does it work btw? My concern primarily is on this: when you clearInterval(interval.current);, you clear one value (let's say whatever, interval.current holds at that time, say number 15. But the ones that are assigned already may lead to infinite loop. Another concern is useEffect doesn't have any dependency here so it wouldn't be called after the initial load.
Use this code for example:
import React, { useEffect, useRef } from 'react';
const Timer = () => {
let interval = useRef();
const startGame = () => {
interval.current = setInterval(() => {
// your code
}, 1000)
}
useEffect(() => {
startGame();
return () => clearInterval(interval.current)
})
return (
// your jsx code;
);
};
export default Timer;
const interval = setInterval(interval); inside setInterval you need to provide a callback not the same assignment
I guess this is what you want:
var ctr = 0, interval = 0;
var startGame1 = () => {
ctr++;
clearInterval(interval);
console.log("hello")
if(ctr>=5){
clearInterval(interval);
}else{
interval = setInterval(()=>{startGame1()}, 1000);
}
}
startGame1()
The interval should update the game, so no condition needed to clear it in the game, i need to clear it in useEffect
I think you wanna check out @urvashi's answer above then. Does that not work?
| common-pile/stackexchange_filtered |
git diff-tree shows no output
I have read that the following command allows you to see all changed files of the last commit:
git diff-tree --no-commit-id --diff-filter=d --name-only -r $(Build.SourceVersion)
Unfortunately I have no luck, the command does not show anything.
How is that possible? I am currently on a branch called swagger-fix, so maybe the command is not able to see the branch?
Thank you for your help.
Or maybe the commit contains only deletions? Your command explicitly excludes these (--diff-filter=d).
Hello Romain, the command does not contain any deletions, just changed files. What are the other reasons why the output may be empty?
What's the output of $(Build.SourceVersion)? Also why using diff-tree rather than diff here?
The output of $(Build.SourceVersion) is simply the commit hash code (I also tried hardcoding it and the result is the same). I already tried diff as well, but i get the same results: no output.
Carnac the Magnificent says: You're using a CI system and you've forgotten to turn off shallow clones in the CI system. Turn off shallow clones (or set the depth to be at least 2).
Thank you so much Carnac, you solved the issue!
@torek Haha, Carnac answers everything! :-D
torek's comment is spot on:
Carnac the Magnificent says: You're using a CI system and you've forgotten to turn off shallow clones in the CI system. Turn off shallow clones (or set the depth to be at least 2).
So make sure to include such crucial information in your future questions :)
The solution: unshallow your CI clone or turn of shallow clones altogether.
I also had a similar problem, I was trying to run this command in docker-image.yml file and I found that when It clone repo for CI, it do a shellow copy.
To fix this, in docker-image.yml you need to add following.
jobs:
build-and-deploy:
runs-on: [self-hosted]
steps:
- name: Checkout code
uses: actions/checkout@v2
with:
fetch-depth: 0
This fetch-depth: 0, will ensure to fetch all commit history, so then you will be able to get changed file from commit.
Additionally, this might help you, who I'm getting changed files
- name: Get changed files
id: changed-files
run: |
touch ${{ github.workspace }}/changed_files.txt
echo ${{github.sha}}
echo $(git diff-tree --no-commit-id --name-only ${{github.sha}} -r) > changed_files.txt
cat ${{ github.workspace }}/changed_files.txt ; echo
Thanks I was scratching my head for so long. Finally this helped me.
Git's diffing will bypass merge commits unless you explicitly either ask for both/all parents with -m or --cc or specify which parent you're diffing against. Try specifying the first parent, $(Build.SourceVersion)~ $(Build.SourceVersion) This will have the added benefit of popping a complaint if you're inadvertently working with a shallow clone.
| common-pile/stackexchange_filtered |
Solving a logic puzzle via Prolog
So I have a knowledge base of these three tables
% order(customer_name, item_name, quantity).
% customer(name, credit_rating).
% item(name, quantity_in_stock).
I am supposed to find all valid orders. Valid orders are defined as valid customers with a good credit rating (rating above 500), the item the customer is ordering should exist in the stock and the order quantity must be less than that of the quantity_in_stock.
I already figured out for good rating, its just customer(X, Rating), Rating >=500. But I cannot figure out how to combine a good customer rating, quantity and then comparing that to the quantity_in_stock.
try modelling joins as you would do in SQL...
This does not look like a puzzle, but a very ordinary database query.
Start by describing what you want a little more precisely. How to combine a good customer rating, quantity... doesn't seem well-defined. What do you mean by combine? If you write it out logically, such-and-such if this, and that, and the other then it should be a little clearer what the Prolog should be.
| common-pile/stackexchange_filtered |
Count Waveform Periods and Calculate Frequency
I have some oscillating time v displacement excel data from an actuator that I need to analyze and my goal is to be able to count the cycles using the amount of times the displacement value crosses 0. Almost like counting the period of a sine wave. The problem I am having is that the frequency of this data changes several times throughout the data set and may not always or ever = 0. I think if I had a way to count the amount of times the displacement value "crossed" zero I could use every 3 of those points to calculate the wave forms cycles and frequency. I have written a lot of simple things in VBA but by no means am I an expert so any help would be appreciated.
I think an easy way to get it done would be to save compare the sign of the previous value to the current value's sign.
For example, value1 = -0.1236 , value2 = 0.5482. So inbetween those two values, you know it must have crossed 0. You can have the program check each value in the data, count up all the times the sign changes and that should be the number you're looking for.
Example code of how to compare the values:
If Current_Value < 0 <> Previous_Value < 0 then Counter = Counter + 1
| common-pile/stackexchange_filtered |
Cannot find command after reboot even though chmod +x was successful?
Dealing with a weird problem on CentOS trying to add the Play! framework to my path. Just earlier I successfully did a chmod +x play on Play! and I could run commands.
Then I rebooted and it completely fails. All attempts to retry chmod fail. I'm doing this from root user, it has 777 permissions, and belongs to the root group.
bash: play: command not found
What am I not considering?
It isn't enough to just add the directory to $PATH; you must make a change to your configuration to add it to $PATH on reboot or shell start. Try editing ~/.bashrc.
Perfect, thanks! Switched from Solaris and just not yet familiar with RHEL/CentOS yet ;) This did it alias play="/home/usrName/javaApi/play-1.1/play"
Aliases is a bad work around if you just wanted it in your $PATH, and Solaris works the same way by the way. See this link for more info on .bashrc and .bash_profile: http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html
| common-pile/stackexchange_filtered |
Wix msi updated property value not working during installation
Working with Wix in Visual Studio. I have a public property defined in Product node of wxs file.
<Property Id="MYPROP" Value="123456789"/>
The property value is passed as commandline argument to a deferred custom action executable. I'm able to receive it in the exe as well. The problem is even if I update the Property using vbs (verified through vbs select as well), when I launch the msi, it still passes the default/original value (123456789) to the custom action executable.
Also tried msiexec.exe /i myinstaller.msi MYPROP=SomeOtherValue
I'm still seeing the original value. What's wrong?
Maybe try this simple thing first:
<Property Id="MYPROP" Secure="yes" Value="123456789"/>
Essentially you need to add a property to the SecureCustomProperties list to have them pass properly to deferred mode in secure desktop environments.
See more information on SecureCustomProperties here. The technical details here are a little bit in flux because of Windows changes, so please just try this first - there could be several other reasons.
How do you use this property? What does it do?
When an msi is run, windows caches the msi file in %windows%\Installer folder. When that msi is run again, windows checks if an msi with identical PackageCode exists in the cache, if so then it uses the cached msi file instead.
PackageCode: identifies each unqiue msi installer package - even if it only has different properties.
In short, when a property is updated using a vbscript etc, then the PackageCode has to be updated as well. This will ensure that after updating msi, the same msi can be used on the same system and windows will not use the cached msi.
So the problem was that you used the same package code hard coded into every package? This is one "gotcha" of MSI. Never hard code package codes - set it to auto-generate (since it is just supposed to be unique). The fact that WiX allows hard coding must be for testing purposes? I have written about this before. Treating something as "identical by definition" is out there for sure... But technology has its quirks. It is basically enforced to force-run from the cached database as you state.
The package code wasn't hardcoded, however, I was trying to use the same msi file by updating properties through a vbscript. it would work the first time but subsequently use the old values, that was throwing me off. It eventually turned out to be msi caching, now I update package code each time I update a property. Part of the problem is msi is a whole world in itself, so for newbie like me lots of gotchas to run into
Is there a way to stop windows from using cached msi and/or not caching msi at all? I've noticed each time I change a property and run msi, windows copies the msi file to %windows%\Installer folder - resulting in many copies of the msi
No, it is a core part of the technology. What are you testing? Just change the MSI, uninstall the existing installation and then re-install. You can prevent the MSI from successfully running from the cache when you launch your modified copy by changing the product code in the MSI. Then MSI will not treat your MSI as identical to the one installed and it will say "a different version of this product is installed". Uninstall installed version and run the MSI with the changed product code again - it will now install with your changes.
Note that the system might be in a dirty state after many failed tests. If that is the case, try on a virtual? Or another box? Overall: avoid post-processing your MSI. Change things in the source and re-compile. What changes are you making to the MSI post-build?
| common-pile/stackexchange_filtered |
Docker-compose volumes not being mounted
I have a simple ASP.net Core project that I run in a docker container using docker-compose. I am trying to mount a host directory in order to save some files, for example log files.
My Dockerfile looks like this:
FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 55498
EXPOSE 44396
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY calibration-upload-server/calibration-upload-server.csproj calibration-upload-server/
RUN dotnet restore calibration-upload-server/calibration-upload-server.csproj
COPY . .
WORKDIR /src/calibration-upload-server
RUN dotnet build calibration-upload-server.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish calibration-upload-server.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "calibration-upload-server.dll"]
My docker-compose file:
version: '3.4'
services:
calibration-upload-server:
image: ${DOCKER_REGISTRY}calibration-upload-server
build:
context: .
dockerfile: calibration-upload-server/Dockerfile
volumes:
- C:/Uploads/logs:/logs
When building the solution in Visual studio, docker compose seems able to parse file, and the volumes group looks like this:
volumes:
- C:\Uploads\logs:/logs:rw
- C:\Users\UserName\AppData\Roaming\ASP.NET\Https:/root/.aspnet/https:ro
- C:\Users\UserName\AppData\Roaming\Microsoft\UserSecrets:/root/.microsoft/usersecrets:ro
So it seems the file got parsed correctly (the other two volumes are from the override file). But when I run the solution, docker run is run without this volume:
docker run -dt -v "C:\Users\UserName\vsdbg\vs2017u5:/remote_debugger:rw" -v "C:\Repos\calibration-upload-server\calibration-upload-server:/app" -v "C:\Users\UserName\AppData\Roaming\ASP.NET\Https:/root/.aspnet/https:ro" -v "C:\Users\UserName\AppData\Roaming\Microsoft\UserSecrets:/root/.microsoft/usersecrets:ro" -v "C:\Users\UserName\.nuget\packages\:/root/.nuget/fallbackpackages2" -v "C:\Program Files\dotnet\sdk\NuGetFallbackFolder:/root/.nuget/fallbackpackages" -e "DOTNET_USE_POLLING_FILE_WATCHER=1" -e "ASPNETCORE_ENVIRONMENT=Development" -e "ASPNETCORE_URLS=https://+:443;http://+:80" -e "ASPNETCORE_HTTPS_PORT=44396" -e "NUGET_PACKAGES=/root/.nuget/fallbackpackages2" -e "NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages;/root/.nuget/fallbackpackages2" -p 55498:80 -p 44396:443 --entrypoint tail calibrationuploadserver:dev -f /dev/null
The most frustrating part is that this worked just fine, until I renamed the solution and project. I have no idea if this is what broke it or not, but still.
One more thing that might be relevant, when building I get warned that The DOCKER_REGISTRY variable is not set. Defaulting to a blank string.
Is there anyway to figure out where the error is?
| common-pile/stackexchange_filtered |
Android - add item into calendar
is there some working sample of code of adding item into phone's calendar in Android? I want to add events with name, place, time and date.
Thanks
| common-pile/stackexchange_filtered |
Prime factors of $\sum_{k=1}^{30}k^{k^k}$
I checked the prime factors of
$$\sum_{k=1}^{30}k^{k^k}$$
and did not find any upto $10^8$
Are there any useful restrictions to accelerate the search ?
This is an interesting question on it's own, but could you tell us how did this come up?
I just searched the smallest prime factors of z(n) := $\sum_{k=1}^nk^{k^k}$ and the largest one occured for n=9 (it is 205991). And n=30 is the least n, such that z(n) has no small prime factors.
How are you currently doing this?
I use the powermod routine to calculate z(n) mod p
I have several ideas on how to test primes faster(FLT, sieving), but no one on how to dismiss primes without testing them, and I don't want to be redundant. Please show your current method to see if I can do any improvement to it(or if your method is better than the one I have in mind I would like to see it)
I use trial division because the numbers are too big to be tested for primality. It would be nice to have a method to calculate z(n) mod p faster.
Are you reducing the red part of $k^{\color{red}{k^k}}$ mod $p-1$?
Yes, I did that. Without that, the calculation is awfully slow.
This is only unproblematic for primes greater than n (so that gcd(p,$k^k$)=1 is guaranteed), but for relatively small n, this is no great problem.
Please add all the info and thoughts you have so far so that we can stop guessing about your method, it helps everyone to undeestand and help you better.
I wrote a small C program using the n_powmod2_preinv function in the Flint Number Theory Library. I used the tricks you already mentioned and checked up to $5\cdot10^{10}$ and didn't find any factors.
I have already described what I have done.
| common-pile/stackexchange_filtered |
Converting button events etc to ASP.NET MVC
Given an asp.net webform page which does something like
asp.net
<asp:textbox id="txtA" runat="server" />
<asp:textbox id="txtB" runat="server" />
<asp:button id="btnAddTogether" runat="server" text="Go" onclick="btn_Click"/>
<asp:textbox id="txtResult" runat="server" />
code behind
protected void btn_Click(...)
{
txtResult.Text = txtA.Text + txtB.Text;
}
How would I convert this to ASP.NET MVC. It's a pretty trivial example, but I'm not sure about how to change my way of thinking.
There's really no direct conversion.
Theoretically, that button would be submitting a Model (via a <form> tag) to a Controller for an Update Action. The string manipulation would then happen inside of your Controller code.
Your example would become something like:
<% using Html.BeginForm("Update", "Home") { %>
<%= Html.TextBox("txtA") %>
<%= Html.TextBox("txtB") %>
<input type="submit" value="Submit" />
<% } %
And then your controller would have:
public class HomeController : Controller
{
public ActionResult Update(string txtA, string txtB)
{
ViewData["result"] = txtA + txtB;
}
}
Would you be able to give me an example to get started with please.
Thanks Justin. As @Anero mentions, this is a hacky way but it will work. Am already converting to ViewData way now :)
@Sophie88: Using ViewData is bad approach. You should stay away from non strongly types solutions. Using view model is the best way.
@Sophie88 LukLed is right, you should try to work towards using a ViewModel (which is strongly typed, unlike the ViewData collection).
I'd also recommend you to read the MVC tutorials, but for this particular case you would do something like the following.
In the .aspx (let's assume it's called ViewA):
<% using(Html.BeginForm("Concatenate"))
{ %>
<%= Html.TextBox("txtA") %>
<%= Html.TextBox("txtB") %>
<input type="submit" value="Go" />
<% } %>
<%= Html.TextBox("txtResult")%>
In the Controller for that View you'll need an action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Concatenate(string txtA, string txtB)
{
this.ViewData["txtResult"] = txtA + txtB;
return this.View("ViewA");
}
Note that this isn't the recommended way, instead of using the ViewData dictionary, you sould use a specific ViewModel class with all the data for the particular view.
+1 for the addendum - there is a fundamental mental shift between MVC and ASP.NET "classic", which goes all the way back to the basic plumbing and concepts. Yes, you can do stuff the "old" way, but it really gets hacky, fast.
@Anero - thanks. This is a great solution, but I'll be doing it best-practice :)
There is such a method, too.
[AttributeUsage(AttributeTargets.Method,
AllowMultiple = false, Inherited = true)]
public class SubmitCommandAttribute : ActionMethodSelectorAttribute
{
private string _submitName;
private string _submitValue;
private static readonly AcceptVerbsAttribute _innerAttribute =
new AcceptVerbsAttribute(HttpVerbs.Post);
public SubmitCommandAttribute(string name) : this(name, string.Empty) { }
public SubmitCommandAttribute(string name, string value)
{
_submitName = name;
_submitValue = value;
}
public override bool IsValidForRequest(ControllerContext controllerContext,
MethodInfo methodInfo)
{
if (!_innerAttribute.IsValidForRequest(controllerContext, methodInfo))
return false;
// Form Value
var submitted = controllerContext.RequestContext
.HttpContext
.Request.Form[_submitName];
return string.IsNullOrEmpty(_submitValue)
? !string.IsNullOrEmpty(submitted)
: string.Equals(submitted, _submitValue,
StringComparison.InvariantCultureIgnoreCase);
}
}
Sample controller code.
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[ActionName("Different")]
[SubmitCommand("DoSave")]
public ActionResult DifferentSave()
{
TempData["message"] = "saved! - defferent";
return View("Index");
}
[ActionName("Different")]
[SubmitCommand("DoDelete")]
public ActionResult DifferentDelete()
{
TempData["message"] = "deleted! - defferent";
return View("Index");
}
[ActionName("Same")]
[SubmitCommand("DoSubmit","Save")]
public ActionResult SameSave()
{
TempData["message"] = "saved! - same";
return View("Index");
}
[ActionName("Same")]
[SubmitCommand("DoSubmit","Delete")]
public ActionResult SameDelete()
{
TempData["message"] = "deleted! - same";
return View("Index");
}
}
and view.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<h1><%= TempData["message"] ?? "Click some button" %></h1>
<h2>Different sumit name(ignore value).</h2>
<% using (Html.BeginForm("Different", "Home")) { %>
<input type="submit" name="DoSave" value="Save" /><br />
<input type="submit" name="DoDelete" value="Delete" />
<% } %>
<h2>same submit name and different value.</h2>
<% using (Html.BeginForm("Same","Home")) { %>
<input type="submit" name="DoSubmit" value="Save" /><br />
<input type="submit" name="DoSubmit" value="Delete" />
<% } %>
</body>
</html>
Hope this code.
Instead of a Click handler, you make a <form> tag that submits to an Action.
The action can then perform its logic and return a view that displays the result.
You don't have to create any views, like others suggested. You don't have to wrap it up into form, because these inputs will be propably part of bigger form.
When you start using ASP.NET MVC, you have to learn JavaScript/jQuery. It can replace a lot of functions that were solved by using postback mechanism in WebForms.
This example can be easily solved on client side or server side:
<form action="" method="post">
<%= Html.TextBox("txtA") %>
<%= Html.TextBox("txtB") %>
<button id="btClientSideAdd" onclick="$('#txtResult').val($('#txtA').val() + $('#txtB').val()); return false;">
Add on client</button>
<button id="btServerSideAdd" onclick="$.post('Home/Add', { a: $('#txtA').val(), b: $('#txtB').val() }, function(data) { $('#txtResult').val(data) }); return false;">
Add on server</button>
<%= Html.TextBox("txtResult") %>
<input type="submit" />
</form>
Additional code for server side:
public JsonResult Add(string txtA, string txtB)
{
return Json(txtA + txtB);
}
This code adds on client side:
$('#txtResult').val($('#txtA').val() + $('#txtB').val());
You can also pass values to server:
$.post(
'Home/Add', //Action to execute
{ a: $('#txtA').val(), b: $('#txtB').val() }, //input values
function(data) { $('#txtResult').val(data) } //what to do with result
);
To do it on client side, you have to use jQuery.post()/jQuery.ajax(). Read about using partial view and JsonResults.
Although jQuery is included with MVC, there is no requirement to use it. While it works for this trivial example, it's probably not good advice long-term or for more complex business logic.
@GalacticCowboy: Sorry, but I don't agree. jQuery/AJAX is basic tool when you want to update part of the page. Do you want to post whole page to update one field? This is crazy. There is no requirement to use jQuery, but it is not wise not to.
As I said, "While it works for this trivial example..." - I think you stated precisely what I was trying to say. The OP is a rather trivial example, so yes in that scenario jQuery makes perfect sense. As a larger example of how to handle form submissions, etc., not so much.
@GalacticCowboy: But it is not form submission. If it was form submission, there would be other postback code. There is absolutely no submission code (there is no further processing, validation, saving to database etc.). She wants to fill some parts of the form and continue work on it.
She is asking about the "MVC Way" - the mental shift in MVC vs. ASP.NET. As stated in the OP, it is a simple, contrived example that demonstrates submitting a form in ASP.NET, doing something server-side and returning a response to the client. You are correct that the stated problem is best solved without posting back to the server. What I am trying to say is that the stated problem is only a proxy for the real problem, how did form processing change from ASP.NET to MVC?
Better if you check MVC tutorials here. http://www.asp.net/learn/mvc/.
And if you are really looking for changing a current application to MVC then you should see this video first.
| common-pile/stackexchange_filtered |
How to know if a facebook friend has a significant other but does not want to disclose?
I am trying to use facebook api to get my friends' relationship status:
FB.api("/me/friends", {
fields: "id, name, relationship_status, significant_other, picture.type(large)"
}, function (response) {
if (response.data) {
...
$.each(response.data, function (index, data) {
if (data.significant_other) {
// If has a significant other
} else {
// If do not have a significant other
}
});
}
});
I tried to determine if a friend has a significant other by looking at the significant_other field. But how can I know if my friend has a significant other but doesn't want to disclose?
how can I know if my friend has a significant other but doesn't want to disclose? Ask them directly? If the information isn't available via the API, it's not available.
Ugh. App devs wanting to do stuff like this is one of the biggest reasons I hate Facebook apps.
I have a solution. If relationship_status equals "In a relationship" but data.significant_other is not in the data. Then that means the friend has a significant_other but does not want to disclose.
If data isn't accessible via the API, there's no way to access that data via the API
This is pretty much a tautology, but if the data were accessible to you, you'd have it via the API call you just included in your question
| common-pile/stackexchange_filtered |
How to extract annotations from CVAT XML file generated using SAM model into mask files in Python
I'm new to CV. I have an annotation XML file generated using the CVAT semi-automated SAM model.
May I know how I can load the XML file and extract the object I am interested in as a mask in jupyter notebook environment? I have 4 object classes and 1000 images.
Sample of annotation content
<annotations>
<version>1.1</version>
<meta>
<job>.....
<label>
<name>objectClass1</name>
<color>#00c44e</color>
<type>any</type>
<attributes> </attributes>
</label>
...
</job>
</meta>
<image id="0" name="KKM22(1).jpg" width="3024" height="4032">
<mask label="KKM22" source="semi-auto" occluded="0" rle="772, 4, 1609, 40, 1579, 77, 1485, 38, 17, 92, 1459, 172, 1448, 183, 1440, 191, 1434, 197, 1426, 206, 1416, 218, 1403, 234, 1392, 243, 1382,
.....
</image>
I have tried a couple of times referring to online tutorial but the result I obtained is in the bounding box instead of the mask.
| common-pile/stackexchange_filtered |
File not exists in Docker container
I have a docker container running and the file structure looks as below.
My work directory is '/app' and I have copied all files into it from my local system. Basically, I want to run Apache Bench with SSL support and hence I have copied these 3 files as well into the workdir.
abs.exe
libcrypto-1_1-x64.dll
libssl-1_1-x64.dll
My DockerFile looks as below
FROM python:3.7
COPY requirements.txt /
RUN pip install -r /requirements.txt
COPY ./ /app
WORKDIR /app
CMD [ "python", "ab_script.py"]
and in the file ab_script.py, I am invoking the script
subprocess.Popen(['abs', '-n 100', '-c 10', 'https://my-url.com'],
stdout=subprocess.PIPE,
universal_newlines=True)
Though it runs completely fine on my local, I getting the below error when I execute it from Docker.
Traceback (most recent call last):
File "ab_script.py", line 70, in <module>
cold_start_process = start_cold_start_process()
File "ab_script.py", line 28, in start_cold_start_process
universal_newlines=True)
File "/usr/local/lib/python3.7/subprocess.py", line 800, in __init__
restore_signals, start_new_session)
File "/usr/local/lib/python3.7/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'abs': 'abs'
Even though I have placed the file abs.exe in the workdir, it says that the file is not found. Could anyone please let me know where I might be going wrong? Thanks.
If the file is called abs.exe then subprocess.Popen(['abs', ...]) is never going to find it. Even if you correct the filename, it still won't work because your current directory is generally not searched for binary names. You would need to provide an explicit path with the correct name, such as:
subprocess.Popen(['./abs.exe', '-n 100', '-c 10', 'https://my-url.com'],
stdout=subprocess.PIPE,
universal_newlines=True)
Thanks you. But with this, I am getting the error OSError: [Errno 8] Exec format error: './abs.exe'
That suggests that you've copied in a binary that has been built for the wrong platform. It looks like you're running a Linux container, but the name abs.exe makes me wonder if you're trying to run a Windows binary. That's not going to work.
Got it. So installed apache-utils in DockerFile and it's working fine ! Thanks
| common-pile/stackexchange_filtered |
Move UIImage horizontally with animation
I want to move UIImageView horizontally from left to right and right to left.
I designed this as below.
UIView (green color)
Arrow Image (Leading of UIView, Center vertically of UIView, Fix Height, Width)
UILabel (Center Horizontally & center Vertically of UIView)
Button (Leading, Top, Trailing, Bottom of UIView)
In above image, Green color is UIView and the left arrow icon is image. so when user press the button i want to move Arrow Image from Left to Right and Right to Left vice versa.
EDIT 1
Thanks for your answer
if sender.isSelected {
UIView.animate(withDuration: 1.0, animations: {
self.imgVWInOut.frame.origin.x = (self.vwPunchInOut.bounds.maxX - self.imgVWInOut.bounds.width) - 10
}) { (done) in
}
} else {
UIView.animate(withDuration: 1.0, animations: {
self.imgVWInOut.frame.origin.x = 10
}) { (done) in
}
}
But when i try to change UIView background color and UIImageView image then animation not working proper.
@IBAction func btnPunchInOutTapped(_ sender: UIButton) {
sender.isSelected = !sender.isSelected
if sender.isSelected {
UIView.animate(withDuration: 1.0, animations: {
self.imgVWInOut.frame.origin.x = (self.vwPunchInOut.bounds.maxX - self.imgVWInOut.bounds.width) - 10
}) { (done) in
self.imgVWInOut.image = #imageLiteral(resourceName: "ic_punchout")
self.lblPunchInOut.text = "Punch out".localized()
self.vwPunchInOut.backgroundColor = Colors.punchOutColor
}
} else {
UIView.animate(withDuration: 1.0, animations: {
self.imgVWInOut.frame.origin.x = 10
}) { (done) in
self.imgVWInOut.image = #imageLiteral(resourceName: "ic_punchout")
self.lblPunchInOut.text = "Punch out".localized()
self.vwPunchInOut.backgroundColor = Colors.punchOutColor
}
}
}
Requirement
Default look likes this.
enter image description here
When user press button it will look like this after animation done.
enter image description here
GIF Link : https://drive.google.com/file/d/1R2hfcwfhyO5JA9CQt1_6Auto3YBRj3yn/view?usp=sharing
Demo project Link :https://drive.google.com/file/d/1H0b3D61fPIxWqSZL8tdvp0RP8juVdr_Z/view?usp=sharing
How can i achieve this. will you please help me for that.
Thanks
Have you tried anything so far?
You need to animate the frame of arrowImageView w.r.t to the customView(green color view), i.e.
@IBAction func onTapButton(_ sender: UIButton) {
self.arrowImageView.frame.origin.x = self.customView.bounds.minX
UIView.animate(withDuration: 1.0) {
self.arrowImageView.frame.origin.x = self.customView.bounds.maxX - self.arrowImageView.bounds.width
}
}
Give the animation duration as per your requirement.
EDIT:
You need to change the isSelected state of sender on button tap,
@IBAction func onTapButton(_ sender: UIButton) {
sender.isSelected = !sender.isSelected //here...
//rest of the code...
}
Thanks, i want same thing like this. let me try this
@KuldeepParmar Do accept (tick on left) if you get that working.
will you please review my updated question. It works but when i try to change UIView BG color and UIImageView image then it wasn't working.
@KuldeepParmar Please elaborate your requirement for selected and not selected state.
I updated my question with requirement, will you please review this.
It is working fine with me. Try adding the code in DispatchQueue.main.async
@KuldeepParmar The link is not accessible.
can you please try this : https://gofile.io/d/KETavy
I found the issue, when i change label text then issue generates.
Yes, when i remove UILabel from subview of UIView and put in over UIView then animation won't disturb. Thanks for your help
| common-pile/stackexchange_filtered |
Python - WebScraping using Request module-URL throws an error -403- forbidden
I'm trying to get the data from https://www.ecfr.gov/cgi-bin/ECFR?page=browse
using requests module in python
Somehow I'm getting HTTP 403-forbidden.
header = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "max-age=0",
"Host": "httpbin.org",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "none",
"Sec-Fetch-User": "?1",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-5ef3288f-10e678d0e55c0670c0807730"}
r = requests.get(url , headers= header)
I have also requested using user-agent and all the parameters in headers info(which I'm seeing in developer tools) .
I have tried using free proxies / rotating user header /cookies and everything i can get my hands on. But somehow website is able to know that I'm not using header.
In the html response - I'm seeing that website is asking to complete captcha.
Is there anyways I can skip that ?
That is the whole point of captchas. They are designed to be unskippable. Look for an API or something, there is no sure way other than that.
Inspecting the http requests, I've found the cloudflare server response trace:
The Cloudflare or ScrapeShield is famous for its scrape protection, security levels. Read more here.
Is there anyways I can skip that ?
There are 2 ways out:
Apply (plug-in) a captcha solving service. That is not that easy providing you use sole python coding.
Leverage the browser automation, making ScrapeShield to think that a real user browses the website. It does take much more resources and time (incl. development time). See a scrape speed comparison table of Chromium headless instance automation vs bare http requests.
| common-pile/stackexchange_filtered |
CSS3 :target issue
I have 2 "links" which has to get a color when i click on them. But they need also be in a h1 tag.
Like this:
<div id="content" class="work">
<h1 style="border-bottom:1px solid #CCC;"><a id="link-grafisk-design" href="#grafisk-design">Grafisk design</a></h1>
<h1 style="border-bottom:1px solid #CCC;"> / </h1>
<h1 style="border-bottom:1px solid #CCC; width:276px"><a id="link-webbdesign" href="#webbdesign">Webbdesign</a></h1>
</div>
But it wont change color when i click in one of them.
Here's the CSS
#webbdesign:target ~ #link-webbdesign {
color:#00A2FF;
}
And where's the element with the id of 'webdesign'?
"But they need also be in a h2 tag". I don't see any h2 tags in your code
the link has an id named link-webbdesign
sorry meant h1 tag
But #webdesign won't link to anything with an id of link-webdesign.
This question is all too confusing for me to be confident that you understand how :target and anchor links work.
@BoltClock i'm trying to achieve the same effect from the tutorial
http://tympanus.net/codrops/2012/01/30/page-transitions-with-css3/
That's not what :target is for. For styling the link you click on you should use h1 a:active.
h1 a:active {
color:#00A2FF;
}
If you want the changed colour to persist until the user clicks something else, then use:
h1 a:focus,
h1 a:active {
color: #00A2FF;
}
DEMO
i want to use target because i will work with transitions and other stuffs later on the same page
@Adib93: Do you want to style the link you click on, or do you want to style the section it leads to? :active is for styling the link itself, :target is for styling the section the link that was clicked goes to.
right now i just want to style the link, but i will use target for styling the section later. And i tried active and it only changed the color for a second, when the mouse was clicked but dissapers after i released
Using the :active and focus pseudo-classes/selectors will only style the element while those conditions are true; which, for mouse input, is usually only while the mouse-button is held down.
@David Thomas: Actually, using :active and :focus is an old trick to get "on click behaviour" with only CSS for things like drop-down menus http://jsfiddle.net/thebabydino/S8Kwq/ or accordions http://dabblet.com/gist/1728264 . You just need to add tabindex="1" and it persists until something else is clicked - I've updated my answer with a demo.
but it wont change unless you click on the other link "grafisk design" and vice versa....
i'm trying to do like the tutorial http://tympanus.net/codrops/2012/01/30/page-transitions-with-css3/
| common-pile/stackexchange_filtered |
How much should I tell the DM about my PC's plans?
The campaign just reached a turning point: an NPC we believed to be an ally betrayed us PCs and gained the power of a god. My PC and another PC were put into a stasis for 3 years while the former ally razed most of the continent. After we were freed, we met up with our former party.
Now I'm considering having my PC pretend to join the former ally's side so that my PC can betray him like he betrayed us.
Should I tell the DM that's my PC's plan or should I surprise the DM with my PC's plan the same way the NPC surprised us with his?
Welcome to the site! Take the [tour]. Is the group's playstyle collaborative that sees everyone (including the DM) working together to tell a good story or is the group's playstyle adversarial that sees everyone (especially the DM) keeping things to themselves and scheming against each other or somewhere in between? Thank you for participating and have fun!
Our playstyle fits somewhere in between. Our DM seems unable to really make up his mind whether he wants to tell a wonderful story, versus wanting to crush us into the ground. I think it leans a bit more towards adversarial, considering we have a player who is plotting to raise an army of demons. (I barely managed to drag that answer out of him, at that.)
It is important to note that while the DM does portray your enemies and adversaries, that is not his only job. It also falls on him to enforce the rules of the fantasy world and to present a good story for all. There are two consequences of this:
The DM has to be able to judge situations
There are rules for tricking characters. The DM has to enforce those rules. If he is unaware that you are lying he cannot do that. Also, most likely when you profess your desire to work for the villain to him (the character) or sometime soon after in a similar situation the DM will outright ask you whether you are deceiving him or not. For the above reasons not telling him (the DM) that you are is cheating.
The DM is not your adversary
How the DM and the players play characters and how they care about them is different. You want to see your hero rise up to challenges and be victorious. While for this to be meaningful there has to be something in your way, the DM knows that the fate of most antagonists is to fall. You can do everything in your power to save your character because there is something limiting you. The DM cannot do that without breaking the game as he is not limited. If your DM understands this, there is no need to trick him to trick a villain.
Thus you should discuss your plans with the DM.
These are tricky situations. If you completely surprise your DM, thare’s a possibility you may short-circuit the plot arc, or torpedo the whole campaign. On the other had, if you tip your DM off, your opportunity to spring an effective ambush might be lost. A little ambiguity might be best.
It depends on whether the DM needs to know
There are valid reasons to keep a thing or two from the DM. It’s very hard to ignore information once it’s in your head. If you tell the DM that you are planning on betraying an NPC, that will certainly affect how they run the game, subtly, or not so subtly.
Be congizant of your DM’s storytelling
While some DM’s would be totally OK with a big player-initiated plot twists, for others it won’t be a lot of fun tearing up their planned encounters, maps, and lovingly-invented NPC’s. In your case, it sounds like this NPC is a pretty central character to the campaign, so use some care.
If your DM has a high-preparation style, it may be better to let him know you want to go down the “Let’s prepare to betray this guy” plot line.
You know your DM better than we do, so let that inform your actions.
If you’re unsure how much your betrayal might disrupt (or improve) the game, you can casually ask how it would go if “somebody” betrayed the NPC instead of going along with his plans. It’s hard to tell, though, how much a DM will pick up on your intentions. Just like PC’s confronted with a mystery, they might catch on the subtlest hint, or remain oblivious to the most obvious tip-offs.
A Shocking Reveal is Great Fun
I once had a PC who got captured, and agreed with his captor to try to take the rest of the party prisoner too. Everybody at the table was fooled. Even when I said, “I draw my sword and step behind [my captor],” nobody suspected I was doing anything other than seeking his protection.
If you want folks to gasp and drop their jaws when you spring your ambush, then keep your plans to yourself.
Since the DM is revealing a big plot here, it would be best to do this at the thrilling climax, instead of trying to blow up the story half-way through.
A Need-to-Know Basis
On the other hand, your treachery may be of the sort that requires preparation that you can’t hide from your DM. If you need a certain item, etc., to turn the tide on your adversary, then of course you’ll need to talk to your DM about your plans to acquire it.
But you can be cagey about your reasons. You might profess that you are looking to take possession of the dangerous artifact to keep it out of the hands of troublesome do-gooders.
Final Answer: Tell the DM what they need to know
| common-pile/stackexchange_filtered |
Change the text of textbox through javascript/jquery
I want to change the value of textbox through javascript.
I have a user control from which I call a js file. There is a textbox in the usercontrol and then in the js file i pass that textbox value. After the button(it is in user control) is clicked, the js file does some operations. After the button is clicked and operations are over, i want to change the value of the textbox.
User control
a textbox and a button
string submitArgs = String.Format("'{0}',tboxTimeMeasured.ClientID);
JsSubmitValues.Value = "javascript:SubmitMeasure(" + submitArgs + ");";
Js File:
function SubmitMeasure(control_TimeMeasured) {
//some operations
//and success= true
if (success) {
alert("Your changes have been saved successfully!");
var datetimeNow = new Date();
control_TimeMeasured.value = datetimeNow.getHours() + ":" + datetimeNow.getMinutes();
}
}
Here, it goes in the success loop, the control_TimeMeasured is the value of textbox which is passed from a user control to a 'js' file. How can I change the value of control_TimeMeasured ??
Its unclear exactly what you're asking. Perhaps you could try to explain exactly what the symptoms of the problem you are seeing are. Can you use the web browser development tools to debug what control_TimeMeasured is?
If control_TimeMeasured is an ASP.NET textbox that's being rendered on the server side, chances are its runtime ID will be different than what you have specified. You can use the <%= control_TimeMeasured.ClientID %> syntax to get its runtime ID. You also want to select the control (using its ID) before you can change its properties; you have to do a little bit more than just referencing it by its name. Try this:
document.getElementById("<%= control_TimeMeasured.ClientID %>").value =
datetimeNow.getHours() + ":" + datetimeNow.getMinutes();
Alternatively, if you have jQuery, you can do this:
$("#<%= control_TimeMeasured.ClientID %>")[0].value =
datetimeNow.getHours() + ":" + datetimeNow.getMinutes();
Now if control_TimeMeasured is just a normal input element, you can simply do this:
document.getElementById("control_TimeMeasured").value =
datetimeNow.getHours() + ":" + datetimeNow.getMinutes();
I tried first 2 options:
Erron 1st: Unable to set property 'value' of undefined or null reference
Erron 2nd: Syntax error, unrecognized expression: #<%= control_TimeMeasured.ClientID %>
I cahnged the 2nd value to $("#" + control_TimeMeasured.ClientID)[0].value = 'hi'; Then it is giving error as first one
I think there is no property as value, it is valueof.
Is there a control on your page with ID set to control_TimeMeasured? Can you post the exact value of control_TimeMeasured?
<asp:TextBox ID="tboxTimeMeasured" runat="server" Width="100px" ></asp:TextBox>
But the value which is passed from user control to js file is in control_TimeMeasured
In your example control_TimeMeasured will be a string. To use this in javascript you will need to use the id to find the element like this.
UPDATED:
var element = document.getElementById(control_TimeMeasured);
if(element){
if(element.tagName.toUpperCase() == 'INPUT'){
var datetimeNow = new Date();
element.value = datetimeNow.getHours() + ":" + datetimeNow.getMinutes();
}else{
console.error('element is not an input. Element is \'' + element.tagName + '\'.');
}
}else{
console.error('element with id\'' + control_TimeMeasured + '\' was not found.');
}
getting the error: Unable to set property 'value' of undefined or null reference
I think there is no property as value, it is valueof.
In that case I imagine there is no element on the page with that id. I've updated the example to help you debug. if the element is not found the javascript will log the id to the console. Then you will be able to see what the ID is and if it matches with the id in the input tag.
@user1989 value is a property of the HTML input element - https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement#Properties
It does not go in the else loop. So there would be something in the element. But when i write 'element' and try for intellisense, it gives me option for valueof and not value
then I suspect the element is not an input element, Can you see the TagName property of element in your debugger?
<asp:TextBox ID="tboxTimeMeasured" runat="server" Width="100px" ></asp:TextBox>
| common-pile/stackexchange_filtered |
Sending messages from background thread to main thread in a number crunching application
I have a number crunching application in Delphi that uses one or more background threads to process numerical data. These background threads run several parallel processes each simultaneously. From these threads I use the WM_COPYDATA message to pass information to the main thread, in order to provide feedback to the users.
In my PC I have the Intel Core i7-10750H CPU processor (6 physical cores and 12 threads) and my RAM is 32GB.
When I run one or two analyses simultaneously (CPU usage 50- 80%, memory consumption 1-2GB) , the messages are passed and processed by the main thread correctly, i.e., I get the feedback in the GUI of the main form. However, when I push the system to its limits (6 parallel analyses in a PC with 6 physical cores, CPU usage > 90%, memory consumption > 2.5GB), very often the messages are not passed to the main thread and I get no feedback in the GUI (somehow they seem to be lost). However, the background threads run correctly and at the end of the analyses they provide the correct results.
What is the problem and the messages are not processed? Can I do something to fix this problem?
Many thanks in advance.
The data are passed with the following record:
type
TCommunicationMsgRecord = record
AnalysisID: integer;
UpdateType: integer;
MessageStr: String[255];
prbProgress: integer;
valX,valY: real;
end;
The code in the background thread is the following:
procedure TExecution.SetMainFormMemoProcess(const str: string);
var
CommunicationMsgRecord: TCommunicationMsgRecord;
copyDataStruct : TCopyDataStruct;
begin
CommunicationMsgRecord.AnalysisID := Self.ExecutionID;
CommunicationMsgRecord.UpdateType := 0;
CommunicationMsgRecord.MessageStr := StrLeft(str,255);
CommunicationMsgRecord.prbProgress := 0;
CommunicationMsgRecord.valX := 0;
CommunicationMsgRecord.valY := 0;
//------------------------------------------------------
copyDataStruct.dwData := 0;
copyDataStruct.cbData := SizeOf(CommunicationMsgRecord);
copyDataStruct.lpData := @CommunicationMsgRecord;
SendMessage(MainForm.handle, WM_COPYDATA, Integer(hInstance), Integer(@copyDataStruct));
end;
The code in the main thread is the following:
type
TMainForm = class(TForm)
private
procedure WMCopyData( var Msg : TWMCopyData ); message WM_COPYDATA;
implementation
procedure TMainForm.WMCopyData(var Msg: TWMCopyData);
var
CommunicationMsgRecord : TCommunicationMsgRecord;
begin
try
CommunicationMsgRecord:= TCommunicationMsgRecord(Msg.CopyDataStruct.lpData^);
case CommunicationMsgRecord.UpdateType of
0: MainForm.memoProcess.Lines.Add(CommunicationMsgRecord.MessageStr);
1: MainForm.Statusbar.Panels[0].Text := CommunicationMsgRecord.MessageStr;
//other options (e.g. plotting) that receive the data from CommunicationMsgRecord
//....
end;
except
on E: EAccessViolation do
begin
ShowMessage('Access Violation');
end;
on E: Exception do //this will catch all your other exceptions
begin
ShowMessage('Other Error');
end;
end;
end;
Never catch EAccessViolation. That's one of the most serious exception you can get, and something that should never every happen in your app. Well written code should never raise such an exception. It should be mathematically impossible (at least if you disregard malfunctioning hardware, OS bugs, hardware driver bugs etc.). In addition, you are never guaranteed to get an AV exception: sometimes you get no exception at all, but memory corruption that may or may not manifest itself in the future. (Maybe you'll send an incorrect $15651233213 invoice a week later.)
First, using WM_COPYDATA is overkill in this situation. It is meant for serializing data across process boundaries, which you are not doing. Since you are sending data to a window in the same process, just send the data pointer directly in a custom message.
Also, do not use Integer() type-casts, that will only work in 32-bit. If you ever decide to compile your app for 64-bit (ie, to access more memory), the code shown will fail. The 4th parameter of SendMessage() is an LPARAM, not an Integer. LPARAM is a 32bit or 64bit integer, depending on the CPU architecture. Use the proper type.
type
PCommunicationMsgRecord = ^TCommunicationMsgRecord;
TCommunicationMsgRecord = record
AnalysisID: integer;
UpdateType: integer;
MessageStr: String[255];
prbProgress: integer;
valX,valY: real;
end;
const
WM_MY_DATA_MSG = WM_APP + 100;
procedure TExecution.SetMainFormMemoProcess(const str: string);
var
CommunicationMsgRecord: TCommunicationMsgRecord;
begin
CommunicationMsgRecord.AnalysisID := Self.ExecutionID;
CommunicationMsgRecord.UpdateType := 0;
CommunicationMsgRecord.MessageStr := StrLeft(str,255);
CommunicationMsgRecord.prbProgress := 0;
CommunicationMsgRecord.valX := 0;
CommunicationMsgRecord.valY := 0;
SendMessage(MainForm.Handle, WM_MY_DATA_MSG, 0, LPARAM(@CommunicationMsgRecord));
end;
...
type
TMainForm = class(TForm)
private
procedure WMMyDataMsg( var Msg : TMessage ); message WM_MY_DATA_MSG;
...
end;
procedure TMainForm.WMMyDataMsg(var Msg: TMessage);
var
CommunicationMsgRecord : PCommunicationMsgRecord;
begin
try
CommunicationMsgRecord := PCommunicationMsgRecord(Msg.LParam);
case CommunicationMsgRecord.UpdateType of
0: MainForm.MemoProcess.Lines.Add(CommunicationMsgRecord.MessageStr);
1: MainForm.StatusBar.Panels[0].Text := CommunicationMsgRecord.MessageStr;
//....
end;
except
...
end;
end;
Second, using MainForm.Handle the way you are is not thread-safe. The VCL can (and sometimes does) recreate its HWNDs dynamically at runtime. If you happen to read a Handle property in a worker thread at the same time that the VCL is re-creating that property's HWND, really bad things can happen. You should use a separate HWND that is guaranteed to be persistent, such as TApplication.Handle (use TApplication.HookMainWindow() to receive its messages), or better the result of AllocateHWnd().
Now, with that said, if you are sending a lot of messages to the main thread, you are probably filling up the main thread's message queue. The queue can hold only so many messages at a time (IIRC, the limit is 10000), but the code you have shown is not performing any error checking on the SendMessage() call, eg:.
procedure TExecution.SetMainFormMemoProcess(const str: string);
var
...
ErrCode: DWORD;
begin
...
if SendMessage(...) = 0 then
begin
ErrCode := GetLastError();
if ErrCode = ERROR_NOT_ENOUGH_QUOTA then
// the message queue is full ...
end;
end;
Also, note that SendMessage() is synchronous, it does not return until the message handler processes the message, which means your worker threads will synchronize against each other, slowing down their processing since one thread will have to wait on another thread if they try to send their data at the same time. To avoid that, use PostMessage() instead (and dynamically allocate the data being posted) so that your threads can run at their full speed, eg:
procedure TExecution.SetMainFormMemoProcess(const str: string);
var
CommunicationMsgRecord: PCommunicationMsgRecord;
begin
New(CommunicationMsgRecord);
CommunicationMsgRecord.AnalysisID := Self.ExecutionID;
CommunicationMsgRecord.UpdateType := 0;
CommunicationMsgRecord.MessageStr := StrLeft(str,255);
CommunicationMsgRecord.prbProgress := 0;
CommunicationMsgRecord.valX := 0;
CommunicationMsgRecord.valY := 0;
if not PostMessage(MainForm.Handle, WM_MY_DATA_MSG, 0, LPARAM(CommunicationMsgRecord)) then
begin
Dispose(CommunicationMsgRecord);
...
end;
end;
...
procedure TMainForm.WMMyDataMsg(var Msg: TMessage);
var
CommunicationMsgRecord : PCommunicationMsgRecord;
begin
try
CommunicationMsgRecord := PCommunicationMsgRecord(Msg.LParam);
try
...
finally
Dispose(CommunicationMsgRecord);
end;
except
...
end;
end;
But, be careful, because that is likely to fill up the main thread's message queue even faster, so instead you should consider storing your data results elsewhere in thread-safe memory, and then have the main thread display the latest results at regular intervals (say, in a timer) rather than on every individual data update.
Many thanks for the very detailed response. I applied all your suggestions successfully, and things seem to be working fine. I only have a couple of final doubts:
When using PostMessage, with ‘dynamically allocate the data being posted’ (as you suggested), you mean to allocate the memory for the record in the background thread and free it in the main thread after the data have been read, right?
My initial code worked when compiled as a 64-bit app, it did not fail even if the Integer type-cast was wrong. Could this is because the integer has the same size in 32-bit and 64-bit?
In order to access the Application handle from the background threads I had to declare in the uses vcl.forms. This is not a problem, right?
If the 64 bit address that needs to be accessed happens to have the top 32 bit all zeros then bad code that zeros out those bits by using a 32 bit intermediate value won't crash. Soon as those bits are not zeros you get crashes / memory corruption etc.
@SteliosAntoniou: Integer is always a 32-bit integer, both in a 32-bit app and a 64-bit app. So in a 32-bit app, a pointer will always fit in an Integer, but in a 64-bit app, a pointer will in general NOT fit in an Integer. But it may accidentally do that. For example, if the pointer value is $00000000 003D1ABB, then truncating it to an Integer, you get $003D1ABB. Interpreting this as a pointer, you get $00000000 003D1ABB back and everything is fine. However, if the pointer happens to be $03CDBA38 113D1ABB then you get $113D1ABB as an Integer and interpreting this back...
...as a pointer, you get $00000000 113D1ABB which is a completely different part of your computer's memory. So reading or writing from this address (incorrectly believing it to be the original one) will cause bugs and crashes or random misbehaviour a week later. Now, it so happened that most pointers even in 64-bit apps used to start with a lot of zeros until ASLR was implemented, so a few years ago, your app often worked "on most systems most of the time" without any visible issues. (But if you had been writing software for pacemakers, you would have killed a patient or two.) Now...
...with ASLR (like in Delphi 11.3), you are much more likely to see truncated pointers and memory corruption and crashes, maybe almost every time you run the program.
@SteliosAntoniou 1) Yes, as I showed in my example. 2) What Andrea said. 3) If you access Application directly, then you need Vcl.Forms, yes. But your thread doesn't need to access Application directly. The main thread could pass Application.Handle (or MainForm.Handle, or the AllocateHwnd() result) as an input parameter to the worker thread's constructor and store it in a member of your thread class. You just need the HWND, not the whole Application object.
| common-pile/stackexchange_filtered |
Generate one cubemap PNG from six individual PNGs
I hope this is the right community to ask. With which free tools could I create a cubemap PNG from six individual PNGs, each being the texture of a cube's side?
The cubemap would have to have a resolution of 512x512 pixels (= a square) so that I can load it into Blender and other software. However, after searching for hours for a tool (preferably for Linux), I can't even find a single one!
_(Note: I'm not looking forward to generate files with different formats than PNG or JPG. Also, I've created that cubemap above with GIMP, but doing so is really exhausting since I have to place all the faces in their right positions).
imagemagic, imagemagic and imagemagic
:) Thanks, but I've also checked for that one. I didn't find any information on what command to use. Maybe you can help me?
The bottom texture is wrong, it should be only brown.
This task is simply done using ImageMagick montage function.
Assuming that you have 6 tiles (map_tile01.png, map_tile02.png, ..., map_tile06.png) and an empty image of the same size of the tiles (empty_tile.png):
You can use the following command:
montage.exe empty_tile.png map_tile01.png empty_tile.png map_tile02.png map_tile03.png map_tile04.png empty_tile.png map_tile05.png empty_tile.png empty_tile.png map_tile06.png empty_tile.png -tile 3x4 -geometry +0+0 -background none cubemap.png
Obtaining the final image:
The parameters of montage are simple:
The list of all the the tiles, in the sequential order to be used (empty_tile.png map_tile01.png empty_tile.png ... empty_tile.png)
How the tiles should be arranged (-tile 3x4)
Spacing between the tiles (-geometry +0+0)
Color of the background (-background none for the transparency)
Name of the final image (cubemap.png)
Please note that also the picture with the example of the tiles was produced using ImageMagick:
montage.exe -label '%f' map_tile01.png map_tile02.png map_tile04.png empty_tile.png -tile x1 -shadow -geometry +4+4 -background none sample_tiles.png
If you have the individual PNGs already created, you could use Inkscape (free, Open Source, works on Linux, Windows and Mac). It has some nice snapping and alignment features which would make placing the PNGs very easy.
You could create it using linked images and clones in Inkscape, to make a kind of template. Then all you'd need to do is change the links to the images to create a new design.
The final stage would be to export the image as PNG. In the export dialog you can set a specific size in pixels.
| common-pile/stackexchange_filtered |
MacVim mode() does not return 'c' for Command mode when pressing ':'
mode() won't return anything when I go into Command mode. I use this for StatusLine info:
set statusline+=%{mode()} as a test to see what mode() returns.
pressing c or C and my StatusLine stays as NORMAL. Is this a bug or am I doing something wrong? The other modes seem to work normally.
Below is the code:
set statusline+=\ %{g:mode_map[mode()]}
let g:mode_map = {
\ 'c' : ' COMMAND ',
\ 'i' : ' INSERT ',
\ 'ic' : ' INSERT ',
\ 'ix' : ' INSERT ',
\ 'n' : ' NORMAL ',
\ 'multi' : ' MULTI ',
\ 'ni' : ' NORMAL ',
\ 'no' : ' NORMAL ',
\ 'R' : ' REPLACE ',
\ 'r' : ' Replace ',
\ 'Rv' : ' REPLACE ',
\ 's' : ' SELECT ',
\ 'S' : ' SELECT ',
\ '' : ' SELECT ',
\ 't' : ' TERMINAL ',
\ 'v' : ' VISUAL ',
\ 'V' : ' VISUAL ',
\ '^V' : ' VISUAL ',
}
fwiw that works fine on my setup ubuntu + neovim 0.5/vim 8.2
I think it is merely that vim does not redraw when pressing :. You can see this with cnoremap <c-l> <c-r>=execute('redraw!')<cr>
Welcome to [vi.se]!
The stuff is known to work in Neovim, but not in Vim, because Vim is too lazy when updating screen, as @Mass correctly noted in the comments.
Personally, I just don't pay attention to this, and keep using my status line plugin without any worries.
But if you are so eager to fix it, you need to force status line redrawing, e.g.:
augroup test | au!
autocmd CmdlineEnter : redrawstatus
augroup end
I did this soon after getting your email and it worked like a charm. THX
FIXED!
This did it for me;
" add this so COMMAND will show when changing to command mode.
" leave the bang '!' off if updates for other windows is not required
augroup my_statusline | autocmd!
autocmd CmdlineEnter * redrawstatus!
augroup END
| common-pile/stackexchange_filtered |
What are all the argument prefixes?
I just received the following warning from my syntax checker:
'&' interpreted as argument prefix
The warning came in response to something like array.all? &:blank? where parenthesis would have been nice.
This got me thinking, what other argument prefixes are there? Searching on Google yields mostly results for this particular error, but I'd like a list of the argument prefixes and what they all do.
The argument prefixes have changed slightly since the duplicate question was asked. There is now a double-asterick for hash/keyword arguments (e.g. def a(**kwargs)), asterick prefixes work in assignments (e.g. a, *b = 1, 2, 3, 4, 5)
| common-pile/stackexchange_filtered |
Convert a CanvasRenderingContext variable for a javascript API
I have a javascript API that takes a canvas context as an argument
The following
var context2dJs = new js.JsObject.fromBrowserObject(canvas.getContext('2d'));
throws Exception: Uncaught Error: object must be an Node, ArrayBuffer, Blob, ImageData, or IDBKeyRange
but the following works
var context2dJs = new js.JsObject.fromBrowserObject(canvas).callMethod('getContext', ['2d']);
However, designing a wrapper around this API, I'd like the dart API to be similar and have a CanvasRenderingContext parameter. How can I convert such dart parameter to its javascript equivalent?
I don't think it's possible to get directly the JsObject corresponding to a CanvasRenderingContext. Please file an issue at http://dartbug.com
| common-pile/stackexchange_filtered |
Integral with linear function, Normal PDF, Normal CDF
I am trying to calculate the following integral:
$$\int_a^\infty x \Phi(cx+d) \phi\left(\frac{x-\mu}{\sigma}\right) dx,$$
where $\Phi$, $\phi$ denote the CDF and PDF of the standard Normal $N(0,1)$.
I found this table of integrals but it includes only the indefinite integral:
https://www.tandfonline.com/doi/pdf/10.1080/03610918008812164?casa_token=0E6SYYGFkkUAAAAA:cd6Lp-PTXsVRR20JaMQcNV8twies8FQAV0sO0DgOcAMD-L8aKBjxwpbqjClYlcFdIIxNUTCrnySg
Can you please help me? Thanks!
You can try just doing an integration by parts to remove the x. The indefinite integral is more manageable because when you do integration by parts, the boundary term disappears. Are you looking for any particular bound?
Thanks! How do we find integrals of the form $\int_a^\infty x \phi(cx+d) \phi(\frac{x-\mu}{\sigma}) dx$ though? Is there a closed form solution?
@Margot. --- the integral in your comment, product of two $\phi$'s, has a closed form in terms of error functions ("complete the square"); but the integral in your question has the product of $\phi$ and $\Phi$, so that does not help.
After integrating by parts, I think this is what we find, right? Do you have a link for the internal in my comment? Thanks!
This is close but I don't know whether this can help https://stats.stackexchange.com/questions/498851/what-is-int-c-infty-phiabx-phi-x-dx-for-c-in-mathbbr/498875#498875
I think you can derive the answer from https://en.wikipedia.org/wiki/List_of_integrals_of_Gaussian_functions
The indefinite integral $\int x \Phi(\alpha x + \beta) \phi\left(x\right) \mathrm{d}x$ is given in Wikipedia. Let's denote it by $I(\alpha,\beta,x)$.
The change of variables $y=\frac{x-\mu}{\sigma}$ in $\int_a^\infty x \Phi(cx+d) \phi\left(\frac{x-\mu}{\sigma}\right) \mathrm{d}x$ gives
$$\sigma\int_{\frac{a-\mu}{\sigma}}^\infty (\mu + \sigma y) \Phi(c\sigma y +c\mu + d) \phi(y) \mathrm{d}y \\ = \sigma\mu\int_{\frac{a-\mu}{\sigma}}^\infty\Phi(c\sigma y +c\mu + d)\phi(y)\mathrm{d}y + \sigma^2\int_{\frac{a-\mu}{\sigma}}^\infty y\Phi(c\sigma y +c\mu + d)\phi(y)\mathrm{d}y.$$
The second integral is ${\bigl[I(c\sigma,c\mu+d,x)\bigr]}_{\frac{a-\mu}{\sigma}}^\infty$. The first integral can be found here.
Edit
I checked with R and it is correct.
I <- function(a, b, x) {
t <- sqrt(1+b^2)
b/t * dnorm(a/t) * pnorm(x*t + a*b/t) - dnorm(x) * pnorm(a + b*x)
}
J <- function(a, b, w) {
t <- sqrt(1+b^2)
rho <- -b/t
library(mvtnorm)
pmvnorm(upper = c(a/t, w), sigma = cbind(c(1, rho), c(rho, 1)))
}
K <- function(a, b, w) {
J(a, b, Inf) - J(a, b, w)
}
a <- 1
mu <- 1; sigma <- 1; c <- 2; d <- -1
mu*sigma * K(c*mu+d, c*sigma, (a-mu)/sigma) +
sigma^2*(I(c*mu+d, c*sigma, Inf) - I(c*mu+d, c*sigma, (a-mu)/sigma))
# 0.8796307
f <- function(x) {
x * pnorm(c*x+d) * dnorm((x-mu)/sigma)
}
integrate(f, lower = a, upper = Inf)
# 0.8796307 with absolute error < 1.7e-08
Edit
So if I didn't do a mistake, the final result is
$$
\sigma \left(\mu\Phi\bigl(\frac{\alpha}{t}\bigr)
- B_{\frac{-\beta}{t}}\Bigl(\frac{\alpha}{t}, v\Bigr)
+ \sigma \Bigl(\frac{\beta}{t} \phi\bigl(\frac{\alpha}{t} \bigr)
\Bigl(1 - \Phi\bigl(tv+\frac{\alpha\beta}{t}\bigr)\Bigr) -
\phi(v)\Phi(\alpha + \beta v)\Bigr)\right)
$$
where $t = \sqrt{1+c^2\sigma^2}$, $\alpha = c\mu+d$, $\beta = c\sigma$, $v = \frac{a-\mu}{\sigma}$, and $B_\rho$ is the bivariate normal function.
To be checked...
the definite integral has a closed-form expression for $\mu=0$,
\begin{align}
& \int_a^\infty x \Phi(cx+d) \phi\left(\frac{x}{\sigma}\right) dx \\[8pt]
= {} & \frac{c \sigma^3 e^{-\frac{d^2}{2 c^2 \sigma^2+2}}}{2 \sqrt{2 \pi } \sqrt{c^2 \sigma^2+1}}\left[1-\operatorname{erf}\left(\frac{c \sigma^2 (c a+d)+a}{\sigma \sqrt{2 c^2 \sigma^2+2}}\right)\right] \\[8pt]
& -\sigma^2(2 \sqrt{2 \pi })^{-1}e^{-\frac{a^2}{2 \sigma^2}} \left[\operatorname{erfc}\left(\frac{c a+d}{\sqrt{2}}\right)-2\right]
\end{align}
Thanks ! I know the expression from the table I shared. I am interested in the definite integral version, though.
Thanks! Can you show the steps?
as indicated in the comment above, integrate by parts to remove the $x$, then follow the steps of https://mathoverflow.net/a/101753/11260
Why does $\mu \neq 0$ cause issues?
the integral $\int \phi(x-\mu)\Phi(x),dx$ does not have a closed-form expression when $\mu\neq 0$
I found this: https://mathoverflow.net/questions/130958/computing-an-integral-involving-standard-normal-pdf-and-cdf Why can't we apply the result in the link using a linear transformation $y = x-\mu$?
I meant change of variables^
@Margot Yes you can do a COV, see the link in my comment to your question.
| common-pile/stackexchange_filtered |
How to download a file from URL using Dockerfile
I'm writing a docker file to install a certain library. The first step it does is download the library from a URL. I'm not sure if it's possible in docker.
I need to install the library on RedHat System.
http://service.sap.com/download is the URL I need to download the library. How can I write Dockerfile for the same?
A Dockerfile is (largely) just a collection of shell commands. How would you do this without a Dockerfile?
You can simply use "RUN wget http://service.sap.com/download" to download the library
This is also something Docker can do on its own if you ADD the URL.
Thanks so much guys for your reply and sharing information.
Using wget has one benefit: ADD downloads file each time you making docker build. If it is a big file(s) - built can take a long time (and bandwith) every time. RUN wget will download only once and use docker cache afterwards.
I recommend using ADD, as @David Maze commented and as @nicobo commented on the first answer.
I think that this is the best answer for many of us, since it does not force download of wget or similar into the Docker image. Here is the example I just used for CMake:
ADD https://github.com/Kitware/CMake/releases/download/v3.27.6/cmake-3.27.6-linux-x86_64.sh /tmp/cmake.sh
RUN mkdir /opt/cmake && bash /tmp/cmake.sh --prefix=/opt/cmake --skip-license && rm /tmp/cmake.sh
You run a RUN command depending on the programs available in your system. If you have wget on your system, you just put the command in your Dockerfile:
RUN wget http://your.destination/file
If you need that file to move to a location in your image, you keep using the RUN command with mv, if the file is outside your image, you can use the COPY command.
To resume, downloading your file from the system
[CLI] wget http://your.destination/file
[DOCKERFILE] COPY file .
Downloading a file with docker
[DOCKERFILE] RUN wget http://your.destination/file
[DOCKERFILE] RUN mv file my/destination/folder
Thanks @savageGoat for your answer.
See David Maze comment above : ADD is a Dockerfile instruction to do exactly that ; although RUN wget is possible, it needs first to have wget installed inside the image.
https://docs.docker.com/engine/reference/builder/#add
| common-pile/stackexchange_filtered |
Arduino, potentiometer goes crazy
I am executing a block of code every certain period of time. The time is indicated by the value of the potentiometer. Everything works well. But in some parts of the potentiometer it is as if the value were 0 or a very low number that makes the code block run continuously.
Here the piece of code:
const int p = A0;
unsigned long t = 0;
void start(){
Serial.begin(9600);
}
void loop(){
if(millis() > t+(analogRead(p)*100)){
t = millis();
Serial.println("Something...");
}
}
What "parts" of the potentiometer? At either of the far ends of it? Somewhere in the middle? Seemingly random?
Just random. Sometimes at the beginning, at the end, middle. But where not, all works well.
To add to the above question. Is the potentiometer some random cheap chinese knockoff? Or an actually QA tested one?
Just to add to this, have you tried dimming a LED using the potentiometer?
It works well. When I print the value everything is fine
When you print the value, are you saying the error does not occur? The code block does not "run continuously"?
Also make sure that you are COPYING and PASTING the code, exactly as you are running on your board. Attempting to transcribe code from your IDE to the stack overflow question can cause issues for us trying to troubleshoot.
Your start() function is wrong, it should be setup() and should include pin mode declaration.
void setup(){
Serial.begin(9600);
pinMode(p, INPUT);
}
| common-pile/stackexchange_filtered |
Building QGIS 1.8.0?
I am very new to QGIS (and the entire Linux thing). I am trying to build QGIS 1.8 on ubuntu 12.04LTS. I specifically need to use the 1.8 version of QGIS.
When running the "make" command, I see the following:
e@pe-ThinkPad-Edge-E320:~/dev/cpp/Quantum-GIS1.8/build-master$ make
-- Quantum GIS version: 1.8.0 Lisboa (10800)
-- Found GRASS: /usr/lib/grass64 (6.4.1)
-- Touch support disabled
-- Found Proj: /usr/lib/libproj.so
-- Found GEOS: /usr/lib/libgeos_c.so
-- Found GDAL: /usr/lib/libgdal1.7.0.so (1.7.3)
-- Found Expat: /usr/lib/i386-linux-gnu/libexpat.so
-- Found Spatialindex: /usr/lib/libspatialindex.so
-- Found Qwt: /usr/local/qwt-5.2.3/lib/libqwt.so (5.2.3)
-- Found Sqlite3: /usr/lib/i386-linux-gnu/libsqlite3.so
-- Found PostgreSQL: /usr/lib/libpq.so
-- Found SpatiaLite: /usr/lib/libspatialite.so
-- Pedantic compiler settings enabled
-- Found Python executable: /usr/local/bin/python
-- Found Python version: 2.7.2
-- Found Python library: /usr/local/lib/libpython2.7.so
-- Found SIP version: 4.15.5
-- Found PyQt4 version: 4.9.1
-- Found GSL: -L/usr/lib -lgsl -lgslcblas -lm
-- Ctest Binary Directory set to: /home/pe/dev/cpp/Quantum-GIS1.8/build-master/output/bin
-- Configuring done
-- Generating done
-- Build files have been written to: /home/pe/dev/cpp/Quantum-GIS1.8/build-master
[ 89%] Built target version
Scanning dependencies of target qgis_core
[ 89%] Building CXX object src/core/CMakeFiles/qgis_core.dir/qgis.cpp.o
Linking CXX shared library ../../output/lib/libqgis_core.so
[ 89%] Built target qgis_core
Linking CXX shared library ../../output/lib/libqgis_analysis.so
[ 89%] Built target qgis_analysis
Linking CXX shared library ../../../output/lib/libqgis_networkanalysis.so
[ 89%] Built target qgis_networkanalysis
[ 89%] Built target ui
Linking CXX shared library ../../output/lib/libqgis_gui.so
[ 89%] Built target qgis_gui
Linking CXX shared module ../../../output/lib/qgis/plugins/libmemoryprovider.so
[ 89%] Built target memoryprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libogrprovider.so
[ 89%] Built target ogrprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libwmsprovider.so
[ 89%] Built target wmsprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libdelimitedtextprovider.so
[ 89%] Built target delimitedtextprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libosmprovider.so
[ 89%] Built target osmprovider
Linking CXX shared library ../../../../output/lib/qgis/plugins/libqgissqlanyconnection.so
[ 89%] Built target qgissqlanyconnection
Linking CXX shared module ../../../output/lib/qgis/plugins/libsqlanywhereprovider.so
[ 89%] Built target sqlanywhereprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libgdalprovider.so
[ 89%] Built target gdalprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libmssqlprovider.so
[ 89%] Built target mssqlprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libpostgresprovider.so
[ 89%] Built target postgresprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libspatialiteprovider.so
[ 89%] Built target spatialiteprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libgpxprovider.so
[ 89%] Built target gpxprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libwfsprovider.so
[ 89%] Built target wfsprovider
Linking CXX shared library ../../../output/lib/qgis/plugins/libqgisgrass.so
[ 89%] Built target qgisgrass
Linking CXX shared module ../../../output/lib/qgis/plugins/libgrassprovider.so
[ 89%] Built target grassprovider
Linking CXX shared module ../../../output/lib/qgis/plugins/libgrassrasterprovider.so
[ 89%] Built target grassrasterprovider
[ 89%] Built target qgis.d.rast
[ 89%] Built target qgis.g.info
Linking CXX executable ../../output/bin/crssync
[ 89%] Built target crssync
Scanning dependencies of target qgis
[ 89%] Building CXX object src/app/CMakeFiles/qgis.dir/main.cpp.o
Linking CXX executable ../../output/bin/qgis
[ 89%] Built target qgis
Linking CXX executable ../../output/lib/qgis/qgis_help
[ 89%] Built target qgis_help
Linking CXX executable ../../output/bin/qbrowser
[ 89%] Built target qbrowser
Linking CXX shared module ../../../output/lib/qgis/plugins/libdelimitedtextplugin.so
[ 89%] Built target delimitedtextplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libdiagramoverlay.so
[ 89%] Built target diagramoverlay
Linking CXX shared module ../../../output/lib/qgis/plugins/libinterpolationplugin.so
[ 89%] Built target interpolationplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/liboracleplugin.so
[ 89%] Built target oracleplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/librasterterrainplugin.so
[ 89%] Built target rasterterrainplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libcoordinatecaptureplugin.so
[ 89%] Built target coordinatecaptureplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libdxf2shpconverterplugin.so
[ 89%] Built target dxf2shpconverterplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libevis.so
[ 89%] Built target evis
Linking CXX shared module ../../../output/lib/qgis/plugins/libspatialqueryplugin.so
[ 89%] Built target spatialqueryplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libsqlanywhereplugin.so
[ 89%] Built target sqlanywhereplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libroadgraphplugin.so
[ 89%] Built target roadgraphplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libzonalstatisticsplugin.so
[ 89%] Built target zonalstatisticsplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libgeorefplugin.so
[ 89%] Built target georefplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libofflineeditingplugin.so
[ 89%] Built target offlineeditingplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libspitplugin.so
[ 89%] Built target spitplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libgrassplugin.so
[ 89%] Built target grassplugin
[ 89%] Built target qgis.g.browser
Linking CXX shared module ../../../output/lib/qgis/plugins/libgpsimporterplugin.so
[ 89%] Built target gpsimporterplugin
Linking CXX shared module ../../../output/lib/qgis/plugins/libheatmapplugin.so
[ 89%] Built target heatmapplugin
Linking CXX shared library ../../output/lib/libqgispython.so
[ 89%] Built target qgispython
[ 89%] Built target t2tdoc
[ 89%] Built target translations
[ 89%] Built target compile_python_files
Linking CXX shared library ../output/python/qgis/analysis.so
[ 89%] Built target python_module_qgis_analysis
Linking CXX shared library ../output/python/qgis/core.so
[ 89%] Built target python_module_qgis_core
[ 89%] Building CXX object python/CMakeFiles/python_module_qgis_gui.dir/gui/sipguipart2.cpp.o
/home/pe/dev/cpp/Quantum-GIS1.8/python/../src/gui/qgsmapcanvas.h: In member function ‘virtual void sipQgsMapCanvas::connectNotify(const char*)’:
/home/pe/dev/cpp/Quantum-GIS1.8/python/../src/gui/qgsmapcanvas.h:461:10: error: ‘virtual void QgsMapCanvas::connectNotify(const char*)’ is private
/home/pe/dev/cpp/Quantum-GIS1.8/build-master/python/gui/sipguipart2.cpp:9597:39: error: within this context
make[2]: *** [python/CMakeFiles/python_module_qgis_gui.dir/gui/sipguipart2.cpp.o] Error 1
make[1]: *** [python/CMakeFiles/python_module_qgis_gui.dir/all] Error 2
make: *** [all] Error 2
So there seems to be a problem with the QgsMapCanvas, but I really don't know how to solve this. Please see the versions of SIP, PyQt4, Python etc. at the beginning of the quote segment.
These are the steps I followed to install Qgis 1.8 from source in my $HOME/qgis18 directory:
Prerequisites:
ccmake installed from synamptic;
gdal,proj4,geos,etc. installed from Ubuntugis repository;
Procedure:
Download datasource from here
$mkdir -p ${HOME}/qgis18
$cd qgis18
$mkdir build
$cd build
$ccmake .. (configure all paths and dependences)
$make
$make install
After that you can try to run QGIS:
$HOME/qgis18/bin/qgis
Qgis has really made improvements in v2.2. I suggest using this version instead if you are interested in productivity.
| common-pile/stackexchange_filtered |
Quadratic equation with parameters
If $a$, $b$, $c$ are real numbers such that $2a + 3b + 6c = 0$, prove that $ax^2+bx +c=0$ has a solution in the interval $[0, 1]$.
This should use high school maths or a little bit more then that.
Ok i just don't understand why you chose $f(1/2)$.
If you want to respond the answer, do comment under the answer, this ensure the one who answered being informed. No one can review all questions answered all the time.
\begin{align*}
0 &= 2a+3b+6c \\
f(x) &= ax^2+bx+c \\
f(0) &= c \\
f\left( \frac{1}{2} \right) &= \frac{a}{4}+\frac{b}{2}+c \\
&= -\frac{a}{12} \\
f(1) &= a+b+c \\
&= \frac{a}{3}-c
\end{align*}
Case I: $ac \ge 0$
$$f(0) f\left( \frac{1}{2} \right) = -\frac{ac}{12} \le 0$$
$\exists x\in \left[ 0, \dfrac{1}{2} \right]$ such that $f(x)=0$.
Case II: $ac \le 0$
$$f\left( \frac{1}{2} \right) f(1)= -\frac{a^2}{36}+\frac{ac}{12} \le 0$$
$\exists x\in \left[ \dfrac{1}{2}, 1 \right]$ such that $f(x)=0$.
Combining, $\exists x \in [0,1]$ such that $f(x)=0$
N.B.
When $0 <3ac <a^2$, there're two such roots, namely $\alpha \in \left( 0, \frac{1}{2} \right)$ and $\beta \in \left( \frac{1}{2}, 1 \right)$.
Updates
The value of $x=\dfrac{1}{2}$ can be inspired by plotting a family of curves by varying either $b$ or $c$. You can see a fixed point at $x=\dfrac{1}{2}$ by varying $c$ below.
Alternatively, $(x,y)=\left(\dfrac{1}{2},-\dfrac{a}{12} \right)$ is a solution of
$$ax^2-\left( \frac{2a}{3} + 2c \right)x+c-y=
\frac{\partial}{\partial c}
\left[
ax^2-\left( \frac{2a}{3} + 2c \right)x+c-y
\right]=0$$
Nice Solution Ng Chung Tak, But i did not understand your alternate solution , specially $\displaystyle \frac{\partial}{\partial c}
\left[
ax^2-\left( \frac{2a}{3} + 2c \right)x+c-y
\right]=0$
That's from theory of envolope. If it's beyond your level, just ignore it.
| common-pile/stackexchange_filtered |
ubuntu 18.10: pdf thumbnails does'nt work
Although evince-thumbnailer is already installed and everything seems to be fine, no pdf thumbnails have appeared in Nautilus.
I tried two fresh installs in two different machines and one more in a virtual box machine and the funny thing is that if you boot in a live cd mode then the thumbnailer seems to work fine.
Can confirm that too!
Another workaround is to purge evince with
sudo apt purge evince
and reinstall it with snap
snap install evince
After deleting .cache/thumbnails and a reboot, .pdf thumbnails immediately work.
I just found a workaround here on Launchpad.
In brief:
Edit the file /etc/apparmor.d/local/usr.bin.evince (e.g., sudo nano /etc/apparmor.d/local/usr.bin.evince)
Add the line owner /tmp/{,.}gnome_desktop_thumbnail.* w, at the end of usr.bin.evince (in my case it was empty), and save.
Run the command sudo apparmor_parser -r /etc/apparmor.d/usr.bin.evince.
That's it! It works immediately...
Thank you for the issue,
Actually, for me it works with "owner /tmp/{,.}gnome-desktop-thumbnailer.* w," According to the link you have shared.
You have writen "owner /tmp/{,.}gnome_desktop_thumbnail.* w," but it didn't works with this code. The différencies are "_" replaced by "-" and "thumbnail" replaced by "thumbnailer"
| common-pile/stackexchange_filtered |
Joomla 2.5 module permissions
I simply want to make a module visible dependent on whether a user belongs to a custom set of groups - including NOT visible if (s)he belongs to a particular group(s). For example, adverts show for public and registered but not a custom "premium" group. A shoutbox should appear for registered and premium but not "not logged in". Thus, the "guest" and "special" groups are pretty useless as far as I can tell. Am I missing something really simple?
If I have to use a 3rd party component/module to achieve this then a free or cheap one would be most beneficial.
Thanks.
One way to achieve this is to edit and create new access levels. To cover up the examples you gave in the question, the following could work:
You need to get the guests out of the root parent group called Public. You can do this by the following three steps:
Using the User Manager, create a new group called "Guest" with Public as parent.
Open up the User Manager Options.
Change Guest User Group to your new group Guest.
The guests on your site will from now on be put into the Guest group. Now you could create a access level for the advert. So create a new access level, name it something like "Non premium users" and add Guest and Registered. Now apply this access level to the module and it should work. Note that the premium group cannot have Registered as a parent.
Next is the access level for the shoutbox. I see two options for this access level. One of them is to create a new access level and add Registered and Premium to it. A simpler approach though is to add the Premium group to the already existing access level called Registered.
Helpful ACL Links:
Allowing Guest-Only Access to Menu Items and Modules
Joomla ACL: Access Levels
| common-pile/stackexchange_filtered |
The CNN model keeps overfitting on our EEG dataset. We're getting 97% accuracy on training but only 72% on validation.
That's classic overfitting. Are you using both spatial and temporal features or just one approach?
Right now I'm feeding all 64 channels directly into a single CNN. Maybe that's too much information at once?
Exactly. Try splitting it into two parallel networks - one for spatial relationships between electrodes, another | sci-datasets/scilogues |
How can I pass in a string and use that as a variable name?
I have a variable such as:
var startX = 20
var startY = 30
I want to call a function such as:
onClick="myFunction('startX')"
or
onClick="myFunction('startY')"
myFunction(passedVar){
}
So passedVar = 'startX' or 'startY' and I then need to reference the variable of the same name and get it's value (20 or 30)
In Powershell I'd do a:
get-variable($passedVar) -value
which would see what's in passedVar and then look for a variable with that name and give me the value.
Does that make sense?
Thanks!
Why wouldn't you just use myFunction('startX', startX) ?
Where is the variable defined? Global? Inside of the function? In an enclosing scope of the function?
well, I guess that'd just be too easy.
@Thilo I think I found that one of the variables was originally set in a function. I moved it out and I think I have it working better now. Thanks for the tip.
Global variables are just properties of the window object. You could try
var val = window[passedVar];
You simply have to omit the single quotes; it is not required.
onClick="myFunction(startX)"
or
onClick="myFunction(startY)"
| common-pile/stackexchange_filtered |
How do I stop cmd from appearing when i run exe file (python 3, gui)
So recently I made a script, and I also finished gui and managed to merge those two together. Now i wish when I start the exe file that cmd doesn't appear but instead only GUI? Any idea on how to manage this? So far my searching didn't yield any satisfying results. Some more info is: Python 3.5, using pyinstaller to convert to exe, Tkinter Gui, pycharm 5.0.1. Thanks!
I'm using pyinstaller, and I don't think py2exe will work with my python 3.5, but I'm new to this so maybe I'm wrong?
Sorry, I think I picked the wrong duplicate target. Maybe this or this will help you.
worked with adding --noconsole... python pyinstaller.py --noconsole -F myscript.py // tyvm :)!
Since your question mentions .exe executables, I'wll assume you work in the Windows environment. Try using a .pywextension instead of a .py extension for the python program.
I think I've tried that already and it was unsuccessful. I'll try again a bit later and will get back with result
| common-pile/stackexchange_filtered |
Print line ArrayList
When I try to use print line to see my array list, the way it's getting printed is not how I want it to be. What do I need to change to receive just the name?
This is how I am adding a new contact:
public class ContactGroup
{
ArrayList<Contact> contactList= new ArrayList<Contact>();
Public void addContact(String aCName)
{
Contact contact= new Contact(aCName);
contactList.add(contact);
}
public class Contact
{
private String name;
public Contact(String aCName)
{
super();
this.name = aCName;
}
}
Add a toString() method to your class containing the ArrayList.
public static void main(String[] args) {
List<Contact> contactList= new ArrayList<Contact>();
// code to insert contact in list
for(Contact contact : contactList) {
System.out.println(contact.getName());
}
}
Did you try this to print name only? Another option is to override toString() method as:
public class Contact {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Contact(String name) {
this.name = name;
}
@Override
public String toString() {
return "Contact{" +
"name='" + name + '\'' +
'}';
}
}
And then use it as:
public static void main(String[] args) {
List<Contact> contactList= new ArrayList<Contact>();
// code to insert contact in list
for(Contact contact : contactList) {
System.out.println(contact);
}
}
Great! Thank you:) - The print name only part worked just fine
I was just wondering if it was at all possible to add an int to my array list. The list is already declared and populated, is there anyway to add a number to each string in the array list?
The list contains objects of class Contact and you cannot add int to it.
What if the class Contact already has an int set to 0 - is there anyway to change that int value after the list has been populated?
Yes you can. You need to iterate over the list and change int value for each of the Contact object. If you have any other doubt I recommend to ask a new question :)
Cant make a new question for awhile, the int is being declared in public class Contact and is being set in the method Contact. If u can help id appreciate it but thanks so much regardless!
You can override the toString() method in any object class
@Override
public String toString(){return "My Text to display";}
You need to implement toString() method inside your class containing the ArrayList. Please follow the best practices suggested in EffectiveJava while implementing the toString() method.
Override toString() method in your class Contact
public class Contact
{
private String name;
public Contact(String aCName)
{
super();
this.name = aCName;
}
@Override
public String toString()
{
return "contact name " + this.name; //say you want to print the name property
}
}
you should add a toString() implementation to Contact class
public class Contact{
private String Name;
public Contact(String name){
this.Name=name;
}
// add toString method here
@Override
public String toString(){
return "This is a Contact of :"+this.Name;
}
}
| common-pile/stackexchange_filtered |
WPF - Rotate Transform Transition
I am relativly new to WPF and I have a question concerning transitions in WPF:
How do I create and use them? My google search result are mostly about animations not transitions.
My goal is to create something like this:
Imagine I have a shape:
<Rectangle Width="100" Height="200" Name="shape_01" x:Key="shape_01" Fill="Green"/>
whoms rotation will be set during run-time to (yet) unknown values. Meaning, that I cannot use a Storyboard or Animation to create a transition.
I use the following code to set the rotation angle:
double angle = ....;
((shape_01.RenderTransform as TransformGroup)
.Children.First(_ => _ is RotateTransform) as RotateTransform)
.Angle = angle;
How can I transition the previous value to the currently set value?
WPF uses animations for "transitions".
@Clemens: I am sorry, but could you elaborate it a bit further, Sir?
I am not (yet) very familiar of the WPF-animation/transition/storyboard concept...
You would use a DoubleAnimation to "transition" a property from one value to another. If you do not set the animation's From property, the transition starts from the current property value.
double angle = ....;
var animation = new DoubleAnimation
{
To = angle,
Duration = TimeSpan.FromSeconds(1)
};
var transform = ((TransformGroup)shape_01.RenderTransform)
.Children.OfType<RotateTransform>().First();
transform.BeginAnimation(RotateTransform.AngleProperty, animation);
How would you do that in XAML?
| common-pile/stackexchange_filtered |
How to add some days in a Datetime attribute in c#?
I want to retrieve a list based on this LINQ query in C#,
var brief = (from i in _context.Detailed
orderby i.BriefSubmittedOn descending
select i).ToList();
This is the View:
@foreach (var item in Model.brief)
{
<tr>
<EMAIL_ADDRESS><EMAIL_ADDRESS><EMAIL_ADDRESS> </tr>
}
The query is working fine, but i don't want the list to remain in this view forever. Instead i want the items of this list should remain for 3 days only after its date of submission.
For instance, if an item is submitted on 5th May 2019, then it should appear in this list till 8th May 2019 but when the date changes to 9th May 2019, then it should disappear from the list.
Note: The submission date of items are stored in BriefSubmittedOn field in this example, which is of type Nullable DateTime?
You need to add where clause to your LINQ query, e.g.:
DateTime targetDate = DateTime.Now.AddDays(-3);
var brief = (from i in _context.Detailed
where i.BriefSubmittedOn > targetDate
orderby i.BriefSubmittedOn descending
select i).ToList();
You may use Today instead of Now to use strict timestamp at the edge 00:00:00. if you need 23:59:59 you can add AddTicks(-1)
| common-pile/stackexchange_filtered |
CTE over id, status, and date causing results to square
I have a table defined as
CREATE TABLE ItemDetail (
ItemNumber bigint not null,
SiteId int not null,
Status int not null,
ScanDate datetime not null,
)
What I am trying to do is get counts by site, by status, by day. I have a CTE as defined
;WITH statCTE AS (
SELECT
Count(ItemNumber) over(partition by SiteId, Status, DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate))) as ItemCount,
SiteId,
Status,
DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate)) AS ScanDate
FROM
ItemDetail
)
The problem is that when I then run
select * from statCTE where siteid = 119 and scandate = '3/3/2011'
I get
ItemCount SiteId Status ScanDate
2 119 0 2011-03-03 00:00:00.000
2 119 0 2011-03-03 00:00:00.000
6 119 5 2011-03-03 00:00:00.000
6 119 5 2011-03-03 00:00:00.000
6 119 5 2011-03-03 00:00:00.000
6 119 5 2011-03-03 00:00:00.000
6 119 5 2011-03-03 00:00:00.000
6 119 5 2011-03-03 00:00:00.000
The result set should be 2 rows, one with 2 for status 0 and one with 6 for status 6. So, my partition isn't working with transforming the date into just a date object and picking the results. I could just square root the ItemCount totals in my final query (a pivot), but that's more of a hack than fixing the actual problem.
Your CTE is still going to have one row for each row in ItemDetail. See Example B on this page.
You are misunderstaning the use of Window functions (or ranking functions). In Your case Count is NOT an aggregate. This use add the result of the function to EVERY row returned by the query. Normally the aggregate is processed BEFORE the select clause, however in this example it is processes ALONG select clause. So TSQL counts how many rows satisfy Your partition and output it along EVERY row returned by the query.
You have 2 partitions with respectable count of 2 and 6 (calculated by the window partition function) and then whole result set is appended with additional column.
If You want the 2 and 6 results YOu need to write the query using the group by clause
WITH statCTE AS (
SELECT
Count(ItemNumber)as ItemCount,
SiteId,
Status,
DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate)) AS ScanDate
FROM
ItemDetail
group by SiteId, Status, DATEADD(dd, 0, DATEDIFF(dd, 0, ScanDate))
)
| common-pile/stackexchange_filtered |
Eager loading returning ID instead of model
I have an issue with Eager Loading using the below code.
Issue is with the Status model
$ticket = Ticket::where('id', $id)->with(['customer', 'status', 'notes' => function($query) {
$query->orderBy('updated_at', 'desc');
}])->first();
If I do,
return response()->json($ticket);
I get the expected response, all OK
{"id":1,"customer_id":10001,"ztk_ticket_no":"ZTK0000001","status":{"id":1,"value":"Open","deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20"},"deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20","customer":{"id":1,"customer_id":10001,"title":"Test Company","deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20"},"notes":[{"id":1,"ticket_id":1,"note":"Lorem ipsum dolor sit amet, ","status":1,"deleted_at":null,"created_at":"2016-02-13 01:36:20","updated_at":"2016-02-13 01:36:20"}]}
But if I do
return response()->json($ticket->status);
I get the id of the status, not the Model
1
Status Model:
class Status extends Model
{
protected $table = 'statuses';
}
Ticket Model:
class Ticket extends Model
{
public function status() {
return $this->hasOne('App\Status', 'id', 'status');
}
}
Try: $ticket->status()->get();
Oh that works, thanks.
Any idea why I have to do it that way?
According to your relationship definition, it looks like your Ticket model has a field named status. If you have a field name on your model with the same name as one of your relationship methods, when you do $ticket->status, you are going to get the value of field, not the related object.
So, based on what I can see, it looks like your tickets.status field is a foreign key to the statuses table. If this is the case, then there are a few issues.
First, your status field should be renamed to status_id. This will help remove the ambiguity between the field name and the related object.
Second, since your Ticket model contains the foreign key, it is on the belongsTo side of the relationship. It may sound a little weird, but a Status can have many Tickets, but a Ticket belongs to a Status. So, you need to change your status() relationship from hasOne to belongsTo.
If you rename the status field to status_id, you can change your method to this:
public function status() {
return $this->belongsTo('App\Status');
}
With this, you access the id field with $ticket->status_id, and the related Status object with $ticket->status.
If you can't change your status field, then it would be a good idea to rename your status() relationship method, so your method should look something like this:
// relationship method renamed
public function relatedStatus() {
// second parameter required since foreign key does not conform to Laravel conventions
return $this->belongsTo('App\Status', 'status');
}
With this, you access the id field with $ticket->status, and the related status object with $ticket->relatedStatus.
Change your code to
$ticket->status()->get();
This would return the object.
$ticket->status;
This one will only return the raw id.
Is this because I have the column name the same as the model? status?
No, what you've called is just the model id by default. In order to get the model object as a collection, you call a get function on the relation.
How come it works if I call $ticket->customer, I get the Model then?
@JilsonThomas $ticket->status would only return the raw id if the Ticket model had a field named status, in addition to a relationship named status().
| common-pile/stackexchange_filtered |
Why isn't there a space in the middle of my pyramid?
So I am trying to solve https://cs50.harvard.edu/x/2021/psets/1/mario/more/ this problem set from cs50.
It's taken me way too long to get this far (5-6 hours WITH help from youtube).
#include <cs50.h>
#include <stdio.h>
int get_positive_int(void);
int main(void)
{
int n = get_positive_int();
// Run a below loop until i is greater than n
for(int i = 0; i < n; i++)
{
// Run if statement on the same row until j is greater than n*2 + i+1
for(int j=0; j < n*2 + i+1; j++)
{
// Create a blank space in exact center of the pyramid
if(j + i - n == 0 || j + i - n == 1)
printf(" ");
//If the value of n-1 is less than the combined value of j and i, or
//if the value of i and n minus j is less than or equal to zero print #
else if ( j + i > n - 1 || i + n - j <= 0)
printf("#");
else
//otherwise print " "
printf(" ");
}
printf("\n");
}
}
Why doesn't the below create a two " " in the center of my pyramid?
if(j + i - n == 0 || j + i - n == 1)
printf(" ");
And why when I choose a value of 1 for n does the program not print anything?
What is this specific type of thinking/math called? I am having difficulty grasping it and I am not sure how to find information online because I don't know what it is called.
My output is below.
When N = 8
#######
#########
###########
#############
###############
#################
###################
#####################
The output I want is.
When N = 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
When I input a value of 1 I get.
What I want when I input 1 is,
# #
I'd like to know what specifically I did wrong in order to fix the issue myself, rather than the direct answer if possible.
Show what the output is and what output you want instead
Have you stepped through with a debugger? Usually, when the internal state or output of a program behind to deviate from the expected is extremely revealing. If you can trace through the steps it's doing vs what you think you told it to do, you will figure out how to fix it.
The middle spaces are always at the same position regardless of the row, so the condition for writing them should depend on j and not on i.
Try if(j + i - n == 0 || j + i - n == 1) printf("%d", j + i - n); ... of course that will mess up your triangle, but maybe give you an idea what you need to change
@Multiplify - What you also did wrong in my opinion: All comments but the third are nothing more than transcriptions of the respective statement and as such have no added value.
You should perhaps have solved the problem in steps: 1. Print the correct number of leading spaces. 2. Print the left hand bricks. 3. Print the gap. 4. Print the right hand bricks. 4. Ready - no spaces to the right are required.
First of all observe that your two for loops both start from 0. Thus at the beginning both i and j are equal to 0. Therefore, since n is a positive integer, both your if and else if clauses are evaluated as false and only the final else gets executed, which is printf(" ");
Now look at your pyramid. Your "pyramid" fills a space with n rows and 2*n + 2 columns. The first loop for (i = 0; i < n; i++) is for the rows, and it's correct, since there are n rows. Your second for loop, however, is faulty. It should be for (int j=0; j < n*2 + 2; j++).
Now when we look at the the i-th row we see that (remembering rows start from 0 because we started counting i from 0), you want to print n-1-i spaces, followed by i+1 # characters followed by 2 spaces, followed by i+1 # characters and finally followed by n-1-i spaces. So the "spaces" are when j < n-1-i (remember j also starts from 0), when j == n and j == n+1 and when j > n+2+i
This can be written as follows using if-else:
if ( j < (n-1-i) || j == n || j == n+1 || j > n+2+i) printf(" ");
else printf("#");
So the final code will look like:
#include <cs50.h>
#include <stdio.h>
int get_positive_int(void);
int main(void)
{
int n = get_positive_int();
for(int i = 0; i < n; i++)
{
for(int j=0; j < n*2 + 2; j++)
{
if ( j < (n-1-i) || j == n || j == n+1 || j > n+2+i) printf(" ");
else printf("#");
}
printf("\n");
}
}
He said he has already spent 5-6 hours on this. I've pointed out the error in the for loop and explained how to approach constructing the if-else statement. It's not like I just gave him the solution and didn't explain anything.
Yes, I like your explanation (upvoted) and removed my impulsive comment, sorry.
I'm working my way through it right now and I appreciate your response as well as everybody else. What is this kind of problem called and where can I find more practice problems of a similar nature so I can understand it better?
@Multiplify you can construct your own. Try to make upside down triangles, right triangles, diamonds (grows until n-th row then shrinks), crosses, even christmas trees, ball-shapes etc. These are usually good exercises for getting comfortable with nested for loops.
| common-pile/stackexchange_filtered |
Text overlapping with too much text on hover
I have tried a few things but seem to be getting nowhere, I can move the text by changing the 'position' tag, but this seems to result in the text kinda vanishing into the boxes edge and being oddly spaced.. I am guessing I have coded this up that its fine on less text, but when adding too much, I get a overlap.. anyway I can shift things about a tad so they look nicely laid out?
Website; http://outside.hobhob.uk
Referring to the text which appears when you hover over the portfolio items in the grid. I need the title to stay at the top, but avoid the description underneath overlapping with the header.
Code snippet of the grid section;
<div class="portfolio-item item tile entry">
<a href="single.html">
<img src="content/portfolio_07.png" alt="">
<div class="magnifier">
<div class="buttons">
<h4>Melbourne Design Guide</h4>
<p>Creative mapping and Illustration for the cities annual design guide</p>
</div><!-- end buttons -->
</div><!-- end magnifier -->
</a>
</div><!-- end item -->
CSS I am looking at.. maybe this is where I am going wrong?
.buttons.blog-style p,
.magnifier p,
#gallery .caption p {
background-color: transparent;
border-color: rgb(0, 0, 0);
border-style: none;
border-width: 0;
font-weight: 500;
bottom: 20px;
color: rgb(0, 0, 0);
font-family: "Raleway";
font-size: 16px !important;
left: 30px;
line-height: 28px;
position: relative;
text-decoration: none;
text-transform: none !important;
text-shadow: none;
}
.buttons.blog-style h4,
.magnifier h4,
#gallery .caption h3 {
font-size:28px !important;
line-height:28px;
font-family:"HighVoltage" !important;
display: inline-block;
color: rgb(0, 0, 0);
position:absolute;
left:30px;
bottom:60px;
text-decoration:none;
text-transform: none !important;
background-color:transparent;
text-shadow:none;
border-width:0px;
border-color:rgb(0, 0, 0);
border-style:none;
}
Not reproducible, or am I seeing something else?
Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a Minimal, Complete, and Verifiable example.
What text are you referring to?? This is really vague for me. Can you make a codepen that reproduces the issue and points it out in specific?
Sorry guys! I mean the text when you hover over the image/placeholder which appears. if you hover over a few, you will see what I mean.
Apologies for not being clear on that!
did you check my answer ? if yes....comment if it's ok or what do you exactly want
i guess you want the h4 to always be on the bottom of the .button and if i understood right you want something like this :
jsfiddle
if an item has absolute position and you don't want it to overlap other items , you need to create a space for that item.
you need to add this css in order to work
.buttons {
position:relative
}
.buttons.blog-style p,
.magnifier p,
#gallery .caption p {
padding-bottom:88px;
}
.buttons.blog-style h4,
.magnifier h4,
#gallery .caption h3 {
margin:0;
}
where 88px is a sum between bottom:60px you have on the description and the height of the description line-height:28px;
i added margin:0 on the description because it just isn't necessary anymore. but if you want to keep that margin...add it to the padding-bottom:88px
Hey,
This helps stop the text overlapping, but results in the the title being above the description. I also still have the issue of the text vanishing off the box edge on some of the boxes with longer sentences.. This is a huge help though in getting me where I need to be :)
Thanks
Ah! Figured it out, I added what you mentioned, but removed the section for buttons to be relative, as I have that code already within the other sections. But removing the left borders all together got the text to stop vanishing. :) Thanks loads, your edits helped me figure this out!
| common-pile/stackexchange_filtered |
How do I solve this / express this question properly?
I put everything on a google document since I don't know how to use LaTeX or whatever. Here's the doc. I would prefer if you looked at the doc, but I've done my best to translate it onto here the best I can. Here it is.
$$\sum_{x=1}^{10} \frac yx = \text{Positive Integer}$$
If $n_1$ is the smallest $y$ value that satisfies the equation above, $n_2$ is the second smallest, etc. then what is the sum of $\sum_{z=n_1}^{n_{100}} z$?
(Example: n1 = 2520, because 2520 is the smallest number that is divisible by every number between 1 and 10.)
I simply have no idea how to even approach this problem. I just learnt about sigma (yes I’m only in algebra II), and so I started fumbling around with it and ended up with this question. I know that $\sum_{z=n_1}^{n_{100}} z$ technically means all the integers between n1 and n100 added together, but what I actually want to do is n1+n2+n3...+n100. How do I write that in sigma notation, or is that a separate part of algebra?
I gave this question a shot, so here it is. First things first, if x is divisible by y, then x*z (z being a non-zero integer) is still divisible by y. That means n2 might be 2n1, n3 might be 3n1, etc. I can generalize it by saying that nx=x(n1). So, the expression can be simplified to something along the lines of [100 over sigma over z=1 of 2520z]. So, that gives me 100(2520+252000)/2, which equates to 12726000. I highly doubt this is the correct answer, but if this question was on an exam or whatever, I would probably just put it as the answer and hope for the best."
The key to show that only the multiples of $2520$ are solutions is to consider that $$\sum_{j=1}^{10} \frac{1}{j}=\frac{7381}{2520}$$ and that $\gcd(7381,2520)=1$
| common-pile/stackexchange_filtered |
Burpees get fit plan
I am a software developer who spends a fair amount of time stuck in one position, sometimes not moving more than 5 hours straight if I have to concentrate on something.
Depending on the time of the year I do a lot of MTB biking, keep walking and generally avoid being sedentary. I do some stretching and try to compensate for a bit of a hyperlordotic posture, which is partially in the family and partially down to sitting.
I recently decided I need to get in better all over shape. Cycling keeps my legs trim but not much else. So I discovered this exercise called Burpee. I can do these near the computer so for me it's very convenient.
So I started these a few days ago, and not only has my posture and poise already completely changed, I feel like I have rigor mortis. The pain is nigh on unbearable and every single muscle in my body seems as though someone beat it repeatedly with a stick.
Can someone tell me if this is normal, or if I should do something different, eat something different, any suggestions? I am concerned I might do myself an injury like this.
It's highly likely you got DOMS from performing a high volume of an exercise you are not used to. Searching for "DOMS" yields a lot of already-answered questions on the topic. If your pain is localised joint or sharp in feeling then RICE and consult your doctor if it does not get better.
Possible duplicate of Prevent or treat delayed onset muscle soreness
Wow. Thanks for the pointers. Funny, there are no real answers. I am particularly attracted to one of the answers there that DOMS is probably a natural response that should be embraced as part of a sudden change in regimen. Hmmm.
Basially, just keep exercising and make sure you are getting enough good food and sleep. They will diminish. A common mistake is resting for too long and then just repeating the same cycle; warming up before exercise will reduce the feeling.
Yes, this looks like the right thing to do, JJosaur. It seems that the unfamiliarity part of it is key. Interesting aside related to DOMS is that my posture is totally different while I am having it. I think the pain is not a muscle soreness down to some kind of damage, but down to a persistent set of cramps that tense the muscles where they were exercised. This could imply that the mechanisms are nervous/CNS/electrolytical.
I don't think this is quite the same as "how can I prevent DOMS". It is a discovery (for me) that this actually is DOMS. Please can you add this as the answer and I will mark the question as answered.
It's highly likely you got DOMS from performing a high volume of an exercise you are not used to. Searching for "DOMS" yields a lot of already-answered questions on the topic. If your pain is localised joint or sharp in feeling then RICE and consult your doctor if it does not get better
Help me understand why you vote to close (on a duplicate), and, add an answer.
| common-pile/stackexchange_filtered |
JLabel not updating
so thanks for looking at my question,Well anyways im trying to make a cookie clicker clone (if you could call it that) where you click the button and the JPanel updates, unfortunately the JPanel doesn't update and I just cant find an answer anywhere else, Any help is valuable help, thank you! Here is my code:
public int numCookies;
public main(){
//JButton
JButton click = new JButton("Click");
click.setLayout(null);
click.setLocation(50, 50);
click.setSize(80, 50);
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
}
});
//JLabel
JLabel cookies = new JLabel();
cookies.setLayout(null);
cookies.setText("Cookies:" + numCookies);
cookies.setLocation(480/2,10);
cookies.setSize(200, 50);
//JPanel
JPanel panel = new JPanel();
panel.setLayout(null);
panel.setLocation(10, 0);
panel.setSize(260, 30);
panel.add(click);
panel.add(cookies);
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String args[]){
new main();
}
I see setLayout(null); and aren't surprised you're having issues...use an appropriate layout manager, no execuses
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them, along with layout padding & borders for white space.
Three things...
One...
Use of null layouts. Don't be surprised when things go wrong. When using JLabel or JButton, unless you intend to actually add something to them, you don't need to touch there layout managers.
Make use of approriate layout managers
Two...
Calling setVisible on your frame before you've finished filling it out...
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 480);
frame.setLocationRelativeTo(null);
// No idea what you expect this to be doing...
pack();
//frame.setVisible(true);
frame.add(panel);
// This belongs here...and you shouldn't pack a window until
// it's ready to be made visible...
frame.setVisible(true);
Three...
You seem to expect that the lable will magically now that the value numCookies has changed...
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
// ??????
}
You need to reassign the value to the label in order for the label to be updated...
For example...
public main(){
//JLabel
// Make the lable final...so we can access from witin
// the listener...
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
//JButton
JButton click = new JButton("Click");
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});
Bonus
Make sure you read through and understand Initial Threads
...And just because null layouts annoy me so much...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public int numCookies;
public Main() {
final JLabel cookies = new JLabel();
cookies.setText("Cookies:" + numCookies);
JButton click = new JButton("Click");
click.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
cookies.setText("Cookies:" + (++numCookies));
}
});
//JFrame
JFrame frame = new JFrame("Cookie clicker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
frame.add(cookies, gbc);
frame.add(click, gbc);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
new Main();
}
});
}
}
Set the text of the JLabel in the actionPerformed method like this:
click.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
numCookies = numCookies + 1;
cookies.setText("Cookies:" + numCookies);
}
});
| common-pile/stackexchange_filtered |
CakePHP-3.0 insert data from one table into 2 other tables
In my app, I have a table (stored in a read-only database):
Machines(ID, NAME, SERIAL_NUMBER, IP, MAC), in upper case.
and 2 tables in my CakePHP database:
Assets(id, name, serial_number)
AssetsAssignations(id, asset_id, ip, mac, is_machine)
I created a page called "retrieve_machines.ctp" to read the Machines table:
1- foreach SERIAL_NUMBER, if it does not exist in Assets, then add it to Assets.
2- foreach SERIAL_NUMBER, copy the new values of (ip, mac) into AssetsAssignations when SERIAL_NUMBER = AssetsAssignation->Asset->serial_number (Sorry for the imporper algorithm).
In AssetsController, I put this:
public function retrieveMachines()
{
$query = $this->Assets->find()
->contain([]);
$filter = $this->Filter->prg($query);
$assets = $this->paginate($filter, ['limit' => 50]);
$connection = ConnectionManager::get('db2'); // 'db2' where my second database is configured
$machines = $connection->execute('SELECT * FROM MACHINE ORDER BY NAME ASC');
$this->set(compact('machines'));
$this->set('_serialize', ['machines']);
$this->set(compact('assets', 'machines'));
$this->set('_serialize', ['assets']);
}
How to do it please?
I found a solution. In my retrieve_machines.ctp :
<table class="hoverTable dataTable">
<thead>
<tr>
<th>Model Number</th><th>Serial Number<th>MAC</th><th>IP</th><th scope="col" class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($machines as $machine):
$model_number = $machine['MODEL'];
$serial_number = $machine['SERIAL'];
$mac = $machine['MAC'];
$ip = $machine['IP'];
$is_found = false;
foreach ($assets as $asset):
if (strcasecmp($asset->serial_number, $serial_number) == 0) :
$is_found = true;
endif;
endforeach;
if(!$is_found):
?>
<tr>
<td><?= h($model_number) ?></td>
<td><?= h($serial_number) ?></td>
<td><?= h($mac) ?></td>
<td><?= h($ip) ?></td>
<td class="actions">
<?= $this->Html->iconButton('glyphicon-plus', __('Add to Assets'), [
'controller' => 'Assets',
'action' => 'add_from_db2', '?' => ['mnum' =>$model_number, 'snum' =>$serial_number]]);
?>
</td>
</tr>
<?php
endif;
endforeach; ?>
</tbody>
</table>
Then, in add_from_db2.ctp:
<div>
<?= $this->Form->create($asset) ?>
<fieldset>
<legend><?= __('Add Asset From DB2') ?></legend>
<div class="row">
<div class="col-xs-3"><?= $this->Form->input('model_number', array('default'=>$this->request->query['mnum'], 'autofocus'=>'autofocus')); ?></div>
<div class="col-xs-3"><?= $this->Form->input('serial_number', array('default'=>$this->request->query['snum'])); ?></div>
</div>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
| common-pile/stackexchange_filtered |
Correlation heatmap for a data frame split by a factor in R
I would like to generate a heatmap/correlation map in R. I have explored various packages, such as corrplot, ggcorrplot and pheatmap, but I found it difficult to get where I wanted.
As an example, using mtcars, I would like to generate a heatmap like below. Specifically:
Compare mpg only against disp, hp, drat and wt using Spearman correlations.
Do these comparisons for cyl=4, cyl=6 and cyl=8 separately.
Calculate the Spearman p values.
Draw heatmap, where tile colors represent Spearman correlation coefficients (r) and p values are printed on each tile.
Desired result similar to this:
I would appreciate help. Thank you.
You can do it with the psych package and a graphics package such as ggplot2 or pheatmap. First define a custom function to get the p-values, then apply the function with by.
library(psych)
myfun <- function(df) corr.test(df[, 1], df[, 3:6], method = "spearman", adjust =
"none")$p
dfs <- by(mtcars, mtcars$cyl, myfun)
mat <- do.call(rbind, dfs)
rownames(mat) <- c("cyl = 4", "cyl = 6", "cyl = 8")
library(pheatmap)
pheatmap(mat,
cluster_rows = F,
cluster_cols = F,
display_numbers = T,
show_rownames = T,
show_colnames = T,
number_format = "%.4f")
I haven't tried to exactly copy the heatmap above, but you can read ?pheatmap to learn about all its options.
Side note: If anyone can do this with the appropriate function in purrr piping into ggplot2 for the heatmap, you have my upvote.
Wow, that's awesome! Thank you so much, Joe!
No problem at all!
| common-pile/stackexchange_filtered |
How do I properly implement async/await for image data migration?
I'm writing a console app to do some data migration between a legacy system and a new version. Each record has associated images stored on one web server and I'm downloading/altering/uploading each image to Azure (and also recording some data about each image in a database).
Here's a rough outline, in code:
public void MigrateData()
{
var records = GetRecords();
foreach (var record in records)
{
// ...
MigrateImages(record.Id, record.ImageCount);
}
}
public void MigrateImages(int recordId, int imageCount)
{
for (int i = 1; i <= imageCount; i++)
{
var legacyImageData = DownloadImage("the image url");
if (legacyImageData != null && legacyImageData.Length > 0)
{
// discard because we don't need the image id here, but it's used in other workflows
var _ = InsertImage(recordId, legacyImageData);
}
}
}
// This method can be used elsewhere, so the return of int is necessary and cannot be changed
public int InsertImage(int recordId, byte[] imageData)
{
var urls = UploadImage(imageData).Result;
return // method call to save image and return image ID
}
public async Task<(Uri LargeUri, Uri ThumbnailUri)> UploadImage(byte[] imageData)
{
byte[] largeData = ResizeImageToLarge(imageData);
byte[] thumbnailData = ResizeImageToThumbnail(imageData);
var largeUpload = largeBlob.UploadFromByteArrayAsync(largeImage, 0, largeImage.Length);
var thumbUpload = thumbsBlob.UploadFromByteArrayAsync(thumbImage, 0, thumbImage.Length);
await Task.WhenAll(largeUpload, thumbUpload);
var largeUrl = "";// logic to build url
var thumbUrl = "";// logic to build url
return (largeUrl, thumbUrl);
}
I'm using async/await for UploadImage() to allow parallel uploads for the large and thumbnail images, saving time.
My question is (if it's possible/makes sense) how can I utilize async/await for MigrateImages() to do parallel image uploads in order to reduce the overall time it takes for the task to complete? Does the fact that I'm already using async/await within UploadImage() hinder my goal?
It might be obvious due to my question, but await/async is still something I can't fully wrap my head around about how to correct utilize and/or implement it.
InsertImage should be async and await UploadImage instead of calling Result. When InsertImage is async you can run multiple "inserts" by using the same pattern in MigrateImages as you do in UploadImage => start multiple async operations and await them with Task.WhenAll
The word "upload" would imply that you are I/O limited, not CPU limited. You need to determine if parallelization will benefit you. If the bottleneck is network speed, throwing more data into the bottleneck isn't going to speed anything up.
@DanielMann I'm trying to parallelize the process of uploading the images. Uploading 10 images "at the same time" should be faster than in serial, yes?
No. If you can upload 1 MB per second, and you're already uploading 1 MB per second, uploading two files at once means you're uploading at 1 MB per second, 500 KB per second per file. Or some other ratio that adds up to 1 MB/s.
@DanielMann understood, thanks for the clarification. For this example, we can assume upload bandwidth is not a limitation.
The async/await technology is intended for facilitating asynchrony, not concurrency. In your case you want to speed-up the images-uploading process by uploading multiple images concurrently. It is not important if you are wasting some thread-pool threads by blocking them, and you have no UI thread that needs to remain unblocked. You are making a tool that you are going to use once or twice and that's it. So I suggest that you spare yourself the trouble of trying to understand why your app is not behaving the way you expect, and avoid async/await altogether. Stick with the simple and familiar synchronous programming model for this assignment.
Combining synchronous and asynchronous code is dangerous, and even more so if your experience and understanding of async/await is limited. There are many intricacies in this technology. Using the Task.Result property in particular is a red flag. When you become more proficient with async/await code, you are going to treat any use of Result like a an unlocked grenade, ready to explode in your face at any time, and make you look like a fool. When used in apps with synchronization context (Windows Forms, ASP.NET) it can introduce deadlocks so easily that it's not even funny.
Here is how you can achieve the desired concurrency, without having to deal with the complexities of asynchrony:
public (Uri LargeUri, Uri ThumbnailUri) UploadImage(byte[] imageData)
{
byte[] largeData = ResizeImageToLarge(imageData);
byte[] thumbnailData = ResizeImageToThumbnail(imageData);
var largeUpload = largeBlob.UploadFromByteArrayAsync(
largeImage, 0, largeImage.Length);
var thumbUpload = thumbsBlob.UploadFromByteArrayAsync(
thumbImage, 0, thumbImage.Length);
Task.WaitAll(largeUpload, thumbUpload);
var largeUrl = "";// logic to build url
var thumbUrl = "";// logic to build url
return (largeUrl, thumbUrl);
}
I just replaced await Task.WhenAny with Task.WaitAll, and removed the wrapping Task from the method's return value.
Thanks, but you didn't actually answer the question - my code isn't working unexpectedly, I'm looking for ways to improve upon it.
Even though your suggestion of shying away from async/await is fine, your code doesn't do anything more than what I already have. There is no performance gain.
@Matt your code already performs concurrent uploads. Adding asynchrony to the mix will not make it faster. If you are asking for suggestions about how to make it faster, I would suggest to start by measuring the duration of uploading two files sequentially, and then two files concurrently. Then measure the duration of downloading and uploading one file sequentially, and then downloading and uploading one file concurrently. Give us these results and we may be able to help!
| common-pile/stackexchange_filtered |
Fabric says 'no route to host', even though I can access it over SSH
I'm having some issues uploading a file to a server with Fabric. I get the following output:
Fatal error: Low level socket error connecting to host ssh.example.com: No route to host
Aborting.
The weird thing is, when I connect manually using ssh (same host string, I copy-pasted it from the fabfile to make sure), it works perfectly as expected. I can also use scp to copy the file to the same location manually.
The offending line in my Fabfile is this, if it helps:
put('media.tgz','/home/private/media.tgz')
Also, I'm connecting to a different host to the rest of my fabfile using the @hosts() decorator (this particular method uploads static media, which is served from somewhere different to the app itself).
I had the same issue. Had not investigated it but using the IP-Address instead the hostname helped. This particular host had an IPv6 AAAA record but my client had no IPv6 connection, maybe this is the reason. HTH
I've had the same issue and it is related to using AAAA records when you have no ipv6 connectivity
| common-pile/stackexchange_filtered |
How to set to true / false based on react props
const [effective_date_status, setEffectiveDateStatus] = React.useState(false)
I'm sending props value from parent to child. I want to set effective_date_status to false if props value is 0 & I want to set to true if props value is 1.
Can anyone help me with this issue.
You can do as:
const [effective_date_status, setEffectiveDateStatus] = React.useState(
!!props.value
);
or
const [effective_date_status, setEffectiveDateStatus] = React.useState(
props.value === 0 ? false : true
);
or Lazy Initialisation
const [effective_date_status, setEffectiveDateStatus] = React.useState(() =>
props.value === 0 ? false : true
);
Lazy Initialization worked for my needs. Thank you.
first, import use effect hook and then try this
useEffect(()=>{
if(props.value === 1)
setEffectiveDateStatus(true);
else if(props.value === 0)
setEffectiveDateStatus(false);
},[props.value])
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.