date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/22 | 1,196 | 4,511 | <issue_start>username_0: I've got this code:
```
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
```
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
```
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
```
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: <http://maps.google.com/maps/api/js?sensor=false&libraries=geometry><issue_comment>username_1: You have the `return` inside an anonymous function that you pass to `geocoder.geocode`, all in yet another function (`get_lat`/`get_lng`). `get_lat`/`get_lng` themselves don't have a `return` statement, and thus return `undefined`.
Furthermore, `geocoder.geocode` will call your anonymous function asynchronously. Which means that there is no chance for `get_lat`/`get_lng` to get hold of the `return` value and `return` it where `get_lat`/`get_lng` was called.
One solution (the simplest one) is to put the `createMarker` code in the callback for `geocoder.geocode`. Also, in this case you will have to merge your two `get_lat`/`get_lng` functions. Example:
```
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
```
Upvotes: 1 <issue_comment>username_2: You have to wait until Google API gives response. So write a logic to create marker in **callback function** of Google API as shown below.
```
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
```
and call that function as shown below
```
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
```
and you will get marker on a map
Upvotes: 0 |
2018/03/22 | 874 | 2,475 | <issue_start>username_0: I am beginner in coding. I have dynamic product price. Price is like 40000, 60000, 654000. I want to make them in [Indian numbering system](https://en.wikipedia.org/wiki/Indian_numbering_system) like 4 Lac, 6.5 Lac, and 1 cr.
I found this code on stackoverflow
```
function numDifferentiation(val) {
if(val >= 10000000) val = (val/10000000).toFixed(2) + ' Cr';
else if(val >= 100000) val = (val/100000).toFixed(2) + ' Lac';
else if(val >= 1000) val = (val/1000).toFixed(2) + ' K';
return val;
}
```
I tried `document.write(numDifferentiation(php echo $row['price'];));</code but its not working.`<issue_comment>username_1: ```
function numDifferentiation(val) {
if(val >= 10000000) val = (val/10000000).toFixed(2) + ' Cr';
else if(val >= 100000) val = (val/100000).toFixed(2) + ' Lac';
else if(val >= 1000) val = (val/1000).toFixed(2) + ' K';
return val;
}
document.write(numDifferentiation(<?php echo $row['price'];?>));
```
you missed the closing php tag '?>'
Upvotes: 3 [selected_answer]<issue_comment>username_2: First thing is you php script has syntax error it should be closed when open.
like below
```
document.write(numDifferentiation('php echo $row['price'];?'));]
```
you can you a html tag and pass access that html tag using id like this `$('id').val(numDifferentiation('php echo $row['price'];?'))`
Upvotes: 0 <issue_comment>username_3: ```
function numDifferentiation(val) {
if(val >= 10000000) val = (val/10000000).toFixed(2) + ' Cr';
else if(val >= 100000) val = (val/100000).toFixed(2) + ' Lac';
else if(val >= 1000) val = (val/1000).toFixed(2) + ' K';
return val;
}
document.write(numDifferentiation(290000));
```
working code
you can also try
```
document.write(numDifferentiation(php echo $row['price'];?));
```
becouse you are not closing php tag
Upvotes: -1 <issue_comment>username_4: The problem is not your javascript function, it looks to works fine.
First, you have to close your Php Tag
Change:
`numDifferentiation(php echo $row['price'];)</code`
To: `numDifferentiation(php echo $row['price']; ?)`
Now, diferent from Php, in JavaScript, you'll always change an existing element, so...
Create an element in HTML:
And just change the element's content using JavaScript
`document.querySelector('#mySpan').innerHTML = numDifferentiation(php echo $row['price'];)</code`
It is suppose to works, try and if you have any error don't hesitate in ask more help :)
Upvotes: -1 |
2018/03/22 | 788 | 3,009 | <issue_start>username_0: Is there a way to validate in java if the given private key, say certain \*.key file matches with the certain public key, to a certain .pub file using RSA algorithm?<issue_comment>username_1: You can verify if a key pair matches by
* creating a **challenge** (random byte sequence of sufficient length)
* **signing** the challenge with the **private key**
* **verifying** the signature using the **public key**
This gives you a sufficiently high confidence (almost certainity) that a key pair matches if the signature verification is ok, and an absolute certainity that a key pair does not match otherwise.
Example code:
```
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// create a challenge
byte[] challenge = new byte[10000];
ThreadLocalRandom.current().nextBytes(challenge);
// sign using the private key
Signature sig = Signature.getInstance("SHA256withRSA");
sig.initSign(privateKey);
sig.update(challenge);
byte[] signature = sig.sign();
// verify signature using the public key
sig.initVerify(publicKey);
sig.update(challenge);
boolean keyPairMatches = sig.verify(signature);
```
This also works with **Elliptic Curve (EC)** key pairs, but you need to use a different signature algorithm (`SHA256withECDSA`):
```
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC");
keyGen.initialize(new ECGenParameterSpec("sect571k1"));
...
Signature sig = Signature.getInstance("SHA256withECDSA");
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: The answer that was marked as being correct wastes a lot of CPU cycles. This answer is waaaay more CPU efficient:
```
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
RSAPrivateCrtKey privateKey = (RSAPrivateCrtKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
// comment this out to verify the behavior when the keys are different
//keyPair = keyGen.generateKeyPair();
//publicKey = (RSAPublicKey) keyPair.getPublic();
boolean keyPairMatches = privateKey.getModulus().equals(publicKey.getModulus()) &&
privateKey.getPublicExponent().equals(publicKey.getPublicExponent());
```
(the other answer signs a message with the private key and then verifies it with the public key whereas my answer checks to see if the modulus and public exponent are the same)
Upvotes: 3 <issue_comment>username_3: `boolean keyPairMatches = privateKey.getModulus().equals(publicKey.getModulus()) && privateKey.getPublicExponent().equals(publicKey.getPublicExponent());`
`java.security.interfaces.RSAPrivateKey` doesn't have getPublicExponent() method.
`org.bouncycastle.asn1.pkcs.RSAPrivateKey` has getPublicExponent() method.
So,if you don't want to use `bouncycastle`, you have to use the `sign&verify` answer.
Upvotes: 0 |
2018/03/22 | 417 | 1,520 | <issue_start>username_0: I'm working on Laravel and my question is: How can I update value in one table when inserting data to another? Do I have to write new function in controller or update existing or maybe its done on form level in eloquent (view?)?
For example:
That's my OrderController.php function handling inserting:
```
public function insert(Request $request){
$order = new order;
$order->material_id = $request->material_id;
$order->invoice_id = $request->invoice_id;
$order->count_order = $request->count_order;
$order->save();
return redirect('/order');
}
```
order.blade.php form that inserts data looks like:
```
@foreach($invoices as $invoice)
{{$invoice->number}}
@endforeach
@foreach($materials as $material)
{{$material->name}}
@endforeach
Dodaj zamówienie
{{ csrf\_field() }}
```
Orders table has:
```
| id | count_order | material_id | invoice_id |
```
Materials table has:
```
| id | name | count_all | count_current | price_unit |
```
Now I want to update column (add value) **count\_all** in **Materials** when I post value in a form when inserting to **count\_order** column in **Orders** table.<issue_comment>username_1: You can extend the `save()` function in Order model, there you would have the value you need and you can perform an update in Materials
Upvotes: 0 <issue_comment>username_2: you can use if
```
$query = $order->save();
if($query){
//do update data
}
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,018 | 3,770 | <issue_start>username_0: I have a list of base class like this:
```
List ChildClasses
```
I have child classes like this:
```
class ChildFoo : BaseClass {}
class ChildBar : BaseClass {}
class ChildBaz : BaseClass {}
class ChildQax : BaseClass {}
class ChildBox : BaseClass {}
...
```
I need to implement a method which can query the `ChildClasses` list to see if it has all of the types I pass to it, which are all derived from `BaseClass`.
So, if I call this method for types `ChildFoo` and `ChildBar`, it should return true if `ChildClasses` list contains at least one instance of `ChildFoo` and `ChildBar`.
How can I approach this situation?<issue_comment>username_1: >
> it should return true if ChildClasses list contains at least one instance of ChildFoo and ChildBar.
>
>
>
You could use [OfType](https://msdn.microsoft.com/en-us/library/bb360913(v=vs.110).aspx) with [Any](https://msdn.microsoft.com/en-us/library/system.linq.enumerable.any(v=vs.110).aspx). You could then combine the expression multiple times.
```
var containsFooAndBar = ChildClasses.OfType().Any()
&& ChildClasses.OfType().Any();
```
---
### Alternate
You could also approach it from the other direction. Create a list of all mandatory types that need to be included and then execute a query on that list using the `ChildClasses` list as the input. This is just a different way of writing the above, the `ChildClasses` collection is still iterated over 2x.
```
Type[] mandatoryTypes = new Type[] {typeof(ChildFoo), typeof(ChildBar)};
var containsFooAndBar = mandatoryTypes.All(mandatoryType => ChildClasses.Any(instance => instance != null && mandatoryType == instance.GetType()));
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Assuming the inheritance hierarchy doesn't go any deeper than in your example...
Create a hashset of the actual types in the list:
```
var actualTypes= new HashSet(ChildClasses.Select(x=>x.GetType()));
```
Then create a hashset of the required types:
```
var requiredTypes = new HashSet
{
typeof(ChildFoo),
typeof(ChildBar)
};
```
Remove all the actual types from the set of required types:
```
requiredTypes.ExceptWith(actualTypes);
```
If `requiredTypes.Count == 0` then the list contained all the required types. If `requiredTypes.Count > 0` then there were missing types and these will be left as the contents of `requiredTypes`.
This approach should be easier to implement if the number of required types is variable (let the caller pass in a hashset directly or an IEnumerable from which you construct the hashset) and be performant for large numbers of items in either ChildClasses or required types.
Upvotes: 1 <issue_comment>username_3: You could create a method which takes your list of classes, and also an array of types, and then check to see if the provided list contains all of those types:
```
static bool ContainsTypes(List list, params Type[] types)
{
return types.All(type => list.Any(x => x != null && type == x.GetType()));
}
```
And implement it like this:
```
List baseClasses = new List();
baseClasses.Add(new ChildFoo());
baseClasses.Add(new ChildBar());
//Population code here...
var result = ContainsTypes(baseClasses, typeof(ChildFoo), typeof(ChildBar));
```
---
**Or if you want to use extension methods**
```
public static class Extensions
{
public static bool ContainsTypes(this List list, params Type[] types)
{
return types.All(type => list.Any(x => x != null && type == x.GetType()));
}
}
```
And once again, implement like so:
```
List baseClasses = new List();
baseClasses.Add(new ChildFoo());
baseClasses.Add(new ChildBar());
//Population code here...
var result = baseClasses.ContainsTypes(typeof(ChildFoo), typeof(ChildBar));
```
Upvotes: 1 |
2018/03/22 | 627 | 2,432 | <issue_start>username_0: We are trying to cache all Gradle dependencies for our Android `build` job.
This is the current approach that is failing:
```
- restore_cache:
key: android-build-{{ checksum "android/build.gradle" }}-{{ checksum "android/app/build.gradle" }}
- save_cache:
paths:
- ~/.gradle
key: android-build-{{ checksum "android/build.gradle" }}-{{ checksum "android/app/build.gradle" }}
```<issue_comment>username_1: There's a sample Android configuration [by Circle CI themselves here](https://circleci.com/docs/2.0/language-android/) as well as a step-by-step walkthrough of the attributes.
```
version: 2
jobs:
build:
working_directory: ~/code
docker:
- image: circleci/android:api-25-alpha
environment:
JVM_OPTS: -Xmx3200m
steps:
- checkout
- restore_cache:
key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
# - run:
# name: Chmod permissions #if permission for Gradlew Dependencies fail, use this.
# command: sudo chmod +x ./gradlew
- run:
name: Download Dependencies
command: ./gradlew androidDependencies
- save_cache:
paths:
- ~/.gradle
key: jars-{{ checksum "build.gradle" }}-{{ checksum "app/build.gradle" }}
- run:
name: Run Tests
command: ./gradlew lint test
- store_artifacts:
path: app/build/reports
destination: reports
- store_test_results:
path: app/build/test-results
```
It's worth noting that we experienced some issues when utilising the cache due to submodules, but the above should work for simpler repositories.
Upvotes: 2 <issue_comment>username_2: Place build steps between `restore_cache` and `save_cache`.
If your project is multi-module/-level **hash all build scripts** and use it as key to proper capture dependencies:
```
- run:
name: Hash dependency info
command: |
mkdir -p build
md5sum gradle.properties settings.gradle build.gradle **/build.gradle >build/deps.md5
- restore_cache:
key: gradle-{{ checksum "build/deps.md5" }}
- run:
name: Build and deploy
command: >
bash ./gradlew
build artifactoryPublish
- save_cache:
key: gradle-{{ checksum "build/deps.md5" }}
paths:
- ~/.gradle/caches
- ~/.gradle/wrapper
```
Upvotes: 1 |
2018/03/22 | 512 | 1,893 | <issue_start>username_0: I don't understand this code;
Can someone write it proper so I can also understand.
```
public void deleteStudentsPersistence(Student student) {
em.remove(em.contains(student) ? student : em.merge(student));
}
```<issue_comment>username_1: this is a ternary operator, called conditional operator. it could also be written this way:
```
public void deleteStudentsPersistence(Student student) {
if (em.contains(student)){
em.remove(student);
} else{
em.remove(em.merge(student));
}
}
```
basically, it check if em contains the student before removing, otherwise it merge it
Upvotes: 2 <issue_comment>username_2: The operator you used there is called a ternary operator and it works almost the same way an if-else statement works. Consider the statement below:
```
int min = (a < b) ? a : b;
```
What this means is: *Evaluate the value of `(a < b)`, if it's true, the value of min is `a`, otherwise, the value of min is `b`*. It can be related to the if-else statement this way: **If (a < b) is true: min = a; else: min is b.**
Back to your question now....
```
em.remove(em.contains(student) ? student : em.merge(student));
```
This means if `em.contains(student)` is true, then perform `em.remove(student)`, however if it's false, then perform `em.remove(em.merge(student))`.
**PS:**
Obviously, in many practical cases that involve giving a variable a value based on a two-way condition, this can be a subtle replacement for if-statement. There is great argument about the "more efficient" method as seen in [this post](https://stackoverflow.com/questions/9745389/is-the-ternary-operator-faster-than-an-if-condition) but I personally prefer to use the ternary operator because of it's relatively short syntax length and readability.
I hope this helps.. Merry coding!
Upvotes: 3 [selected_answer] |
2018/03/22 | 675 | 2,568 | <issue_start>username_0: I’ve searched and read all the posts I can find, but I don’t think I get it. We have an extron SMP that provides us with a multicast live RTP stream. This stream can be viewed from any computer on our network using VLC Player. Now we want to play this stream in our browser.
I know that you cannot natively play the stream and must convert it real time to an HTML compatible version. This is where I am having issues.
I have attempted to use the program ‘udpxy’ which converted the multicast stream to an H264 HTTP Stream, but I could never find an HTML player that would play the stream. It worked in VLC, But the ‘video’ tag, videoJS, not jwplayer would work.
I also attempted to use nginx and the nginx rtmp module and failed miserably. Could never get nginx to serve a stream.
Could some elaborate on the method that I need to use to convert the multicast RTP stream to an HTML5 compliant stream.<issue_comment>username_1: this is a ternary operator, called conditional operator. it could also be written this way:
```
public void deleteStudentsPersistence(Student student) {
if (em.contains(student)){
em.remove(student);
} else{
em.remove(em.merge(student));
}
}
```
basically, it check if em contains the student before removing, otherwise it merge it
Upvotes: 2 <issue_comment>username_2: The operator you used there is called a ternary operator and it works almost the same way an if-else statement works. Consider the statement below:
```
int min = (a < b) ? a : b;
```
What this means is: *Evaluate the value of `(a < b)`, if it's true, the value of min is `a`, otherwise, the value of min is `b`*. It can be related to the if-else statement this way: **If (a < b) is true: min = a; else: min is b.**
Back to your question now....
```
em.remove(em.contains(student) ? student : em.merge(student));
```
This means if `em.contains(student)` is true, then perform `em.remove(student)`, however if it's false, then perform `em.remove(em.merge(student))`.
**PS:**
Obviously, in many practical cases that involve giving a variable a value based on a two-way condition, this can be a subtle replacement for if-statement. There is great argument about the "more efficient" method as seen in [this post](https://stackoverflow.com/questions/9745389/is-the-ternary-operator-faster-than-an-if-condition) but I personally prefer to use the ternary operator because of it's relatively short syntax length and readability.
I hope this helps.. Merry coding!
Upvotes: 3 [selected_answer] |
2018/03/22 | 651 | 2,182 | <issue_start>username_0: I have two python files in same folder `file1.py` `file2.py`.
`file1.py`
```
data = dict()
data["user1"] = "xyz"
data["user2"] = "abc"
#saving it in json
with open(myfile, "w") as f: #myfile is a path to a json file
json.dump(data , f, indent=4, ensure_ascii=False)
```
I want to use `data` in file2:
```
data["user3"] = "qwe"
data["user4"] = "rty"
```
and then use the values of `user3` & `user4` from file2 to save in `myfile`. I tried importing it but it didnt work. How can I resolve it.?
Thanks<issue_comment>username_1: this is a ternary operator, called conditional operator. it could also be written this way:
```
public void deleteStudentsPersistence(Student student) {
if (em.contains(student)){
em.remove(student);
} else{
em.remove(em.merge(student));
}
}
```
basically, it check if em contains the student before removing, otherwise it merge it
Upvotes: 2 <issue_comment>username_2: The operator you used there is called a ternary operator and it works almost the same way an if-else statement works. Consider the statement below:
```
int min = (a < b) ? a : b;
```
What this means is: *Evaluate the value of `(a < b)`, if it's true, the value of min is `a`, otherwise, the value of min is `b`*. It can be related to the if-else statement this way: **If (a < b) is true: min = a; else: min is b.**
Back to your question now....
```
em.remove(em.contains(student) ? student : em.merge(student));
```
This means if `em.contains(student)` is true, then perform `em.remove(student)`, however if it's false, then perform `em.remove(em.merge(student))`.
**PS:**
Obviously, in many practical cases that involve giving a variable a value based on a two-way condition, this can be a subtle replacement for if-statement. There is great argument about the "more efficient" method as seen in [this post](https://stackoverflow.com/questions/9745389/is-the-ternary-operator-faster-than-an-if-condition) but I personally prefer to use the ternary operator because of it's relatively short syntax length and readability.
I hope this helps.. Merry coding!
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,093 | 3,651 | <issue_start>username_0: Java 10 brings a C#-like `var` keyword for [local type-inference](https://developer.oracle.com/java/jdk-10-local-variable-type-inference).
But does Java 10 also provide a `val` keyword, as is [found in Scala](https://stackoverflow.com/questions/4437373/use-of-def-val-and-var-in-scala)?
`val` would work like `var` but the binding would be `final`.
```
var x = "Hello, world. ";
x = "abc"; // allowed
val y = "Hello, world. ";
y = "abc"; // forbidden
```
If it does not, is there a reason that this is the case?<issue_comment>username_1: There is no `val` in Java 10, as stated in [JEP 286: Local-Variable Type Inference](http://openjdk.java.net/jeps/286):
>
> **Syntax Choices**
>
>
> There was a diversity of opinions on syntax. The two main degrees of freedom here are what keywords to use (var, auto, etc), and whether to have a separate new form for immutable locals (val, let). We considered the following syntactic options:
>
>
> * var x = expr only (like C#)
> * var, plus val for immutable locals (like Scala, Kotlin)
> * var, plus let for immutable locals (like Swift)
> * auto x = expr (like C++)
> * const x = expr (already a reserved word)
> * final x = expr (already a reserved word)
> * let x = expr
> * def x = expr (like Groovy)
> * x := expr (like Go)
>
>
> After gathering substantial input, var was clearly preferred over the Groovy, C++, or Go approaches. There was a substantial diversity of opinion over a second syntactic form for immutable locals (val, let); this would be a tradeoff of additional ceremony for additional capture of design intent. **In the end, we chose to support only `var`**. Some details on the rationale can be found [here](http://mail.openjdk.java.net/pipermail/platform-jep-discuss/2016-December/000066.html).
>
>
>
And here's the main reasoning:
>
> I know this is the part people really care about :) After considering
> the pros and cons at length, there appears to be an obvious winner --
> var-only. Reasons for this include:
>
>
> * While it was not the most popular choice in the survey, it was
> clearly the choice that the most people were OK with. Many hated
> var/val; others hated var/let. Almost no one hated var-only.
> * Experience with C# -- which has var only -- has shown that this is a
> reasonable solution in Java-like languages. There is no groundswell of
> demand for "val" in C#.
> * The desire to reduce the ceremony of immutability is certainly
> well-taken, but in this case is pushing on the wrong end of the lever.
> Where we need help for immutability is with fields, not with locals. But
> var/val doesn't apply to fields, and it almost certainly never will.
> * If the incremental overhead of getting mutability control over that
> of type inference were zero, there might be a stronger case, but it was
> clear that many people found two different leading keywords to be a
> distraction that kept their eyes from quickly settling on the important
> stuff. If variable names are more important than types, they're more
> important than mutability modifiers too.
>
>
>
([Source](http://mail.openjdk.java.net/pipermail/platform-jep-discuss/2016-December/000066.html))
Upvotes: 7 [selected_answer]<issue_comment>username_2: Because there is `final var` for that in Java. If we had `val` too, there would be two things that mean the same. This is not good. There should be only one way to express a particular thing.
Upvotes: 4 <issue_comment>username_3: If you want to use "val", that is, "final var", you always can to use [Lombok's val](https://projectlombok.org/features/val).
Upvotes: 3 |
2018/03/22 | 485 | 1,992 | <issue_start>username_0: I have an NSObject class, which has some primitive properties:
### MyClass.h
```
@interface MyClass: NSObject
@property (nonatomic, assign) BOOL boolProp;
@property (nonatomic, assign) NSInteger intProp;
@end
```
### MyClass.m
```
@implementation MyClass
// No init implemented
@end
```
From what I experienced, when there is no init method, then the properties default to "reasonable" values (`BOOL` to `NO`, `intProp` to `0`). Is this defined behaviour? If yes, is there any Apple documentation for this behaviour?<issue_comment>username_1: By default the structure behind the implementation (a C structure) is being set to 0 as a whole. Imagine using `memset(self, 0, sizeof(_type))`. All the rest is just typecasting. That means all pointers are `Null`, all integers or other numbers are `0`, all boolean values are `0`, `NO` or `false`.
I am not sure there is a documentation about it but if it is then it is on the level of allocation of `NSObject`. These defaults are there in general the way are described it but that might not actually meant they are guarantied. What I mean by that is that although this functionality of setting all to zero is working there is still a chance that this behaviour may not be true for some old version or for some future version. (unless this behaviour is in fact documented).
It should also be noted that as said the memory of structure itself is set to zero so no setters are being called to put things to zero and no logic is executed no matter how you setup your class.
Upvotes: 3 [selected_answer]<issue_comment>username_2: As for Apple documentation check [Object Initialization](https://developer.apple.com/library/content/documentation/General/Conceptual/CocoaEncyclopedia/Initialization/Initialization.html). It mentions the topic raised in your question. For example
>
> The default set-to-zero initialization performed on an instance variable during allocation is often sufficient
>
>
>
Upvotes: 3 |
2018/03/22 | 635 | 2,410 | <issue_start>username_0: I want to delete records from both tables in the JOIN from the this CTE in `SQL Server 2012`:
```
WITH RECORDS_TO_DELETE ([Counter], [ID])
AS
(
SELECT D.[Counter], D.[ID], C.[ID]
FROM [Table1] AS D
LEFT JOIN
(
SELECT [ID] FROM [Table2]
WHERE NOT LOWER (COL1) = '*my criteria*'
AND (Date1 <= '31-Mar-2010' OR Date2 <= '31-Mar-2010')) AS C
ON D.ID = C.ID
)
DELETE FROM RECORDS_TO_DELETE
```
I have seen other examples that say its important to do this in the correct order but those examples are not in `CTEs`. I used a `CTE` because I have a convoluted `WHERE` clause (perhaps complicated by the fact my JOIN is to a result set) that I haven't felt necessary to include here. A `CTE` was the only thing that selected the data I wanted deleted.
Is there a way to delete records from both tables where there is a match between both tables?<issue_comment>username_1: SQL Server only allows a `delete` statement to delete records from one table.
Two options come to mind for removing records from multiple. The first is to define foreign key relationships with the `cascading delete` option. The second is to define a trigger on a view that combines the two tables.
Neither of these are modifications really use a `delete` statement. In other words, the database needs to be designed to support deletion from multiple tables at once.
Upvotes: 0 <issue_comment>username_2: In order to delete the records from both tables, use your CTE to identify the primary key values for all of the records in both tables that you want to delete and write those values somewhere (table variable, temp table, actual table, probably based on the volume of your data).
Then execute two DELETE statements, one against each table, joining on the key values for the table in question.
You'll need that table to hold your values since, after you delete from the first table, your CTE won't work to identify the needed records anymore.
```
WITH cte AS
(
INSERT YOUR LOGIC HERE
)
INSERT INTO @KeyValuesHoldingTable
SELECT
*
FROM
cte;
DELETE Table1
FROM
Table1 as t
JOIN
@KeyValuesHoldingTable as h
ON t.KeyValues = h.KeyValues;
DELETE Table2
FROM
Table2 as t
JOIN
@KeyValuesHoldingTable as h
ON t.KeyValues = h.KeyValues;
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,108 | 3,211 | <issue_start>username_0: I have a nested dictionary, an encryption function and a dotted path, I want to apply my encryption function to encrypt specific field.
Example:
mydict
```
{"a":{
...
"b":{
...
"c":"value"
}
}
}
```
field path: `a.b.c`
I want to execute encryption function on `c` value and modify my dict.
What's the most efficent and pythonic way?<issue_comment>username_1: Dictionary are quite efficient in python, so you can directly encrypt it:
```
# d -- dictionary
key1 = d.keys()[0]
key2 = d[key1].keys()[0]
key3 = d[key1][key2].keys()[0]
d[key1][key2][key3] = encrypt(d[key1][key2][key3])
```
Upvotes: 0 <issue_comment>username_2: I'm guessing what you mean is have the number of nestings be variable according to a string like `'a.b.c'`:
```
d = {"a":{"b":{"c":"value"}}}
dotted = 'a.b.c'
paths, current = dotted.split('.'), d
for p in paths[:-1]:
current = current[p]
current[paths[-1]] = encrypt(current[paths[-1]])
```
this will modify the given dictionary `d` to be
```
{"a":{"b":{"c":"whatever the encrypted value is"}}}
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: By recommended practices you should probably get it by,
```
d['a']['b']['c']
```
Or you may add a Class to objectify for using dot (A hacky solution though).
```
class Objectify(object):
def __init__(self, obj):
for key in obj:
if isinstance(obj[key], dict):
self.__dict__.update(key=Objectify(obj[key]))
else:
self.__dict__.update(key=obj[key])
d = Objectify({'a': {'b': {'c': True}}})
print(d.a.b.c)
```
Result:
```
True
```
Upvotes: 1 <issue_comment>username_4: Use below function
```
def update(d, path, value):
out = path.split('.', 1)
key = out[0]
if len(out) > 1:
path = out[1]
return update(d[key], path, value)
else:
d[key] = value
d = {'a': {'b': {'c': 'value'}}}
path = 'a.b.c'
value = 100 # let's consider encrypted value
update(d, path, value)
print(d )
# Output: {'a': {'b': {'c': 100}}}
```
Upvotes: 2 <issue_comment>username_5: Maybe a little too late and **tricky** but to be **functional**:
```py
from functools import reduce
d = {'a': {'b': {'c': 'value'}}}
path = 'a.b.c'
# result will be 'value'
result = reduce(dict.__getitem__, path.split('.'), d)
```
Upvotes: 2 <issue_comment>username_6: You can use [glom assignment](https://glom.readthedocs.io/en/latest/mutation.html#assignment) to get and modify the value in-place:
```
from glom import glom, assign, Assign, Spec
d = {'a': {'b': {'c': 'value'}}}
```
Option 1 with [regular glom assignment](https://glom.readthedocs.io/en/latest/mutation.html#glom.Assign:%7E:text=Assign%20is%20to-,deep%2Dapply,-a%20function%3A):
```
value_to_encrypt = glom(d,'a.b.c') # deep-get
_ = assign(d, 'a.b.c', encrypt(value_to_encrypt)) # deep-modify 'c' in place
```
Option 2 with [deep-apply](https://glom.readthedocs.io/en/latest/mutation.html#glom.Assign:%7E:text=Assign%20is%20to-,deep%2Dapply,-a%20function%3A):
```
_ = glom(d, Assign('a.b.c', Spec(('a.b.c', encrypt)))) # applies 'encrypt' on a.b.c and modifies the value in place
```
Upvotes: 0 |
2018/03/22 | 457 | 1,876 | <issue_start>username_0: I am trying to do junit testing using plain junit by calling the controller class method as below, when i am doing this, the @Autowired annotation for object creation returns me null instead of creating the object.
Example:
JunitClass:
```
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestingJunit {
@Test
public void testing() {
APIController repo = new APIController();
ResponseEntity prod = repo.getNames(8646, 1);
List ff = (List) prod.getBody();
Assert.assertEquals("AA", ff.get(0).getName());
}
}
```
Controller:
```
@Autowired
private ServiceClass serviceClass;
public ResponseEntity getNames(@PathVariable("aa") int aa, @RequestHeader(value = "version") int version){
serviceClass.callSomeMethod(); // **here i am getting null for serviceClass object**
}
```<issue_comment>username_1: It's because you manually instaniates your controller by doing `APIController repo = new APIController();`. Doing this, Spring does not inject your service because you explicitely controls your bean (and its dependencies).
Try inject your controller in your test instead.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can inject your APIController bean instead of doing `new APIController()` by autowiring the same in test class. As by doing new APIController the ServiceClass instance was not created/injected hence giving a NullPointer Exception.
Below should be the test class.
```
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestingJunit {
@AutoWired
APIController apiController; //apiController will be referring to bean Name
@Test
public void testing() {
ResponseEntity prod = apiController.getNames(8646, 1);
List ff = (List) prod.getBody();
Assert.assertEquals("AA", ff.get(0).getName());
}
}
```
Upvotes: 0 |
2018/03/22 | 530 | 2,047 | <issue_start>username_0: I use AngularFire library to read data from Firebase Realtime database. Below is the code that I used to subscribe for real time data changes
```
// db is a reference to AngularFireDatabase
this.dbSubscription = db.list('/authors').valueChanges().subscribe(items =>
```
For some user actions I have to change the path that I'm listening data. So the code looks like this
```
this.dbSubscription.unsubscribe();
this.dbSubscription = db.list('/books').valueChanges().subscribe(items =>
```
Is calling `this.dbSubscription.unsubscribe();`detach the application from the database so that any data changes happen to the the previous path, i.e. /authors does not sync with the application once it is subscribed to new path /books ? I want to make sure that the data that I'm not interested are not downloaded to the application.<issue_comment>username_1: You are correct in your thinking.
`AngularFire` does not have an API function such as `off()` like the regular [JavaScript library](https://firebase.google.com/docs/database/web/read-and-write#detach_listeners) does. `off()`, in the JavaScript library, would be used remove the listener on the database.
Using `unsubscribe()` is the correct way to achieve what you want in `AngularFire`.
More can be read [here](https://github.com/angular/angularfire2/issues/380).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Yep! Calling unsubscribe will in fact call the `.off()` method under the hood. You can see it [here in the source code](https://github.com/angular/angularfire2/blob/master/src/database/observable/fromRef.ts#L26).
```
return new Observable(subscriber => {
const fn = ref[listenType](event, (snapshot, prevKey) => {
subscriber.next({ snapshot, prevKey });
if (listenType == 'once') { subscriber.complete(); }
}, subscriber.error.bind(subscriber));
if (listenType == 'on') {
// return a method for unsubscribing the listener
return { unsubscribe() { ref.off(event, fn)} };
} else {
return { unsubscribe() { } };
}
})
```
Upvotes: 2 |
2018/03/22 | 525 | 1,988 | <issue_start>username_0: I am using `ng-idle` to redirect the user back to the home screen if the app isn't used within 60 seconds.
The problem I have is that if there is an ion-select popover open at the time of redirecting, these are still displayed on the screen until they are manually closed. Is there any way of detecting any open popovers and closing them all?
I've seen that you can reference ion-select like so:
`@ViewChild('myselect') select: Select;`
but my select fields are setup dynamically in a form so there's no way of knowing how many select fields will be set up.
I have also tried removing the elements manually with javascript, but for some reason this prevents the user from opening the ion-select popovers when they start to use the app again.
Thanks for any help.<issue_comment>username_1: You are correct in your thinking.
`AngularFire` does not have an API function such as `off()` like the regular [JavaScript library](https://firebase.google.com/docs/database/web/read-and-write#detach_listeners) does. `off()`, in the JavaScript library, would be used remove the listener on the database.
Using `unsubscribe()` is the correct way to achieve what you want in `AngularFire`.
More can be read [here](https://github.com/angular/angularfire2/issues/380).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Yep! Calling unsubscribe will in fact call the `.off()` method under the hood. You can see it [here in the source code](https://github.com/angular/angularfire2/blob/master/src/database/observable/fromRef.ts#L26).
```
return new Observable(subscriber => {
const fn = ref[listenType](event, (snapshot, prevKey) => {
subscriber.next({ snapshot, prevKey });
if (listenType == 'once') { subscriber.complete(); }
}, subscriber.error.bind(subscriber));
if (listenType == 'on') {
// return a method for unsubscribing the listener
return { unsubscribe() { ref.off(event, fn)} };
} else {
return { unsubscribe() { } };
}
})
```
Upvotes: 2 |
2018/03/22 | 1,057 | 4,551 | <issue_start>username_0: I am using ActiveMq with SpringBoot, to send every record from large csv file to another service. I am loading records to a map and then in a for each loop I send records to ActiveMq Queue.
My problem is that, ActiveMq wont let any consumer to take record from queue, until all records from my map are sent to ActiveMq.
Can I configurate ActiveMq to allow consuming message immediately after being put on queue (and not wating for some kind of commit transaction)?
Here's my ActiveMq Config:
```
@EnableJms
@Configuration
public class JmsConfig implements JmsListenerConfigurer {
@Autowired
private JmsErrorHandler jmsErrorHandler;
@Autowired
private MessageConverter messageConverter;
@Autowired
private DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory;
@Autowired
private DefaultMessageHandlerMethodFactory handlerMethodFactory;
@Autowired
private JsonMessageConverter jsonMessageConverter;
@Value("${spring.activemq.broker-url}")
private String brokerUrl;
@Value("${spring.activemq.user}")
private String username;
@Value("${spring.activemq.password}")
private String password;
@Bean
public ActiveMQConnectionFactory activeMQConnectionFactory() {
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(username, password, brokerUrl);
activeMQConnectionFactory.setUseAsyncSend(true);
return activeMQConnectionFactory;
}
@Bean
public DefaultJmsListenerContainerFactory defaultJmsListenerContainerFactory() {
return new DefaultJmsListenerContainerFactory();
}
@Bean
public JmsListenerContainerFactory jmsListenerContainerFactory(ActiveMQConnectionFactory activeMQConnectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
defaultJmsListenerContainerFactory.setErrorHandler(jmsErrorHandler);
configurer.configure(defaultJmsListenerContainerFactory, activeMQConnectionFactory);
return defaultJmsListenerContainerFactory;
}
@Bean
public DefaultMessageHandlerMethodFactory handlerMethodFactory() {
DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setMessageConverter(messageConverter);
return factory;
}
@Bean
public MessageConverter messageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setObjectMapper(createJacksonObjectMapper());
return converter;
}
@NotNull
private ObjectMapper createJacksonObjectMapper() {
return Jackson2ObjectMapperBuilder
.json()
.modules(new JavaTimeModule())
.build();
}
@Override
public void configureJmsListeners(@NotNull JmsListenerEndpointRegistrar registrar) {
registrar.setMessageHandlerMethodFactory(handlerMethodFactory);
}
@Bean
public JmsTemplate createJmsTemplate(ActiveMQConnectionFactory activeMQConnectionFactory) {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setMessageConverter(jsonMessageConverter);
jmsTemplate.setConnectionFactory(activeMQConnectionFactory);
jmsTemplate.setDeliveryPersistent(false);
return jmsTemplate;
}
```
}
I am sending messages with following code:
```
public void sendRecordToLogbook(Record record) {
jmsTemplate.convertAndSend(logbookDestination, record);
}
```<issue_comment>username_1: You are correct in your thinking.
`AngularFire` does not have an API function such as `off()` like the regular [JavaScript library](https://firebase.google.com/docs/database/web/read-and-write#detach_listeners) does. `off()`, in the JavaScript library, would be used remove the listener on the database.
Using `unsubscribe()` is the correct way to achieve what you want in `AngularFire`.
More can be read [here](https://github.com/angular/angularfire2/issues/380).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Yep! Calling unsubscribe will in fact call the `.off()` method under the hood. You can see it [here in the source code](https://github.com/angular/angularfire2/blob/master/src/database/observable/fromRef.ts#L26).
```
return new Observable(subscriber => {
const fn = ref[listenType](event, (snapshot, prevKey) => {
subscriber.next({ snapshot, prevKey });
if (listenType == 'once') { subscriber.complete(); }
}, subscriber.error.bind(subscriber));
if (listenType == 'on') {
// return a method for unsubscribing the listener
return { unsubscribe() { ref.off(event, fn)} };
} else {
return { unsubscribe() { } };
}
})
```
Upvotes: 2 |
2018/03/22 | 465 | 1,447 | <issue_start>username_0: I had a case that I can not figure out how to solve.
I have a Bootstrap 3 section where the video is in the center.
I need to add one image to the left of the video edge, the second image to the right of the video edge. Just like I schemed in the picture.
I tried to do this with `position: absolute`; and everything was fine, but when the screen is scaling, problems occurs. How do I make the images look like they are on the image, but was everything okay with responsiveness?
[](https://i.stack.imgur.com/yo6AV.jpg)
```html


```<issue_comment>username_1: You can do this by splitting `sm-12` to a *2+8+2*
```css
.pl-0 {
padding-left: 0 !important;
}
.pr-0 {
padding-right: 0 !important;
}
```
```html


```
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
Hi Since you are using bootstrap, please align your code with bootstrap grid system,
img{
width:30px;height:30px;
}
.embed-responsive{
width:100%;
}


You can style the height and width of image as per your need. This makes your website looks responsive and good looking.
Happy coding !! :)
```
Upvotes: 0 |
2018/03/22 | 1,924 | 7,771 | <issue_start>username_0: So as the title suggests, I'd like to dynamically add `colspan="100"` to any lonely cell in a table row using jquery.
I'm using a wordpress plugin to add a table to a page, but it doesn't allow for the use of colspan, so I am hiding any empty cells with jquery.
The problem occurs when there is only one cell being used in a row. I'd like it to span `100%`.
I need to be able to count each visible cell in each row and if there is only one, add `.attr('colspan', '100')` to that one cell so that it fills the row.
Any ideas? Thanks
This is what I am generating with wordpress.
```js
$(document).ready(function() {
$('.curriculum table tr').each(function() {
$('td').each(function() {
var cellText = $.trim($(this).text());
var $cellExp = $(this).closest('td').prev();
if (cellText.length == 0) {
$(this).hide();
$cellExp.attr('colspan', '2');
}
});
});
});
```
```html
| | | | | | |
| --- | --- | --- | --- | --- | --- |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit |
| | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | | | |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | |
```<issue_comment>username_1: Here is a script.
```
$(document).ready(function () {
$('.curriculum table tr').each(function () {
$('td').each(function () {
var cellText = $.trim($(this).text());
if (cellText.length == 0) {
$(this).remove();
}
});
if ($(this).children("td").length == 1) {
$(this).children("td").attr("colspan", "100")
}
});
});
```
[Codepen](https://codepen.io/smitraval27/pen/GxmPKe)
Upvotes: 2 <issue_comment>username_2: I would start from all cells that are followed by an empty cell and then remove any empty cells that follow, whilst adding the colspan (comments in code):
```js
$('td').filter(function() {
return $(this).next().text().trim() === ''; // get all tds that have an empty cell after them
}).each(function() {
var $original = $(this); // get the original cell
if (!$original.hasClass('remove')) { // check if the cell has already been marked for removal
var counter = 1,
$item = $original;
do {
if ($item.next().text().trim() === '') {
// next cell is empty, increment colspan and reset do...while for next cell
counter++;
$item = $item.next().addClass('remove');
}
} while ($item.next().length && $item.next().text().trim() === '');
$original.attr('colspan', counter); // set the colspan on the first cell
}
});
$('.remove').remove();
// merge any previous empty cells
$('td').filter(function() {
$prev = $(this).prev();
return $prev.length && $prev.text().trim() === ''; // get all tds that have an empty cell before them - should only be ones that start the row
}).each(function() {
var $original = $(this),
$prev = $original.prev();
var colspan = getColspan($original) + getColspan($prev);
$original.attr('colspan', colspan);
$prev.remove();
});
function getColspan($elem) {
var attr = $elem.attr('colspan');
if (typeof attr !== typeof undefined && attr !== false) {
return parseInt(attr);
}
return 1;
}
```
```css
td {
vertical-align: top;
border: 1px solid black;
}
```
```html
| | | | | | |
| --- | --- | --- | --- | --- | --- |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit |
| | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | | | |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | |
```
Upvotes: 1 <issue_comment>username_3: Using `colspan = 100` is not a good solution at first. Counting max td count then using it as colspan may be a better idea. If you don't want to hide other cells when there is more then 1 visible cell in a row, you can easly modify this code to achieve it.
```js
$(document).ready(function() {
var maxTdCount = 0;
$('.curriculum table tr').each(function() {
$('td').each(function() {
var cellText = $.trim($(this).text());
if (cellText.length == 0) {
$(this).hide();
}
});
if($(this).find("td:visible").length > maxTdCount)
{ maxTdCount = $(this).find("td").length;}
});
$('.curriculum table tr').each(function() {
if($(this).find("td:visible").length == 1)
{
$(this).find("td").attr("colspan", maxTdCount);
}
});
});
```
```css
td{border:1px solid black}
```
```html
| | | | | | |
| --- | --- | --- | --- | --- | --- |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit |
| | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | | | |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | |
| Lorem ipsum dolor sit amet, consectetur adipisicing elit | | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | Lorem ipsum dolor sit amet, consectetur adipisicing elit | |
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,376 | 5,143 | <issue_start>username_0: I am writing API login register system for my app.
I have created a controller for login and register, so I can create my user from postmen and log in from there but when I try to call `my get details` method it's returning
>
> as a method not allowed an exception
>
>
>
here is my Controller
```
php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
class PassportController extends Controller
{
//
public $successStatus = 200;
public function register(Request $request){
$validator = Validator::make($request-all(), [
'name' => 'required',
'email' => 'required|email',
'password' => '<PASSWORD>',
'c_password' => '<PASSWORD>|same:password',
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
$input = $request->all();
$input['password'] = <PASSWORD>($input['<PASSWORD>']);
$user = User::create($input);
$success['token'] = $user->createToken('MyApp')->accessToken;
$success['name'] = $user->name;
return response()->json(['success'=>$success], $this->successStatus);
}
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')->accessToken;
return response()->json(['success' => $success], $this->successStatus);
}
else{
return response()->json(['error'=>'Unauthorised'], 401);
}
}
public function getDetails()
{
$user = Auth::user();
return response()->json(['success' => $user], $this->successStatus);
}
}
```
*api.php*
```
php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')-get('/user', function (Request $request) {
return $request->user();
});
Route::post('register', 'API\PassportController@register')->name('register');
Route::post('login', 'API\PassportController@login')->name('login');
Route::group(['middleware' => 'auth:api'], function(){
Route::post('details', 'API\PassportController@getDetails');
});
```
here is my postmen screenshot
[](https://i.stack.imgur.com/6Z65K.jpg)
you can share me your thoughts or any ideas<issue_comment>username_1: Please add your function url in app->http->Middleware->VerifyCsrfToken in $except .
laravel need csrf . if you pass data from outside it will not pass csrf so at that time you have to define for this function no csrf required .
Upvotes: 2 <issue_comment>username_2: Are you using passport with laravel? If yes there might be multiple issues causing this.
I would like to see what you get when you click on application frames, but here are some of the more common issues i found myself dealing with
General issues I know of (regardless of technology)
1. method is not public
2. Authorization and Accept should be in table Headers in postman [](https://i.stack.imgur.com/OPNTx.png)
when using the Authorization it need to be like this: Headers tab
key: Authorization
Value: Bearer <KEY>
where this gibberish is your access token without any commas
3. check you server and laravel logs. Sometimes postman messes up and send get instead of post requests and the other way around
4. If you get Unauthenticated error
4.1 follow these steps here: <https://laravel.com/docs/5.6/passport>
4.2 copy the client secret from the db/command line
4.3 use this endpoint in the picture [](https://i.stack.imgur.com/0xWw2.png)
{{url\_key}} id the address to my site ex: demo.dev or htttp://localhost. I'm not sure about using locahost (I only developed laravel on vagrant so i don't know what issues may arise from that)
Headers should be empty in this case
4.4 use the token to authenticate
5. Make sure VerifyCsrfToken class looks like this
>
>
> ```
> class VerifyCsrfToken extends BaseVerifier
> {
> /**
> * The URIs that should be excluded from CSRF verification.
> *
> * @var array
> */
> protected $except = [
> 'api/*'
> ];
> }
>
> ```
>
>
Upvotes: 2 <issue_comment>username_3: You method is `getDetails()` while your route is `post`
```
Route::post('details', 'API\PassportController@getDetails');
```
Try changing `getDetails()` to `postDetails()`
and change route as
```
Route::post('details', 'API\PassportController@postDetails');
```
Upvotes: 2 |
2018/03/22 | 790 | 2,857 | <issue_start>username_0: I would like to obtain `int[].class` from Matlab. Unfortunately, Matlab does not allow this syntax. Simultaneously, I allows to call any Java functions or access static members as is.
For example, I can't call
```
int.class
```
but can
```
java.lang.Integer.TYPE
```
Is it possible to find `int[].class` somewhere in JDK API in the same way?<issue_comment>username_1: So I tried this in a jshell:
```
int[].class.getName()
```
And that yielded:
```
[I
```
And tried to reverse it:
```
Class.forName("[I")
```
And that seemed to parse it: `class [I`
So you could try `Class.forName("[I")`. And that seems to work just fine:
```
Class.forName("[I").isArray() // outputs true
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use the [Apache Commons](https://commons.apache.org) package in order to achieve your goal. Signally, [ClassUtils.getClass](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ClassUtils.html#getClass-java.lang.String-) is what you are looking for:
```
>> org.apache.commons.lang.ClassUtils.getClass('int[]')
ans =
class [I
```
For the sake of analyzing things deeply:
```
>> ans.get()
Annotation: 0
Annotations: [0×1 java.lang.annotation.Annotation[]]
AnonymousClass: 0
Array: 1
CanonicalName: 'int[]'
Class: [1×1 java.lang.Class]
ClassLoader: []
Classes: [0×1 java.lang.Class[]]
ComponentType: [1×1 java.lang.Class]
Constructors: [0×1 java.lang.reflect.Constructor[]]
DeclaredAnnotations: [0×1 java.lang.annotation.Annotation[]]
DeclaredClasses: [0×1 java.lang.Class[]]
DeclaredConstructors: [0×1 java.lang.reflect.Constructor[]]
DeclaredFields: [0×1 java.lang.reflect.Field[]]
DeclaredMethods: [0×1 java.lang.reflect.Method[]]
DeclaringClass: []
EnclosingClass: []
EnclosingConstructor: []
EnclosingMethod: []
Enum: 0
EnumConstants: []
Fields: [0×1 java.lang.reflect.Field[]]
GenericInterfaces: [2×1 java.lang.Class[]]
GenericSuperclass: [1×1 java.lang.Class]
Interface: 0
Interfaces: [2×1 java.lang.Class[]]
LocalClass: 0
MemberClass: 0
Methods: [9×1 java.lang.reflect.Method[]]
Modifiers: 1041
Name: '[I'
Package: []
Primitive: 0
ProtectionDomain: [1×1 java.security.ProtectionDomain]
Signers: []
SimpleName: 'int[]'
Superclass: [1×1 java.lang.Class]
Synthetic: 0
TypeParameters: [0×1 java.lang.reflect.TypeVariable[]]
```
Upvotes: 1 |
2018/03/22 | 1,404 | 5,126 | <issue_start>username_0: When I add variable products to my shop I got a price range on the catalogue and product page. I found a way to show only minimum price instead of the price range. It works great. (see code below).
But now I would like to hide those minimum price on the product pages (but only on product pages!). Because there is already a price showing when picking a product from the variable list. So it will be a bit confusing and bad looking if there is 2 price displaying. (see picture below).
My code actually:
```
add_filter('woocommerce_variable_price_html', 'custom_variation_price', 10, 2);
function custom_variation_price( $price, $product ) {
$price = '';
$price .= wc_price($product->get_price());
return $price;
}
```
Any idea how this can be done ?
There is two price in variable product single pages:
[](https://i.stack.imgur.com/F1HoK.jpg)<issue_comment>username_1: I dont know why the answer of LoicTheAztec dont work with me. But I found a solution. In
```
wp-content/plugins/woocommerce/templates/single-product/price.php
```
I have replaced :
```
php echo $product-get\_price\_html(); ?>
```
with this one :
```
php if ( ! $product-is_type( 'variable' ) ) : ?>
php echo $product-get\_price\_html(); ?>
php endif; ?
```
This together with the code inside my question, it is now showing minimum price of variable products everywhere but no price at all in the product page of variable products.
Upvotes: 1 <issue_comment>username_2: Since the price range is part of the `woocommerce_single_product_summary` hook, we can achieve this by removing the `woocommerce_template_single_price` callback function from the action hook `woocommerce_single_product_summary`.
**This code will remove the price range below product title for variable products only, on single product pages.**
```
/** Remove price variation below title for variable products on single product page **/
add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
global $product;
if ( $product->is_type( 'variable' ) ) {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
}
}
```
Answer was found on this thread, with a very good explanation:
[Disable Variable Product Price Range on the WooCommerce Single Product Pages Only](https://stackoverflow.com/questions/44447112/disable-variable-product-price-range-on-the-woocommerce-single-product-pages-onl)
**This code will remove the price below product title for single products only, on single product pages.**
```
/** Remove price below title for single products on single product page **/
add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
global $product;
if ( $product->is_type( 'simple' ) ) {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
}
}
```
**This code will remove the price below product title indifferent from product type, on single product pages.**
```
/** Remove price below title for all product types on single product page **/
add_action( 'woocommerce_before_single_product', 'my_remove_variation_price' );
function my_remove_variation_price() {
global $product;
if ( $product ) {
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price' );
}
}
```
The code to be added in your `function.php` file of your active `child-theme`. It is not necessary to use all the codes. Use only one, and change the `if` statement to your needs.
Upvotes: 0 <issue_comment>username_3: You can use this code to modify variable product on loop and single product to display the highest price:
```
/* Modify variable product to display the highest price*/
add_filter( 'woocommerce_variable_price_html', 'custom_min_max_variable_price_html', 10, 2 );
function custom_min_max_variable_price_html( $price, $product ) {
$prices = $product->get_variation_prices( true );
$count = (int) count( array_unique( $prices['price'] ));
// When all variations prices are the same
if( $count === 1 )
return $price;
$max_price = max( $prices['price'] );
$max_keys = array_search( $max_price, $prices['price'] );
$max_reg_price = $prices['regular_price'][$max_keys];
$max_price_html = wc_price( $max_price ) . $product->get_price_suffix();
// When max price is on sale (Can be removed)
if( $max_reg_price != $max_price ) {
$max_price_html = '' . $max\_price\_html . '';
$max_price_reg_html = '~~' . wc\_price( $max\_reg\_price ) . $product->get\_price\_suffix() . '~~';
$max_price_html = $max_price_reg_html . ' ' . $max_price_html;
}
$price = sprintf( __( ' %s', 'woocommerce' ), $max_price_html );
return $price;
}
```
I check it and work on my site. You can put it at the **function.php** file on your child-theme.
Upvotes: 0 |
2018/03/22 | 767 | 3,156 | <issue_start>username_0: I am working on one Asp.net application. I have one **Email Reminder form** in which my Client's Email ID & checkbox is provided. Admin will select the checkbox & press the **send reminder** button & the mail will be sent to all the checked checkboxes i.e. to my clients.but in this form I have one Textbox say **Sender** in which Admin will put sender Email ID & from that Email ID all the email will be sent to my clients.
How can I send mail without password as admin can use any email ID from our company email IDs as per his requirement. How can I achieve this
here is my code
```
SmtpClient smtpClient = new SmtpClient
{
Host = "smtp.office365.com",
Port = 25,
UseDefaultCredentials = true,
EnableSsl = true,
Credentials = new NetworkCredential("<EMAIL>", "123456")
};
var mailMessage = new MailMessage();
mailMessage.Subject = subject;
mailMessage.From = new MailAddress("<EMAIL>");
mailMessage.IsBodyHtml = true;
mailMessage.Body = body;
//"Email from : [" + from + "](mailto:" + from + ")
For Form Name : ";
mailMessage.To.Add(new MailAddress(tomail));
smtpClient.Send(mailMessage);
mailMessage.Dispose();
smtpClient.Dispose();
```<issue_comment>username_1: Ok, it sounds like you want one of two things.
You either want to spoof the email address, in which case you will actually change the From header field. This will show the recipient the email address and name that you desire.
```
mail.From = new MailAddress("<EMAIL>", "<NAME>" );
```
The other possible answer is that you want to actually to send the email from your own login credentials, but have it be sent 'from' an account that you have exchange permissions to send from. (This is an MS Outlook / Exchange specific answer) - You would need to send via the MS Outlook interop API
```
// Retrieve the account that has the specific SMTP address.
Outlook.Account account = GetAccountForEmailAddress(oApp , "<EMAIL>");
// Use this account to send the e-mail.
oMsg.SendUsingAccount = account;
```
This would ensure that only someone who has appropriate permissions to send 'from' an address, can do so - as it offloads the authentication levels checking to MS Outlook.
Upvotes: 0 <issue_comment>username_2: Create a new user for the sole purpose of sending mail from your web application, and configure its credentials in your application.
Then configure that user so it may send on behalf of the user or group you want to let the email originate from.
You can use SMTP Client Submission or SMTP Relay, see [How to set up a multifunction device or application to send email using Office 365](https://support.office.com/en-us/article/How-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4).
Upvotes: 1 |
2018/03/22 | 672 | 2,417 | <issue_start>username_0: I am working on a Facebook Messenger bot that I am hosting on Heroku.
In my `package.json` I've specified my node version and NPM version as follows:
```
"engines": {
"node": "8.10.0",
"npm": "5.7.1"
},
```
When I do a push to heroku using `git push heroku master`, I see the following:
```
remote: Resolving node version 8.10.0...
remote: Downloading and installing node 8.10.0...
remote: Bootstrapping npm 5.7.1 (replacing 5.6.0)...
remote: npm 5.7.1 installed
```
What do I need to do to make sure that node version 8.10.0 and npm 5.7.1 are always installed so it doesn't need to do this with each push? I assume this refers to the versions on the server rather than on my local machine?<issue_comment>username_1: Ok, it sounds like you want one of two things.
You either want to spoof the email address, in which case you will actually change the From header field. This will show the recipient the email address and name that you desire.
```
mail.From = new MailAddress("<EMAIL>", "<NAME>" );
```
The other possible answer is that you want to actually to send the email from your own login credentials, but have it be sent 'from' an account that you have exchange permissions to send from. (This is an MS Outlook / Exchange specific answer) - You would need to send via the MS Outlook interop API
```
// Retrieve the account that has the specific SMTP address.
Outlook.Account account = GetAccountForEmailAddress(oApp , "<EMAIL>");
// Use this account to send the e-mail.
oMsg.SendUsingAccount = account;
```
This would ensure that only someone who has appropriate permissions to send 'from' an address, can do so - as it offloads the authentication levels checking to MS Outlook.
Upvotes: 0 <issue_comment>username_2: Create a new user for the sole purpose of sending mail from your web application, and configure its credentials in your application.
Then configure that user so it may send on behalf of the user or group you want to let the email originate from.
You can use SMTP Client Submission or SMTP Relay, see [How to set up a multifunction device or application to send email using Office 365](https://support.office.com/en-us/article/How-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4).
Upvotes: 1 |
2018/03/22 | 831 | 3,026 | <issue_start>username_0: I am facing this issue since last OS update.
I am deploying Mule app with the help of anypoint-cli runtime-mgr cmdlet.
Here is the sample code I am using for the deployment in Execite Shell task of Jenkins job.
```
export ANYPOINT_USERNAME=username@env
ifexist="`anypoint-cli runtime-mgr cloudhub-application list|grep -iapplication-name|wc -l`"
if [ $ifexist == 0 ]
then
echo "Deploying the application ... " anypoint-cli runtime-mgr cloudhub-application deploy application-name application-artifact.zip
else
echo "Updating & ReDeploying the application ... "
anypoint-cli runtime-mgr cloudhub-application modify application-name application-artifact.zip anypoint-cli runtime-mgr cloudhub-application start application-name
fi
```
I am getting following error:
>
> [workspace] $ /bin/sh /tmp/jenkins72443737290339703.sh channel stopped
> /bin/bash stty: when specifying an output style, modes may not be set
> /usr/lib/node\_modules/anypoint-cli/node\_modules/readline-sync/lib/read.sh:
> line 48: /dev/tty: No such device or address stty: standard input:
> Inappropriate ioctl for device Build step 'Execute shell' marked build
> as failure Finished: FAILURE
>
>
>
The Shell script runs perfectly fine when run from terminal. Not sure what is happening when it is running in background.
Has anybody faced this issue?<issue_comment>username_1: Ok, it sounds like you want one of two things.
You either want to spoof the email address, in which case you will actually change the From header field. This will show the recipient the email address and name that you desire.
```
mail.From = new MailAddress("<EMAIL>", "<NAME>" );
```
The other possible answer is that you want to actually to send the email from your own login credentials, but have it be sent 'from' an account that you have exchange permissions to send from. (This is an MS Outlook / Exchange specific answer) - You would need to send via the MS Outlook interop API
```
// Retrieve the account that has the specific SMTP address.
Outlook.Account account = GetAccountForEmailAddress(oApp , "<EMAIL>");
// Use this account to send the e-mail.
oMsg.SendUsingAccount = account;
```
This would ensure that only someone who has appropriate permissions to send 'from' an address, can do so - as it offloads the authentication levels checking to MS Outlook.
Upvotes: 0 <issue_comment>username_2: Create a new user for the sole purpose of sending mail from your web application, and configure its credentials in your application.
Then configure that user so it may send on behalf of the user or group you want to let the email originate from.
You can use SMTP Client Submission or SMTP Relay, see [How to set up a multifunction device or application to send email using Office 365](https://support.office.com/en-us/article/How-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4).
Upvotes: 1 |
2018/03/22 | 483 | 1,776 | <issue_start>username_0: I have a sample package.json for my application,
```
dependencies : {
P1 : “^1.0.0” // has a peer dependency of p3 v1
P2 : “^1.0.0” // has a peer dependency of p3 v2
}
```
P1 and P2 has peer dependency on P3, but on deferent versions.
(e.g P1 has peer dependency of P3 V1 and P2 has peer dependency of P3 V2 )
(I don’t have access to p1 p2 source code. )
Is there any way to resolve such scenarios is my application’s package.json for not showing warning messages?<issue_comment>username_1: UPDATE: This answer is only applicable to regular dependencies, NOT peer dependencies. Please see my new answer for a description of the difference and an answer for the case of P3 being a peer dependency.
I'm guessing you're running an old version of npm. Newer versions of npm should be able to handle multiple versions of the same dependency just fine.
[How can I update Node.js and npm to the next versions?](https://stackoverflow.com/questions/6237295/how-can-i-update-node-js-and-npm-to-the-next-versions)
Upvotes: -1 <issue_comment>username_1: My previous answer failed to realize the difference between dependencies and peer dependencies. For those who may also not realize the difference [another answer describes it well](https://stackoverflow.com/a/34645112/7650673):
>
> TL;DR: peerDependencies is for dependencies that are exposed to (and expected to be used by) the consuming code, as opposed to "private" dependencies that are not exposed, and are only an implementation detail.
>
>
>
If P1 and P2 indeed both have peer dependencies on incompatible versions of P3 you will need to either find versions of P1 and P2 with compatible peer dependencies of P3 or abandon the use of either P1 or P2.
Upvotes: 2 |
2018/03/22 | 462 | 1,772 | <issue_start>username_0: please, i need help!!! i am really new on all this installation i try to install ruby mine and it s give me all time this error 'Cucumber gem ist't installed for ruby -2.0.0 - p 481 SDC' i have mac and install one universal version of ruby when i put it on terminal - it s always give me this answer
```
tests-MBP:~ annasena$ gem install cucumber
ERROR: While executing gem ... (Gem::FilePermissionError)
You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.
```<issue_comment>username_1: UPDATE: This answer is only applicable to regular dependencies, NOT peer dependencies. Please see my new answer for a description of the difference and an answer for the case of P3 being a peer dependency.
I'm guessing you're running an old version of npm. Newer versions of npm should be able to handle multiple versions of the same dependency just fine.
[How can I update Node.js and npm to the next versions?](https://stackoverflow.com/questions/6237295/how-can-i-update-node-js-and-npm-to-the-next-versions)
Upvotes: -1 <issue_comment>username_1: My previous answer failed to realize the difference between dependencies and peer dependencies. For those who may also not realize the difference [another answer describes it well](https://stackoverflow.com/a/34645112/7650673):
>
> TL;DR: peerDependencies is for dependencies that are exposed to (and expected to be used by) the consuming code, as opposed to "private" dependencies that are not exposed, and are only an implementation detail.
>
>
>
If P1 and P2 indeed both have peer dependencies on incompatible versions of P3 you will need to either find versions of P1 and P2 with compatible peer dependencies of P3 or abandon the use of either P1 or P2.
Upvotes: 2 |
2018/03/22 | 1,879 | 7,082 | <issue_start>username_0: i am facing a problem with server side validation with php. The problem is that it always shows the validation error message even with valid values. For example on the username field if i enter something that contains no special symbols it still enters the if statement and shows the error message: "User name must not contains Special characters". The regex seems to be working fine so i think it is a logic fault. Here is my php code:
```
php
/**
* Include our MySQL connection.
*/
require 'connect.php';
$error = '';
try {
//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
if (isset($_POST['register'])) {
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$firstName = $form['firstName'];
$lastName = $form['lastName'];
$address = $form['address'];
$email = $form['email'];
$age = $form['age'];
$phone = $form['phone'];
//Retrieve the field values from our registration form.
$username = !empty($_POST['username']) ? trim($_POST['username']) : null;
$password = !empty($_POST['password']) ? trim($_POST['password']) : null;
//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
//Validations username
if (strlen($username) < 4 || strlen($username) 8 || empty($username)) {
throw new Exception("User name must be between 4 an 8 symbols.");
}
$patern = '[A-Za-z0-9]+';
if (!preg_match($patern, $form['username'])) {
throw new Exception("User name must not contains Special characters.");
}
$patern = '^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$';
//Validation email
if (!preg_match($patern, $email)) {
throw new Exception("Please fill valid email.");
}
//Validation password
if (strlen($password < 8 || strlen($password > 15) || empty($password))) {
throw new Exception("Password must be between 8 an 15 symbols.");
}
$patern = '(?=(.*\d){2,})(?=.*[A-Z]{1,})(?=.*[a-zA-Z]{2,})(?=.*[!@~#$%^&?]{1,})[0-9a-zA-Z!@~#?$^%&`]{8,15}';
if (!preg_match($patern, $password)) {
throw new Exception("Password must contains at least 1 special symbol at least 1 uppercase letter at least 2 numbers at least 3 letters.");
}
if (strlen($password < 8 || strlen($password > 15) || empty($password))) {
throw new Exception("Password must contains at least 1 special symbol at least 1 uppercase letter at least 2 numbers at least 3 letters.");
}
if (strlen($phone) != 10) {
throw new Exception("Phone must be 10 numbers.");
}
//Now, we need to check if the supplied username already exists.
//Construct the SQL statement and prepare it.
$sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':username', $username);
//Execute.
$stmt->execute();
//Fetch the row.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if ($row['num'] > 0) {
throw new Exception('That username already exists!');
}
$sql = "SELECT COUNT(email) AS test FROM users WHERE email = :email";
$stmt = $pdo->prepare($sql);
//Bind the provided username to our prepared statement.
$stmt->bindValue(':email', $email);
//Execute.
$stmt->execute();
//Fetch the row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
if ($result['test'] > 0) {
throw new Exception('That email already exists!');
}
//Hash the password as we do NOT want to store our passwords in plain text.
$passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));
//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
$sql = "INSERT INTO users (username, password, email, phone, address, first_name, last_name, age)
VALUES (:username, :password,:email, :phone, :address, :first_name, :last_name, :age)";
$stmt = $pdo->prepare($sql);
//Bind our variables.
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $passwordHash);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':phone', $phone);
$stmt->bindValue(':address', $address);
$stmt->bindValue(':first_name', $firstName);
$stmt->bindValue(':last_name', $lastName);
$stmt->bindValue(':age', $age);
//Execute the statement and insert the new account.
$result = $stmt->execute();
//If the signup process is successful.
if ($result) {
$_SESSION['username'] = $firstName;
header('Location: login.php');
}
}
} catch (Exception $exception) {
$error = $exception->getMessage();
}
?>
```
And the html form:
```
Register
php if ($error) : ?
= $error ?
-----------
php endif; ?
php $error = ''; ?
I have read and agree to the [Terms and Conditions
\*](https://www.un.org/Depts/ptd/terms-and-conditions-agreement)
GDPR Agreement \*
\* Mandatory fields
Register
```<issue_comment>username_1: The problem is with your regex:
```
$patern = '[A-Za-z0-9]';
```
You are missing the delimiters and you should fix the pattern to the start and the end as now it will only fail if the string contains *only* invalid characters:
```
$patern = '#^[A-Za-z0-9]+$#';
^ delimiter
^ end of string
^ 1 or more characters
^ beginning of string
^ delimiter
```
Alternatively you could search for invalid characters instead by inverting the character group:
```
$patern = '#[^A-Za-z0-9]#';
// ^ negate the character class
// or case insensitive
$patern = '#[^a-z0-9]#i';
// Change the condition
if (preg_match($patern, $form['username'])) {
// At least 1 invalid character found
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: ```
$patern = '#[^a-z0-9]#i';
if (preg_match($patern, $form['username'])) {
throw new Exception("User name must not contains Special characters.");
}
```
just replace this block
Upvotes: 0 |
2018/03/22 | 592 | 1,975 | <issue_start>username_0: I'm trying to upload files to Digitalocean Spaces using Laravel file system. I followed a tutorial on youtube but I keep getting an error from Laravel saying "Endpoints must be full URIs and include a scheme and host".
This is the tutorial that I followed:
<https://www.youtube.com/watch?v=vFwy-vB_d_k&t=776s>
Any help would be appreciated.
In the config/filesystems.config I have added this
```
'do_spaces' => [
'driver' => 's3',
'key' => env('DO_SPACES_KEY'),
'secret' => env('DO_SPACES_SECRET'),
'region' => env('DO_SPACES_REGION'),
'bucket' => env('DO_SPACES_BUCKET'),
'endpoint' => env('DO_SPACES_ENDPOINT'),
],
```
In my .env file
```
DO_SPACES_KEY= secret
DO_SPACES_SECRET= secret
DO_SPACES_REGION=nyc3
DO_SPACES_BUCKET= afghanjamtest
DO_SPACES_ENDPOINT= https://nyc3.digitaloceanspaces.com
```
This is my code for my controller
```
$input=$request->all();
$songs=array();
if($files=$request->file('files')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$path = Storage::disk('do_spaces')->putFileAs('uploads', $file, $name);
// $file->move('songs',$name);
$songs[]=$name;
}
}
return redirect('/show');
}
```<issue_comment>username_1: configuration is good but You need to delete caches from config.
1. close server if running (because you also need to restart server to env changes take effect)
2. php artisan clear:data
3. php artisan cache:clear
Now run server again, and hope it will work.
Upvotes: -1 <issue_comment>username_2: Change yours env variables:
```
DO_SPACES_KEY='secret'
DO_SPACES_SECRET='secret'
DO_SPACES_REGION='nyc3'
DO_SPACES_BUCKET='afghanjamtest'
DO_SPACES_ENDPOINT='https://nyc3.digitaloceanspaces.com'
```
Whitout spaces and between ' or " because sometimes the secret has a char # and it is a special char in env files.
Upvotes: 2 |
2018/03/22 | 1,099 | 4,361 | <issue_start>username_0: Being new to Swift this is what I found:
```
enum HttpMethod {
static let post = "POST"
static let get = "GET"
}
// can assign to string property.
request.httpMethod = HttpMethod.post // --> "POST"
```
The reason to use a caseless `enum` and not a `struct` makes sense to me after reading [this](https://stackoverflow.com/questions/38585344/swift-constants-struct-or-enum/39005493#39005493) but is not the thing I'm interested here.
Having a strong C# background this is how I would implement it:
```
enum HttpMethod: String {
case post = "POST"
case get = "GET"
}
// I'd even consider this alternatively:
enum HttpMethod: String {
case post
case get
}
// Must retrieve string value
request.httpMethod = HttpMethod.post.rawValue // --> "POST" or "post"
```
The second version requires the usage of `rawValue` but it treats the enum as a *real* enum. Coming from C# I'm used to using `.ToString()` on enum values.
Is this all just coming down to personal preference and Swift's conventions to use a caseless enum instead of actual cases + rawValue, or is there another (technical) reason to prefer the first over the second version?<issue_comment>username_1: Whether to use enums with string values depends on the problem you are trying to solve. If you need an unbounded set of string cases, it might be better to declare a struct with a single `let rawValue: String` property, and for known values, declare static instances of the known values. That is what Apple frameworks do for things like [NSNotification.Name](https://developer.apple.com/documentation/foundation/nsnotification.name).
Sidebar regarding enum rawValue: enums declared with `:String` are automatically CustomStringConvertible (similar to .toString()), using `"\(enum-name)"`, rather than .rawValue, but that prints it in the case of the enum, not the string. I sometimes implement CustomStringConvertible to print the rawValue instead, when I need that.
Upvotes: 0 <issue_comment>username_2: Enum with cases
===============
It is better to create an enum with cases in the following scenarios:
* It is mutually exclusive
* Finite set of values that you know at compile time
* You are the one defining it (If an enum is defined in a framework you wouldn't be able to extend it to add more cases)
Advantage of an enum are:
-------------------------
* Since the values are a finite set, you can write exhaustive switch statements
* cleaner code
Static values:
==============
When a `struct` / `class` is defined in a framework and you want to extend it to add more values.
Example of where this approach is used is `Notification.Name` in `Foundation`
Note:
=====
* enums in swift are quite powerful
* enums can have associated values
* enums can have other functions. (if you are defining states like start, inProgress, finished, you could define a function called next, which could return the next state. start.next()
* if you are in a scenario where values are not mutually exclusive, like it could a combination of values then use OptionSet instead
Conclusion
==========
* It all depends on your intent
* If you know the values before hand and they will not change, then create an `enum`
* If that is not possible then create `static` values.
* If you are creating static values, you are compromising so you don't have to use it in an `enum`, you could define it as a `struct` so that the intent is clearer.
* This is as of now, there is a swift proposal for extendable enums
Upvotes: 4 [selected_answer]<issue_comment>username_3: I do agree that such an implementation is better with cases than not. The other reason caseless enums are useful for is storing constants. It can become tricky deciding how to store constants. Caseless enums provide a type which can not be instantiated/constructed. It is just a means of listing static constant properties which can be accessed like enums.
```
enum Constants {
static let dateFormat: String = "dd.MM.yy"
static let timeFormat: String = "hh:mm:ss a"
static let defaultLocationCoordinates: CLLocationCoordinate2D = CLLocationCoordinate2DMake(-26.204103, 28.047305)
}
class Test {
static func echo() {
print("\(Constants.dateFormat)")
print("\(Constants.timeFormat)")
print("\(Constants.defaultLocationCoordinates)")
}
}
```
Upvotes: 1 |
2018/03/22 | 1,629 | 5,060 | <issue_start>username_0: I've tried to understand when Python strings are identical (aka sharing the same memory location). However during my tests, there seems to be no obvious explanation when two string variables that are equal share the same memory:
```
import sys
print(sys.version) # 3.4.3
# Example 1
s1 = "Hello"
s2 = "Hello"
print(id(s1) == id(s2)) # True
# Example 2
s1 = "Hello" * 3
s2 = "Hello" * 3
print(id(s1) == id(s2)) # True
# Example 3
i = 3
s1 = "Hello" * i
s2 = "Hello" * i
print(id(s1) == id(s2)) # False
# Example 4
s1 = "HelloHelloHelloHelloHello"
s2 = "HelloHelloHelloHelloHello"
print(id(s1) == id(s2)) # True
# Example 5
s1 = "Hello" * 5
s2 = "Hello" * 5
print(id(s1) == id(s2)) # False
```
Strings are immutable, and as far as I know Python tries to re-use existing immutable objects, by having other variables point to them instead of creating new objects in memory with the same value.
With this in mind, it seems obvious that `Example 1` returns `True`.
It's still obvious (to me) that `Example 2` returns `True`.
It's not obvious to me, that `Example 3` returns `False` - am I not doing the same thing as in `Example 2`?!?
I stumbled upon this SO question:
[Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?](https://stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce/1504742#1504742)
and read through <http://guilload.com/python-string-interning/> (though I probably didn't understand it all) and thougt - okay, maybe "interned" strings depend on the length, so I used `HelloHelloHelloHelloHello` in `Example 4`. The result was `True`.
And what the puzzled me, was doing the same as in `Example 2` just with a bigger number (but it would effectively return the same string as `Example 4`) - however this time the result was `False`?!?
I have really no idea how Python decides whether or not to use the same memory object, or when to create a new one.
Are the any official sources that can explain this behavior?<issue_comment>username_1: From [the link you posted](http://guilload.com/python-string-interning/):
>
> **Avoiding large .pyc files**
>
>
> So why does `'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'` not evaluate to `True`? Do you remember the .pyc files you encounter in all your packages? Well, Python bytecode is stored in these files. What would happen if someone wrote something like this `['foo!'] * 10**9`? The resulting *.pyc* file would be huge! In order to avoid this phenomena, sequences generated through peephole optimization are discarded if their length is superior to 20.
>
>
>
If you have the string `"HelloHelloHelloHelloHello"`, Python will necessarily have to store it as it is (asking the interpreter to detect repeating patterns in a string to save space might be too much). However, when it comes to string values that can be computed at parsing time, such as `"Hello" * 5`, Python evaluate those as part of this so-called "peephole optimization", which can decide whether it is worth it or not to precompute the string. Since `len("Hello" * 5) > 20`, the interpreter leaves it as it is to avoid storing too many long strings.
*EDIT:*
As indicated in [this question](https://stackoverflow.com/questions/14493236/when-does-python-compile-the-constant-string-letters-to-combine-the-constant-st), you can check this on the source code in [`peephole.c`](https://github.com/python/cpython/blob/v3.6.8/Python/peephole.c), function `fold_binops_on_constants`, near the end you will see:
```
// ...
} else if (size > 20) {
Py_DECREF(newconst);
return -1;
}
```
*EDIT 2:*
*Actually*, that optimization code has recently been [moved to the AST optimizer](https://github.com/python/cpython/commit/7ea143ae795a9fd57eaccf490d316bdc13ee9065#diff-a33329ae6ae0bb295d742f0caf93c137) for Python 3.7, so now you would have to look into [`ast_opt.c`](https://github.com/python/cpython/blob/v3.7.0/Python/ast_opt.c), function `fold_binop`, which calls now function `safe_multiply`, which checks that the string is no longer than `MAX_STR_SIZE`, [newly defined as 4096](https://github.com/python/cpython/commit/2e3f5701858d1fc04caedefdd9a8ea43810270d2). So it seems that the limit has been significantly bumped up for the next releases.
Upvotes: 4 [selected_answer]<issue_comment>username_2: In Example 2 :
```
# Example 2
s1 = "Hello" * 3
s2 = "Hello" * 3
print(id(s1) == id(s2)) # True
```
Here the value of s1 and s2 are evaluated at compile time.so this will return true.
In Example 3 :
```
# Example 3
i = 3
s1 = "Hello" * i
s2 = "Hello" * i
print(id(s1) == id(s2)) # False
```
Here the values of s1 and s2 are evaluated at runtime and the result is not interned automatically so this will return false.This is to avoid excess memory allocation by creating "HelloHelloHello" string at runtime itself.
If you do intern manually it will return True
```
i = 3
s1 = "Hello" * i
s2 = "Hello" * i
print(id(intern(s1)) == id(intern(s2))) # True
```
Upvotes: 1 |
2018/03/22 | 513 | 2,252 | <issue_start>username_0: I am in the process of building my first live node.js web app. It contains a form that accepts data regarding my clients current stock. When submitted, an object is made and saved to an array of current stock. This stock is then permanently displayed on their website until the entry is modified or deleted.
It is unlikely that there will ever be more than 20 objects stored at any time and these will only be updated perhaps once a week. I am not sure if it is necessary to use MongoDB to store these, or whether there could be a simpler more appropriate alternative. Perhaps the objects could be stored to a JSON file instead? Or would this have too big an implication on page load times?<issue_comment>username_1: The only way to know for sure is test it with a load test. But as you probably read html and js files from the file system when serving web pages anyway, the extra load of reading a few json files shouldn't be a problem.
Upvotes: 1 <issue_comment>username_2: You could potentially store in a JSON file or even in a cache of sorts such as Redis but I still think MongoDB would be your best bet for a live site.
Storing something in a JSON file is not scalable so if you end up storing a lot more data than originally planned (this often happens) you may find you run out of storage on your server hard drive. Also if you end up scaling and putting your app behind a load balancer, then you will need to make sure there are matching copy's of that JSON file on each server. Further more, it is easy to run into race conditions when updating a JSON file. If two processes are trying to update the file at the same time, you are going to potentially lose data. Technically speaking, JSON file would work but it's not recommended.
Storing in memory (i.e.) Redis has similar implications that the data is only available on that one server. Also the data is not persistent, so if your server restarted for whatever reason, you'd lose what was stored in memory.
For all intents and purposes, MongoDB is your best bet.
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you want to go with simpler way i.e JSON file use [nedb API](https://www.npmjs.com/package/nedb) which is pretty fast as well.
Upvotes: 2 |
2018/03/22 | 368 | 1,279 | <issue_start>username_0: `EC2 Details:
OS: Ubuntu 16.04
Git client: git version 2.7.4`
**Issue:**
From AWS instance I am not able to connect to bitbucket.org repositories. Tried ping to bitbucket.org but, I didn't got any response. I check-out bit-bucket repository via ssh clone. Outbound traffic is of type 'All traffic'.<issue_comment>username_1: Having the same problem on my ec2 instance.
tried `ping bitbucket.org` packet loss : 100%'
I can't pull in any of my instacne but can pull in my local machine.
Dunno what is the problem.
Upvotes: 1 <issue_comment>username_2: We're facing the same issue from EU Frankfurt zone of AWS. However, it works well from EU Ireland AWS zone. So it seems to be specific to Frankfurt region.
Also there is a related mention in twitter - <https://twitter.com/search?f=tweets&q=frankfurt%20network%20bitbucket&src=typd>
---
**UPDATE:**
You can see the official status here - <https://status.bitbucket.org/>
Currently it says: "Bitbucket is unavailable to customers routing from EU"
Upvotes: 3 [selected_answer]<issue_comment>username_1: Issue seems to be solved now by bitbucket.
-thnks bitbucket team
Upvotes: 0 <issue_comment>username_3: in AWS security group check whether port 443 is configured for https connections
Upvotes: 0 |
2018/03/22 | 711 | 2,243 | <issue_start>username_0: Why if I have several divs, which I want to give different height depending on the content. He always takes the height from the first condition.
```js
$('.box-site-promo').each(function(index) {
console.log($(this));
if ($(this).find('.box-site-tags')) {
heightBox = 200;
console.log(index + " " + heightBox);
} else if ($(this).find('.box-site-authors')) {
heightBox = 100;
console.log(index + " " + heightBox);
} else {
heightBox = 300;
console.log(index + " " + heightBox);
}
$(this).height(heightBox);
});
```
```html
A
some tags
B
authors
C
some tags
D
```<issue_comment>username_1: Your first condition is always `true` because [`$.fn.find`](https://api.jquery.com/find/) returns a `jQuery` object, which always evaluates to `true` regardless of whether any matching elements have been found or not.
To check whether the object contains any elements you can check its [`length`](https://api.jquery.com/length/) property:
```
if ($(this).find('.box-site-tags').length > 0)
```
**Snippet:**
```js
/* ----- JavaScript ----- */
$(".box-site-promo").each(function(index) {
var $this = $(this), heightBox = 300;
if ($this.find(".box-site-tags").length > 0) {
heightBox = 200;
} else if ($this.find(".box-site-authors").length > 0) {
heightBox = 100;
}
console.log(index + " " + heightBox);
$this.height(heightBox);
});
```
```html
A
some tags
B
authors
C
some tags
D
```
Upvotes: 1 <issue_comment>username_2: Use length to know if the div has descendants. As in the documentation says, find returns jQuery collection. Check it this snippet. Regards
```js
$('.box-site-promo').each(function(index) {
//console.log($(this));
if ($(this).find('.box-site-tags').length > 0) {
heightBox = 200;
console.log(index + " " + heightBox);
} else if ($(this).find('.box-site-authors').length > 0) {
heightBox = 100;
console.log(index + " " + heightBox);
} else {
heightBox = 300;
console.log(index + " " + heightBox);
}
$(this).height(heightBox);
});
```
```html
A
some tags
B
authors
C
some tags
D
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 587 | 2,092 | <issue_start>username_0: Can anyone help me with getting PHP to reference the value or id attribute in form handling. I can only see how to reference the name using $\_POST, how can this work with radio input type when the name is not unique?
Thanks in advance for any advice.
```
input type="radio" name="fuel" value="Unleaded" id="fuel_0"
/>Unleaded
Diesel
Super Unleaded
Premium Diesel
```<issue_comment>username_1: You do reference the name using $\_POST. The name is still unique even if the radio button name fuel shows 4 times. It is unique for the whole group and only one will be selected so you only have one value.
```
$radioValue = $_POST["fuel"];
```
Upvotes: 2 <issue_comment>username_2: Radio buttons work by giving all of inputs in a particular group the same name. However, when the form is submitted, only the value from the selected radio button is sent to the server. PHP will only end up seeing the one value.
Upvotes: 0 <issue_comment>username_3: I guess I should have rephrased the question to ask how to choose a different function depending on which option was chosen as you can't differentiate by using the name if they are all the same. I've got this working using the below code. I didn't realise before today that you could just refer to the value. Thanks to those of you who answered my earlier question.
```
php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{if(isset($_REQUEST['amount'])&&is_numeric($_REQUEST['amount'])){
$litres=$_REQUEST['amount'];}
else {echo "please enter a valid amount";$litres=0;}
$choice = $_POST ['fuel'];
if ($choice == "Unleaded"){echo "litres=amount= " . $litres . " final cost
is " . unleaded($litres) ;}
if ($choice == "Diesl"){echo "litres=amount= " . $litres . " final cost is
" . diesel($litres) ;}
if ($choice == "Super Unleaded"){echo "litres=amount= " . $litres . " final
cost is " . Superunleaded($litres) ;}
if ($choice == "Premium Diesel"){echo "litres=amount= " . $litres . " final
cost is " . premiemdiesel ($litres) ;}
}
</code
```
Upvotes: 0 |
2018/03/22 | 1,410 | 4,010 | <issue_start>username_0: Out of the box create-react-app with jest is always failing
Steps I did
```
create-react-app cra-test
cd cra-test
yarn install
```
Changed the original `test` in `package.json` into this
```
{
"name": "cra-test",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-scripts": "1.1.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
}
}
```
When I run `yarn test` the test failed. Here's the output
```
yarn run v1.1.0
$ jest
FAIL src\App.test.js
● Test suite failed to run
.../cra-test/src/App.test.js: Unexpected token (7:18)
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
> 7 | ReactDOM.render(, div);
| ^
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 3.413s, estimated 12s
Ran all test suites.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
```
I have read that this might be caused by upgrading Jest that it become incompatible with create-react-app, but I did not do such thing.
```
node --version && yarn --version && npm --version && create-react-app --version
v6.10.2
1.1.0
5.7.1
1.4.3
```<issue_comment>username_1: Unless you eject create-react-app, you have neither babel config nor jest config in your root dir, hence jest doesn't know it has to transpile sources. So you have to create .babelrc:
```
{
"presets": [
"react-app"
]
}
```
and jest.config.js:
```
module.exports = {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"setupFiles": [
"/config/polyfills.js"
],
"testMatch": [
"/src/\*\*/\_\_tests\_\_/\*\*/\*.{js,jsx,mjs}",
"/src/\*\*/?(\*.)(spec|test).{js,jsx,mjs}"
],
"testEnvironment": "node",
"testURL": "http://localhost",
"transform": {
"^.+\\.(js|jsx|mjs)$": "/node\_modules/babel-jest",
"^.+\\.css$": "/config/jest/cssTransform.js",
"^(?!.\*\\.(js|jsx|mjs|css|json)$)": "/config/jest/fileTransform.js"
},
"transformIgnorePatterns": [
"[/\\\\]node\_modules[/\\\\].+\\.(js|jsx|mjs)$"
],
"moduleNameMapper": {
"^react-native$": "react-native-web"
},
"moduleFileExtensions": [
"web.js",
"mjs",
"js",
"json",
"web.jsx",
"jsx",
"node"
]
}
```
*These configs you can find after you do npm run eject.*
`babel-preset-react-app` should be installed since jest config refers to it. Also, note that jest config mentions `config` directory which is a part of create-react-app. Which means it's not going to work without it, so you need to copy that dir from create-react-app or write your own setup files.
Upvotes: 1 <issue_comment>username_2: I do not know the cause, but I fixed it for the moment below.
`export CI=1`
[Bibliography](https://books.google.co.jp/books?id=f_RZDwAAQBAJ&pg=PA49&lpg=PA49&dq=src/App.test.js:+Unexpected+token+(7:18)&source=bl&ots=wdXBr8MXOb&sig=GsIYSjzHlxV8yTnyiQk8_HcYAzc&hl=ja&sa=X&ved=0ahUKEwizz7PFqNLbAhVDX5QKHYAnD_sQ6AEIYDAG#v=onepage&q=src%2FApp.test.js%3A%20Unexpected%20token%20(7%3A18)&f=false)
Upvotes: -1 <issue_comment>username_3: Test Suites: 0 of 1 total
FAIL src/App.test.js
× renders learn react link (6ms)
● renders learn react link
```
ReferenceError: React is not defined
3 |
4 | test('renders learn react link', () => {
> 5 | render();
| ^
6 | const linkElement = screen.getByText(/learn react/i);
7 | expect(linkElement).toBeInTheDocument();
8 | });
at Object. (src/App.test.js:5:10)
```
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 total
Snapshots: 0 total
Time: 6.378s, estimated 17s
Ran all test suites.
Determining test suites to run...
--watch is not supported without git/hg, please use --watchAll
Upvotes: 1 |
2018/03/22 | 1,530 | 5,770 | <issue_start>username_0: I was creating a component and was trying to break my implementation. The idea is to not allow user to manipulate the exposed properties.
The implementation was like this:
```js
function MyClass(){
var data = [];
Object.defineProperty(this, 'data', {
get: function(){ return data; },
set: function(){ throw new Error('This operation is not allowed'); },
configurable: false,
});
}
var obj = new MyClass();
try {
obj.data = [];
} catch(ex) {
console.log('mutation handled');
}
obj.data.push('Found a way to mutate');
console.log(obj.data)
```
As you see, setting the property is handled but user is still able to mutate it using `.push`. This is because I'm returning a reference.
I have handled this case like:
```js
function MyClass(){
var data = [];
Object.defineProperty(this, 'data', {
get: function(){ return data.slice(); },
set: function(){ throw new Error('This operation is not allowed'); },
configurable: false,
});
}
var obj = new MyClass();
try {
obj.data = [];
} catch(ex) {
console.log('mutation handled');
}
obj.data.push('Found a way to mutate');
console.log(obj.data)
```
As you see, I'm returning a new array to solve this. Not sure how it will affect performance wise.
**Question:** Is there an alternate way to not allow user to mutate properties that are of type *object*?
I have tried using `writable: false`, but it gives me error when I use it with `get`.
---
**Note:** I want this array to mutable within class but not from outside.<issue_comment>username_1: Your problem here is that you are effectively blocking attempts to modify `MyClass`. However, other objects members of `MyClass` are still JavaScript objects. That way you're doing it (returning a new Array for every call to `get`) is one of the best ways, though of course, depending of how frequently you call `get` or the length of the array might have performance drawbacks.
Of course, if you could use ES6, you could extend the native Array to create a `ReadOnlyArray` class. You can actually do this in ES5, too, but you lose the ability to use square brackets to retrieve the value from a specific index in the array.
Another option, if you can avoid Internet Explorer, is to use `Proxies` (<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy>).
With a proxy, you can trap calls to get properties of an object, and decide what to return or to do.
In the example below, we create a Proxy for an array. As you see in the handler, we define a `get` function. This function will be called whenever the value of a property of the target object is accessed. This includes accessing indexes or methods, as calling a method is basically retrieving the value of a property (the function) and then calling it.
As you see, if the property is an integer number, we return that position in the array. If the property is 'length' then we return the length of the array. In any other case, we return a void function.
The advantage of this is that the proxyArray still behaves like an array. You can use square brackets to get to its indexes and use the property length. But if you try to do something like `proxyArray.push(23)` nothing happens.
Of course, in a final solution, you might want decide what to do based on which
method is being called. You might want methods like `map`, `filter` and so on to work.
And finally, the last advantage of this approach is that you keep a reference to the original array, so you can still modify it and its values are accessible through the proxy.
```js
var handler = {
get: function(target, property, receiver) {
var regexp = /[\d]+/;
if (regexp.exec(property)) { // indexes:
return target[property];
}
if (property === 'length') {
return target.length;
}
if (typeof (target[property]) === 'function') {
// return a function that does nothing:
return function() {};
}
}
};
// this is the original array that we keep private
var array = [1, 2, 3];
// this is the 'visible' array:
var proxyArray = new Proxy(array, handler);
console.log(proxyArray[1]);
console.log(proxyArray.length);
console.log(proxyArray.push(32)); // does nothing
console.log(proxyArray[3]); // undefined
// but if we modify the old array:
array.push(23);
console.log(array);
// the proxy is modified
console.log(proxyArray[3]); // 32
```
Of course, the poblem is that `proxyArray` is not really an array, so, depending on how you plan to use it, this might be a problem.
Upvotes: 2 <issue_comment>username_2: What you want isn't really doable in JavaScript, as far as I'm aware. The best you can hope for is to hide the data from the user as best you can. The best way to do that would be with a [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap)
```
let privateData = new WeakMap();
class MyClass {
constructor() {
privateData.set(this, {
data: []
});
}
addEntry(entry) {
privateData.get(this).data.push(entry);
}
getData() {
return privateData.get(this).data.concat();
}
}
```
So long as you never export `privateData` don't `export` from the module, or wrap within an [IIFE](https://developer.mozilla.org/en-US/docs/Glossary/IIFE) etc.) then your `MyClass` instances will be able to access the data but external forces can't (other than through methods you create)
```
var myInstance = new MyClass();
myInstance.getData(); // -> []
myInstance.getData().push(1);
myInstance.getData(); // -> []
myInstance.addEntry(100);
myInstance.getData(); // -> [100]
```
Upvotes: 0 |
2018/03/22 | 426 | 1,771 | <issue_start>username_0: So I was checking some implementations online and I noticed that some people use the following way to generate a key:
```
using (var random = RandomNumberGenerator.Create())
{
var key = new byte[32];
random.GetBytes(key);
}
```
While others use the generateKey method which is built in the AES class:
```
using (Aes myAes = Aes.Create())
{
myAes.GenerateKey();
var key = myAes.Key;
}
```
Both of them are in the System.Security.Cryptography library, just wondering if there is an actual difference between them and if yes which one should I go with?<issue_comment>username_1: Good question. Both use the same underlying CSPRNG. The results are equally secure.
You can view this in the [.NET Reference Source](https://referencesource.microsoft.com)
Upvotes: 2 <issue_comment>username_2: Both versions do the same thing. `Aes.GenerateKey` will use the same `RandomNumberGenerator.Create()` as first example to generate new key.
However I'd prefer to use second version, because:
1) It expresses intent very clear. You are generating AES key, not just arbitrary random byte array.
2) AES can have different key sizes. Not only that, but some key sizes are invalid for AES. First example now generates 32-byte keys only. If you modify it to accept key size - someone can pass invalid (for AES) key size to it. So you will need to validate passed size to verify it's a valid key size for AES. But why do that if `Aes` class already does that for you?
Side note: there is no need to call `GenerateKey`, though it does not harm too. If there is no key yet - it will be generated when you first access `Key` property.
Upvotes: 4 [selected_answer] |
2018/03/22 | 355 | 1,476 | <issue_start>username_0: How to create Custom Authentication Attribute in C# Web API
```
using System.Web.Http;
using System.Web.Http.Controllers;
namespace WebApiCustomAuthorization
{
public class MyAuthorization : AuthorizeAttribute
{
protected override bool Authorized(HttpActionContext actionContext)
{
return true;
}
}
}
```<issue_comment>username_1: Good question. Both use the same underlying CSPRNG. The results are equally secure.
You can view this in the [.NET Reference Source](https://referencesource.microsoft.com)
Upvotes: 2 <issue_comment>username_2: Both versions do the same thing. `Aes.GenerateKey` will use the same `RandomNumberGenerator.Create()` as first example to generate new key.
However I'd prefer to use second version, because:
1) It expresses intent very clear. You are generating AES key, not just arbitrary random byte array.
2) AES can have different key sizes. Not only that, but some key sizes are invalid for AES. First example now generates 32-byte keys only. If you modify it to accept key size - someone can pass invalid (for AES) key size to it. So you will need to validate passed size to verify it's a valid key size for AES. But why do that if `Aes` class already does that for you?
Side note: there is no need to call `GenerateKey`, though it does not harm too. If there is no key yet - it will be generated when you first access `Key` property.
Upvotes: 4 [selected_answer] |
2018/03/22 | 434 | 1,716 | <issue_start>username_0: Using Create-react-app, I want to lazy load some of my components, this is working fine as long as the components are in the same folder as my main component (where I define the routes) however as soon as I want to load a component from another folder like
```
loader: () => import("../containers/HomeAContainer")
```
it fails to find/import the module. (exact same module will work if I move the file!
I have made a complete example which can be seen [here](https://codesandbox.io/s/184rpk25rl)
* I have also tried to change the route to src/x/x instead of ../x/x but again getting errors.<issue_comment>username_1: Good question. Both use the same underlying CSPRNG. The results are equally secure.
You can view this in the [.NET Reference Source](https://referencesource.microsoft.com)
Upvotes: 2 <issue_comment>username_2: Both versions do the same thing. `Aes.GenerateKey` will use the same `RandomNumberGenerator.Create()` as first example to generate new key.
However I'd prefer to use second version, because:
1) It expresses intent very clear. You are generating AES key, not just arbitrary random byte array.
2) AES can have different key sizes. Not only that, but some key sizes are invalid for AES. First example now generates 32-byte keys only. If you modify it to accept key size - someone can pass invalid (for AES) key size to it. So you will need to validate passed size to verify it's a valid key size for AES. But why do that if `Aes` class already does that for you?
Side note: there is no need to call `GenerateKey`, though it does not harm too. If there is no key yet - it will be generated when you first access `Key` property.
Upvotes: 4 [selected_answer] |
2018/03/22 | 628 | 1,727 | <issue_start>username_0: Is it possible to group only specific elements in a scala map which matches a given condition?
**From:**
```
val map = Map(((1,true,"case0")->List(1,2,3)), ((2,true,"case0")->List(3,4,5)),
((1,true,"case1")->List(2,4,6)), ((2,false,"case1")->List(3)))
```
**To:**
```
Map(((1,true,"nocase")->List(2)), ((2,true,"case0")->List(3,4,5)),
((2,false,"case1")->List(3)))
```
**Condition:**
key.\_1 should match and key.\_2 should be true<issue_comment>username_1: You can perform the `groupBy` on a conditional basis
```
map.groupBy{case (key, value) => if (key._1 == 1) (key._1, key._2) else key }
.map{case (key, elements) => (key, elements.values.reduce(_ intersect _ ))}
```
In this piece of code, you will use the whole key (3 elements) to group if the first element of the key is not 1, otherwise it will group by only the first and second elements of the key
**Output**:
```
Map((2,true,case0) -> List(3, 4, 5), (2,false,case1) -> List(3), (1,true) -> List(2))
```
Upvotes: 1 <issue_comment>username_2: Here is way
```
map.groupBy(
e => (e._1._1, e._1._2) //group input by key._1 and key._2
).collect{
case e if (e._2.keys.size > 1)=> // if key have more cases(key._3) use "nocase"
(e._1._1, e._1._2, "nocase") -> //Tuple3(Int, Boolean, String)
e._2.values.reduce(_.intersect(_)) //List of common elements
case e => //we have only one key._3 so use as it is
(e._1._1, e._1._2, e._2.map(e=> e._1._3).mkString("")) ->
e._2.values.reduce(_.intersect(_))
}
```
Output
------
```
Map((2,false,case1) -> List(3), (2,true,case0) -> List(3, 4, 5), (1,true,nocase) -> List(2))
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,143 | 3,580 | <issue_start>username_0: I have just started to learn Angular 4. I get the following error
```
Uncaught TypeError: Object(...) is not a function
at eval (bidi.es5.js:70)
at eval (bidi.es5.js:72)
at Object../node_modules/@angular/cdk/esm5/bidi.es5.js (vendor.bundle.js:39)
at __webpack_require__ (inline.bundle.js:55)
at eval (core.es5.js:57)
at Object../node_modules/@angular/material/esm5/core.es5.js (vendor.bundle.js:255)
at __webpack_require__ (inline.bundle.js:55)
at eval (autocomplete.es5.js:15)
at Object../node_modules/@angular/material/esm5/autocomplete.es5.js (vendor.bundle.js:191)
at __webpack_require__ (inline.bundle.js:55)
```
and a bunch of Warnings like this
```
./node_modules/@angular/material/esm5/datepicker.es5.js
107:59-75 "export 'defineInjectable' was not found in '@angular/core'
@ ./node_modules/@angular/material/esm5/datepicker.es5.js
@ ./node_modules/@angular/material/esm5/material.es5.js
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi (webpack)-dev-server/client?http://0.0.0.0:0 ./src/main.ts
./node_modules/@angular/cdk/esm5/a11y.es5.js
1118:164-170 "export 'inject' was not found in '@angular/core'
@ ./node_modules/@angular/cdk/esm5/a11y.es5.js
@ ./node_modules/@angular/material/esm5/bottom-sheet.es5.js
@ ./node_modules/@angular/material/esm5/material.es5.js
@ ./src/app/app.module.ts
@ ./src/main.ts
@ multi (webpack)-dev-server/client?http://0.0.0.0:0 ./src/main.ts
```
I believe something is wrong with Angular Material. So I tried reinstalling it. But didn't help.
**app.module.ts**
```
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatButtonModule, MatMenuModule, MatToolbarModule, MatIconModule,
MatCardModule, MatCheckboxModule, MatSelectModule, MatInputModule, MatTabsModule} from '@angular/material';
import { AppComponent } from './app.component';
import { PlayerComponent } from './player/player.component';
import { LoginComponent } from './login/login.component';
@NgModule({
declarations: [
AppComponent,
PlayerComponent,
LoginComponent,
],
imports: [
BrowserModule,
BrowserAnimationsModule,
MatButtonModule, MatMenuModule, MatToolbarModule, MatIconModule,
MatCardModule, MatCheckboxModule, MatSelectModule,
MatInputModule, MatTabsModule,
HttpClientModule, FormsModule
],
providers: [],
bootstrap : [AppComponent]
})
export class AppModule { }
```
I don't even know how to make sense of this anymore.
**----EDIT 1----**
I tried adding package.json as code but SO didn't allow me.
[](https://i.stack.imgur.com/npkud.png)<issue_comment>username_1: The `package.json` should have the following entries for Angular Material and the Angular CDK packages:
```json
"@angular/cdk": "^5.2.4",
"@angular/material": "^5.2.4"
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: check the version of @angular/cdk&material in your package.json
if you see a version above 5.2.4 and you're using angular 5 try to downgrade it using those commandes
=> npm uninstall @angular/material --save
then
=> npm install @angular/[email protected] --save
and for CDK use :
=> npm uninstall @angular/cdk --save
then
=> npm install @angular/[email protected] --save
hope it work for you :)
Upvotes: 2 |
2018/03/22 | 591 | 2,124 | <issue_start>username_0: The following code is working on development but not on production , am getting error
I have added the name attribute on the componenet but it's still not working. For now i have removed the spinner component.
```
Unknown custom element: - did you register the component correctly?
For recursive components, make sure to provide the "name" option
```
my .vue component looks like this:
```
![]()
X
export default{
name:'event-image',
props: ['image'],
data(){
return {
showspinner:false
}
},
methods: {
remove(){
this.showspinner = true;
axios.delete('/media/'+JSON.parse(this.image).id)
.then(response => {
this.showspinner = false;
location.reload();
})
.catch(errors =>{
});
}
},
computed : {
url(){
return JSON.parse(this.image).url;
}
}
}
```
and registered it on app.js as:
```
Vue.component(
'event-image',
require('./components/event/EventImage.vue'));
```
then used it on blade like:
```
@foreach($images as $image)
@endforeach
```
where is the error above comming from.<issue_comment>username_1: Answering this question even though the original author determined a different reason for the problem: I received the same Vue error message and I'm guessing others will navigate here as well.
This fixed it for me when I added this line to my export statement:
```
name: "Comment"
```
Note that "Comment" is the name of the (current) component that is recursively calling itself.
Upvotes: 1 <issue_comment>username_2: I got the same err message using SFC ([Single file components](https://v2.vuejs.org/v2/guide/single-file-components.html)) with code like this:
Component I want to use in another one `./buttons/SomeButton.vue`:
```js
...html of component...
export default {
name: "some-button",
...
}
```
Component which use that one above `./RowOfButtons.vue`:
```js
import SomeButton from "./buttons/SomeButton"
export default {
name: "row-of-buttons",
comments: {
SomeButton
},
...
}
```
And obviously there were typo due to PhpStorm completed it with `comments` instead of `components`.
Upvotes: 0 |
2018/03/22 | 637 | 2,225 | <issue_start>username_0: I'm new to Django and i'm working on uploading files.
when uploading my files, the saving is working perfectly.
but problem is i need to associate every aploaded file to a bill id, cause the uploaded file for me is a bill.
something like
>
> billX\_[45]
>
>
>
45 is the bill id in my database.
billX is the uploaded file name.
in some documentations i found that upload\_to helps fo do so, but i still feel confused.
my form.py is :
```
class bills(forms.Form):
numfacture=forms.CharField()
myfile=forms.FileField()
```
model.py
```
class facture_ventes(models.Model):
numfac=models.CharField(max_length=20)
piece_joint=models.FileField(upload_to = 'FacturesVentes')
```
in my view :
```
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return redirect('/veentes', {
'uploaded_file_url': uploaded_file_url
})
```
The `FacturesVentes` is added to `MEDIA_ROOT` in the settings
Any help please , Thank You So Much<issue_comment>username_1: Answering this question even though the original author determined a different reason for the problem: I received the same Vue error message and I'm guessing others will navigate here as well.
This fixed it for me when I added this line to my export statement:
```
name: "Comment"
```
Note that "Comment" is the name of the (current) component that is recursively calling itself.
Upvotes: 1 <issue_comment>username_2: I got the same err message using SFC ([Single file components](https://v2.vuejs.org/v2/guide/single-file-components.html)) with code like this:
Component I want to use in another one `./buttons/SomeButton.vue`:
```js
...html of component...
export default {
name: "some-button",
...
}
```
Component which use that one above `./RowOfButtons.vue`:
```js
import SomeButton from "./buttons/SomeButton"
export default {
name: "row-of-buttons",
comments: {
SomeButton
},
...
}
```
And obviously there were typo due to PhpStorm completed it with `comments` instead of `components`.
Upvotes: 0 |
2018/03/22 | 628 | 1,603 | <issue_start>username_0: I have dataframe like this:
```
import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'ent':['A','B']})
| |a |b |ent
|---|---|----|----
|0 |1 |3 |A
|1 |2 |4 |B
```
I want to have this dataframe in form like **this:**
```
|ent |A |B
-------------
|a |1 |2
|b |3 |4
```
I can apply `df.T` or `df.transpose` but I don't get exactly what I want (header):
```
| |0 |1
-------------
|a |1 |2
|b |3 |4
|ent |A |B
```
I'm looking for pandastic solution (renaming columns and dropping ent row after transpose for me is inelegant).<issue_comment>username_1: If need first column is `index` add [`set_index`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html):
```
df1 = df.set_index('ent').T
print (df1)
ent A B
a 1 2
b 3 4
```
And if need default index:
```
df1 = df.set_index('ent').T.rename_axis(None, 1).rename_axis('ent').reset_index()
print (df1)
ent A B
0 a 1 2
1 b 3 4
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: `pd.pivot_table(df, values=['a','b'], columns='ent')`
does exactly what you want
Edit: username_1 is totally correct. The output of the displayed pivot\_table function with
`df= a b ent
0 1 3 A
1 2 4 B`
is
`ent A B
a 1 2
b 3 4`
but if we change df to
`df= a b ent
0 1 3 A
1 2 4 A`
the output of `pd.pivot_table(df, values=['a','b'], columns='ent')` is
`ent A
a 1.5
b 3.5`.
Note that it is possible to apply an own function in the pivot\_table argument aggfunc. 'mean' is just the default value.
Upvotes: 1 |
2018/03/22 | 396 | 1,575 | <issue_start>username_0: For example, if we set OnClick on button and also set it invisible
It still works right ?
If yes, What's a real life scenario in which it would be beneficial ?
If there is no use , Why does android even allow to have onClick on Invisible view and it doesn't even give warning or anything.
I am curious to know :')<issue_comment>username_1: You are using android views in the wrong way.
Views have three properties to alter visibility which are
1. **Visible**: By default, all views are visible
2. **Invisible**: The `view` is not visible but occupies space and resources
3. **Gone**: The `view` is entirely out of the layout
`Visisble` is used to set a `view` from either of the other two.
`Invisible` is used when you want a certain `button` that is lying on top of another `view` to be clicked rather than the view. It can also be used when you want a `view` to occupy space but not be present for the user. This scenario might occur when using `LinearLayouts` with `android:layoutWeight`
`Gone` is used when you want to completely hide a view from the picture. This is common with login screens and welcome previews in apps
Upvotes: 1 <issue_comment>username_2: Because for a View `visibility` and `onClick` are completely independent properties.
When a View is `INVISIBLE` as per its property it is just not shown but present in the given place, so `onClick()` would work on the view.
In case if a view is `GONE`, as the view itself is not present at the expected place, `onClick` function wont be called.
Upvotes: 1 [selected_answer] |
2018/03/22 | 583 | 2,340 | <issue_start>username_0: I need to create a zip file by using Java. Library is not important, but zip4j seems to be a good one. In this zip file, only some of the files or subdirectories will be password protected. For example in the following zip file, only the files starting with "\*" will be password protected:
```
foo.zip
foo1.txt
*secure
*secure1.txt
*secure2.txt
```
Is there any way to implement this scenario in Java?
Thanks in advance...<issue_comment>username_1: Anyway, I found it by using zip4j. Fwollowing snippets can be used for creating both password protected and non-password protected files.
For the files to be password protected:
```
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(<PASSWORD>);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
```
And the files that are not password protected:
```
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
```
Upvotes: 0 <issue_comment>username_2: this mavne dependency:
```xml
net.lingala.zip4j
zip4j
2.6.1
```
code:
```java
ZipParameters parameters = new ZipParameters();
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
ZipFile zip = new ZipFile(destFile, PASSWORD.toCharArray());
zip.setCharset(InternalZipConstants.CHARSET_UTF_8);
for (File file : srcFiles) {
if (file.isFile()) {
zip.addFile(file, parameters);
} else {
zip.addFolder(file, parameters);
}
}
```
Upvotes: 1 |
2018/03/22 | 559 | 2,277 | <issue_start>username_0: After navigation on page,
`driver.navigate().to("http://");`
nothing is working, page is transferred but it stops execution. If we go to browser and manually refresh it, then it is executing next step.
No error or exception, But still its stop working after navigation.
```
driver.navigate().refresh();
```
also not calling as on next step. It holds everything.<issue_comment>username_1: Anyway, I found it by using zip4j. Fwollowing snippets can be used for creating both password protected and non-password protected files.
For the files to be password protected:
```
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(<PASSWORD>);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
```
And the files that are not password protected:
```
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
```
Upvotes: 0 <issue_comment>username_2: this mavne dependency:
```xml
net.lingala.zip4j
zip4j
2.6.1
```
code:
```java
ZipParameters parameters = new ZipParameters();
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
ZipFile zip = new ZipFile(destFile, PASSWORD.toCharArray());
zip.setCharset(InternalZipConstants.CHARSET_UTF_8);
for (File file : srcFiles) {
if (file.isFile()) {
zip.addFile(file, parameters);
} else {
zip.addFolder(file, parameters);
}
}
```
Upvotes: 1 |
2018/03/22 | 709 | 3,005 | <issue_start>username_0: I have the following class component:
```
class ConceptPopup extends React.Component {
constructor(props) {
super(props);
this.state = {
attributeForm: []
};
this.addAttributeForm();
}
addAttributeForm() {
//this method adds label and input field to the state array
var array = this.state.attributeForm;
array.push(
**new Attribute**
Attribute name :
);
this.setState({
attributeForm: array
});
}
render() {
return (
{this.state.attributeForm}
ADD ATTRIBUTE
);
}
}
```
Now the ideal situation would be that everytime the ADD ATTRIBUTE button is clicked a new input field appears.
My current situation is that the method addAttribute is called on button click and the state updates correctly but the changes aren't visible.
All that is shown is one input field due to the addAttributeForm from the constructor. I tried to force re-render the form on click but that only throws a buch of errors (like Maximum call stack size exceeded).<issue_comment>username_1: Anyway, I found it by using zip4j. Fwollowing snippets can be used for creating both password protected and non-password protected files.
For the files to be password protected:
```
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
zipParameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
zipParameters.setPassword(<PASSWORD>);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
```
And the files that are not password protected:
```
ZipFile zipFile = new ZipFile(zipFileName);
ZipParameters zipParameters = new ZipParameters();
zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
zipFile.addFiles(new ArrayList<>(filesToZip), zipParameters);
```
Upvotes: 0 <issue_comment>username_2: this mavne dependency:
```xml
net.lingala.zip4j
zip4j
2.6.1
```
code:
```java
ZipParameters parameters = new ZipParameters();
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
ZipFile zip = new ZipFile(destFile, PASSWORD.toCharArray());
zip.setCharset(InternalZipConstants.CHARSET_UTF_8);
for (File file : srcFiles) {
if (file.isFile()) {
zip.addFile(file, parameters);
} else {
zip.addFolder(file, parameters);
}
}
```
Upvotes: 1 |
2018/03/22 | 511 | 2,251 | <issue_start>username_0: I'm using $mdDialog to show popup alerts. I want to refresh the the page whenever I close the Pop up container.
```
$scope.updateCustomer = function(){
HomeService.updateCustomer($scope.update)
.then (function success(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Username has been changed successfully!")
.ariaLabel('')
.ok('Ok')
);
},
function error(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Something is wrong!")
.ariaLabel('')
.ok('Ok')
);
});
}
```
How to refresh the page when I close the pop up container?<issue_comment>username_1: Page reloading is not quite the angularjs pattern but you can use:
```
$mdDialog
.show({
...
onRemoving: function() {
window.location.reload();
}
});
```
Ref.: [$mdDialog Service](https://material.angularjs.org/latest/api/service/$mdDialog#mddialog-show-optionsorpreset)
Upvotes: 0 <issue_comment>username_2: This was the working answer for my problem...
```
$scope.updateCustomer = function(){
HomeService.updateCustomer($scope.update)
.then (function success(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Username has been changed successfully!")
.ariaLabel('')
.ok('Ok')
.onRemoving(window.location.reload())
);
},
function error(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Something is wrong!")
.ariaLabel('')
.ok('Ok')
);
});
}
```
Upvotes: 1 |
2018/03/22 | 437 | 1,803 | <issue_start>username_0: I'm currently working on google's dialog flow using api-ai-javascript. I'm recieving a response from server in json format and trying to access "res.result.fulfillment.messages[0]" field in it. But everytime i "ng serve" it displays following error: "error TS2339: Property 'messages' does not exist on type '{ speech: string; }'". I tried to display the whole response in console, and it shows "messages" field. Can someone plz help [here's screenshot of my console log](https://i.stack.imgur.com/ZoiX4.png)<issue_comment>username_1: Page reloading is not quite the angularjs pattern but you can use:
```
$mdDialog
.show({
...
onRemoving: function() {
window.location.reload();
}
});
```
Ref.: [$mdDialog Service](https://material.angularjs.org/latest/api/service/$mdDialog#mddialog-show-optionsorpreset)
Upvotes: 0 <issue_comment>username_2: This was the working answer for my problem...
```
$scope.updateCustomer = function(){
HomeService.updateCustomer($scope.update)
.then (function success(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Username has been changed successfully!")
.ariaLabel('')
.ok('Ok')
.onRemoving(window.location.reload())
);
},
function error(response){
$mdDialog.show(
$mdDialog.alert()
.parent(angular.element(document.querySelector('#popupContainer')))
.clickOutsideToClose(true)
.textContent("Something is wrong!")
.ariaLabel('')
.ok('Ok')
);
});
}
```
Upvotes: 1 |
2018/03/22 | 1,189 | 3,731 | <issue_start>username_0: So I have a situation in which I need to populate a specific column from an URL ( Basically a get request to that URL will give a list of numbers ).
I am new with the macros but I want to make a system in which I will click a button and then that will read the data and populate the column.
**Edit:**
I have a URL, let's say `192.168.127.12/importData.txt` and it has the following data.
```
12345
67890
12345
09876
87653
14214
14566
46131
12456
35098
```
Now in my excel, I have a button like this :
[](https://i.stack.imgur.com/YYT0I.jpg)
and I need to populate the column `A1` with the data.<issue_comment>username_1: Such as this to extract?
Windows machines:
add the reference in to microsoft xml and to html object library VBE > tools > references
Also, XMLHTTP60 will need to be adjusted (the 60 bit) to the appropriate version for your Excel.
```
' "http://192.168.3.11/excelimport.txt"
Sub Getinfo3()
Dim http As New XMLHTTP60
Dim html As New HTMLDocument
With http
.Open "GET", "http://192.168.3.11/excelimport.txt", False
.send
html.body.innerHTML = .responseText
End With
Dim returnArray() As String
returnArray = Split(html.body.innerText, " ")
Dim currentItem As Long
For currentItem = LBound(returnArray) To UBound(returnArray)
ActiveSheet.Cells(currentItem + 1, 1) = returnArray(currentItem)
Next currentItem
End Sub
```
And internet explorer version (requires reference to Microsoft Internet Controls and html object library
```
Public Sub scrapeaIE()
Dim appIE As Object
Dim ihtml As Object
Set appIE = CreateObject("internetexplorer.application")
With appIE
.Visible = True
.navigate "http://192.168.3.11/excelimport.txt"
While .Busy = True Or .readyState < 4: DoEvents: Wend
Set ihtml = .document
End With
Dim returnArray() As String
returnArray = Split(ihtml.body.innerText, vbNewLine)
Dim currentItem As Long
For currentItem = LBound(returnArray) To UBound(returnArray)
ActiveSheet.Cells(currentItem + 1, 1) = returnArray(currentItem)
Next currentItem
appIE.Quit
Set appIE = Nothing
End Sub
```
References included to use both (Excel 2016)
[](https://i.stack.imgur.com/FzOwc.png)
1. Internet Controls
2. XML Library (version for your excel)
3. HTML Object library (version for your excel)
Edit:
For Mac:
You may be able to do something with [AppleScript and MacScript](https://www.ozgrid.com/forum/forum/help-forums/excel-general/107972-accessing-web-page-via-safari-on-mac-using-vba)
Edit:
-----
The OP running the code starting getting cache data returning after the first run with each new URL. In the same way as [Excel-VBA REST WCF works on 1st call, but subsequent calls return cached (non-current) data](https://stackoverflow.com/questions/11620747/excel-vba-rest-wcf-works-on-1st-call-but-subsequent-calls-return-cached-non-cu)
The resolution was to add:
```
.setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
```
Before
```
.send
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: Sounds like a job for PowerQuery, depending on your version of Excel it is either built in or is available as an add-in from Microsoft. So for Excel 2016 you just click the Data tab, then New Query > From Other Sources > From Web and then follow the dialog boxes and job done.
You can find out more from [here](https://support.office.com/en-ie/article/connect-to-a-web-page-power-query-b2725d67-c9e8-43e6-a590-c0a175bd64d8)
Upvotes: 0 |
2018/03/22 | 1,367 | 4,742 | <issue_start>username_0: I don't know if someone is able to help me but I'm having trouble getting Envira Gallery to work with ACF pro.
What I'm trying to do is have Envira Gallery pick-up the gallery I've made with ACF. It should be possible for what I've read. And it kind of works at the moment. I've read [this](https://www.jowaltham.com/display-advanced-custom-fields-envira-gallery/) tutorial about a 1000 times to check if I've done anything wrong but I can't seem to get it to work.
I have made a gallery in Envira Gallery called `New fotos` and it got ID `7522` and I've also created an ACF gallery field called `get_my_fotos` and put some images in it, as instructed by the tutorial. I've grabbed the code from the github link in the comments since that was a newer code.
My HTML:
```
php get_header(); ?
php echo do\_shortcode('[envira-gallery id="7522"]'); ?
php get_footer(); ?
```
And now the script to enable the Envira Gallery to work with ACF:
```
/*
* Populate Envira Gallery with ACF gallery field
*
* Filters the gallery $data and replaces with the image data for our images in the ACF gallery field.
*
* @uses ACF Pro
* @uses Envira Gallery
* @param $data
* @param $gallery_id
*/
function envira_acf_gallery( $data, $gallery_id ) {
// Target desired Envira gallery using ID
if ( $data[ "id" ] == 7522 ) {
//Setup new array to populate Envira gallery
$newdata = array();
// Don't lose the original gallery id and configuration
$newdata[ "id" ] = $data[ "id" ];
$newdata[ "config" ] = $data[ "config" ];
if ( function_exists( 'get_field' ) )
// Get array of images data from desired ACF gallery field
$image_ids = get_field( 'get_my_fotos' );
// Check to make sure array has images
if( is_array( $image_ids ) ) {
// Populate the Envira gallery with meta from the ACF gallery
foreach( $image_ids as $image_id ) {
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "status" ] = 'active';
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "src" ] = $image_id["url"];
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "title" ] = $image_id["title"];
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "link" ] = $image_id["url"];
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "alt" ] = $image_id["alt"];
$newdata[ "gallery" ][ ( $image_id["id"] ) ][ "thumb" ] = $image_id["sizes"]["thumbnail"];
}
}
// Return the new array of images
return $newdata;
}
}
// Add new image data to the envira gallery
add_filter( 'envira_gallery_pre_data', 'envira_acf_gallery', 10, 2);
```
Now, if I check my inspector I see:
```
```
Without the script I see the following:
```
```
So it's IS picking up some code, but it looks like its an older ID of an gallery I've deleted. But I can't seem to get why it's not picking up the ID i've given in the script. Thus showing no images.
Has anyone tried this before? I hope there is some help here. I've also tried the script in the tutorial itself but that didn't work.<issue_comment>username_1: I just encountered the same issue. Adding the following solved it:
```
add_filter( 'envira_gallery_get_transient_markup', '__return_false' );
```
See [How to Remove Fragment Cache from Envira](https://enviragallery.com/docs/how-to-remove-fragment-cache-from-envira/) for more info.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Another way around this is to use the Dynamic Addon available with Envira Gallery. You can set this to automatically display the default WordPress gallery as an Envira gallery if a shortcode or the classic editor is used (does not work with the block editor). You can then use an ACF gallery field and output the data as a WordPress gallery and it is displayed as an Envira gallery.
Instructions for configuring the Envira gallery are on [Envira Dynamic Addon page](http://enviragallery.com/docs/dynamic-addon/)
Code taken from ACF Gallery docs to display the shortcode is:
```
// Load value (array of ids).
$image_ids = get_field('gallery');
if( $image_ids ) {
// Generate string of ids ("123,456,789").
$images_string = implode( ',', $image_ids );
// Generate and do shortcode.
// Note: The following string is split to simply prevent our own website from rendering the gallery shortcode.
$shortcode = sprintf( '[' . 'gallery ids="%s"]', esc_attr($images_string) );
echo do_shortcode( $shortcode );
}
```
I've checked it out on a localhost site and works fine. Since it uses the shortcode it might be less susceptable to problems caused by Envira gallery code changing.
Upvotes: 1 |
2018/03/22 | 1,049 | 3,153 | <issue_start>username_0: I want to store data inside Li for displaying it when it's being clicked.
I've used Data attribute but it's store only the type...rather then the object itself ...so it's doing something like
```
-
```
Here is what i've done so far :
```js
var data_obj = [{
name: "foo",
age: 33
}, {
name: "goo",
age: 34
}];
var tmp = '';
var count = 0;
$.each(data\_obj, function() {
count++;
tmp += '* ' + count + '
';
});
$('#res').html(tmp + '
');
```
```html
```
My goal is to be able to get the Li's data when being clicked....thanks<issue_comment>username_1: To achieve this you can use the `data()` method to store an object within jQuery's data cache. You will however need to re-arrange your logic slightly though, in order to retain the references to the created elements, something like this:
```js
var data_obj = [{
name: "foo",
age: 33
}, {
name: "goo",
age: 34
}];
var elements = data_obj.map(function(obj, i) {
return $(`- ${i + 1}
`).data('obj', obj);
});
$('
').appendTo('#res').append(elements);
// for testing only...
$('#res').on('click', 'li', function() {
console.log($(this).data('obj'));
});
```
```html
```
Upvotes: 0 <issue_comment>username_2: You're getting `[object][object]` because that's what javascript does when it tries to convert an object to a string. And when you do `"str" + obj + "str"`, `obj` is converted to string.
You could also use `JSON.stringify`, but jQuery has a better way:
You can benefit from jQuery's [**`.data()`**](https://api.jquery.com/data/) function, and jQuery's implementation of element creation.
Try this instead:
```js
var data_obj = [{
name: "foo",
age: 33
}, {
name: "goo",
age: 34
}];
var $ul = $('
', {
id: 'list'
});
var count = 0;
$.each(data_obj, function() {
count++;
var $li = $("-
", {
text: count
});
$li.data('obj', this);
$ul.append($li);
});
$('#res').append($ul);
//You can use this to retrieve data on click:
$("#res").on('click', 'li', function(){
var data = $(this).data('obj');
alert(data.name);
});
```
```html
```
Upvotes: 2 <issue_comment>username_3: You can store data in li element by converting it to string with JSON.stringify().
```
var data_obj = [{
name: "foo",
age: 33
}, {
name: "goo",
age: 34
}];
var tmp = '';
var count = 0;
$.each(data\_obj, function() {
count++;
tmp += '* ' + count + '
';
});
$('#res').html(tmp + '
');
```
Upvotes: 0 <issue_comment>username_4: Instead of concatenating your html, build it up and add separate `data` elements for each key/value in your data:
```js
var data_obj = [{
name: "foo",
age: 33
}, {
name: "goo",
age: 34
}];
var count = 0;
var lis = [];
$.each(data_obj, function() {
var $li = $('-
');
$.each(this, function(k,v){
$li.data(k,v);
})
count++;
$li.text(count)
lis.push($li)
});
$('#res').append($('').append(lis))
$('ul li').on('click',function(){
console.log($(this).data('name') + ":" + $(this).data('age'))
});
```
```html
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,256 | 4,144 | <issue_start>username_0: What the following expression computes, exactly?
```
#define SIGN(x) ((x < 0) ? -1 : (x > 0))
```
what yields if x is zero, less than zero, more than zero?
I guess I know the answer, but I'd like to check for clarity...
Thank you
EDIT: added missing parenthesis
EDIT: more info [here](https://stackoverflow.com/questions/1903954/is-there-a-standard-sign-function-signum-sgn-in-c-c)<issue_comment>username_1: It does exactly what you probably *think* it does, gives `-1` for negative numbers, `0` for zero, and `1` for positive numbers.
However, you should generally avoid function-like macros since they will *not* do what you expect if, for example, you try to calculate `SIGN(value++)`. Since they're simple text substitutions, that would resolve to:
```
((value++ < 0) ? -1 : (value++ > 0)
```
You're far better off just using *real* functions and letting the compiler inline them if it decides it's worth it. You can also suggest to the compiler that inlining it, with the `inline` keyword, but keep in mind it *is* a suggestion.
Upvotes: 2 <issue_comment>username_2: That macro got a stray parenthesis.
It looks like it is meant to be an implementation of signum function, which returns -1, 1 or 0 depending on value of argument.
For sake of being safe and writing C++ code, it is prudent
to replace macro by template, similar to
```
template
int SIGN( T x )
{
return (x < T(0)) ? -1 : (x > T(0));
}
```
First comparision is argument of trenary operator ?:. Ternary would return -1 if expression evaluates to true , i.e. x is less than 0, otherwise it would return result of x > T(0).
That expression would evaluated to 0 if x equals to 0, otherwise it would be evaluated to 1.
Note that my implementation is not ideal, you can find better implementation elsewhere on SO.
An alternative expression can be:
```
return (T(0)x);
```
Which may be more effective with platforms that implement certain CPU instructions
Upvotes: 1 <issue_comment>username_3: First, the macro doesn't compute anything. It is substituted into a source code, expanded, and the resulting text gets compiled. What the resulting text is, depends on the way you use the macro, especially on what parameter you give.
Second, the macro lacks one closing paren, so it probably would not give you a meaningful expression to be compiled.
Third, even when you add the lacking paren:
```
#define SIGN(x) ((x < 0) ? -1 : (x > 0))
```
it is possible you get unexpected results if you use the macro in a non-simplest way. For example,
```
SIGN(a ^ b)
```
would result in
```
((a ^ b < 0) ? -1 : (a ^ b > 0))
```
which is interpreted in C and C++ as
```
((a ^ (b < 0)) ? -1 : (a ^ (b > 0)))
```
which certainly is *not* what we intend.
You should add parentheses to avoid unwanted operators binding – for:
```
#define SIGN(x) (((x) < 0) ? -1 : ((x) > 0))
```
the above example will yield a sensible expression
```
(((a ^ b) < 0) ? -1 : ((a ^ b) > 0))
```
but that still doesn't protect you against unwanted double increment/decrement in case of plus-plus or minus-minus operators or double execution of a function in case the expression substituted for `x` contains a function call.
Upvotes: 3 [selected_answer]<issue_comment>username_4: If you use it with values only and not expressions that macro will produce -1, 0, 1, otherwise you may have serious problems. The tricky part is (x>0). Lets read the standard:
>
> **5.9 Relational operators [expr.rel]**
>
>
> The operators < (less than), > (greater than), <= (less than or equal
> to), and >= (greater than or equal to) all yield false or true. The
> type of the result is bool.
>
>
>
and
>
> **3.9.1 Fundamental types [basic.fundamental]**
>
>
> Values of type bool are either true or false. Values of type bool participate in integral promotions (4.5).
>
>
>
Thus x>0 is either `true` or `false`.
>
> **4.5 Integral promotions [conv.prom]**
>
>
> A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.
>
>
>
and is promoted to either `1` or `0` (respectively).
Upvotes: 0 |
2018/03/22 | 1,351 | 4,699 | <issue_start>username_0: I am working on an security analysis for an DB2 setup which uses federated nicknames.
When setting up federated nicknames on DB2 a wrapper and user mappings must be created. For both a username and a password must be stored at the DB2.
```
CREATE SERVER V9SAMPLE TYPE DB2/UDB VERSION 9.1 WRAPPER DRDA
AUTHID "USERNAME" PASSWORD "<PASSWORD>" OPTIONS ( DBNAME 'SAMPLE' );
CREATE USER MAPPING FOR USER SERVER V9SAMPLE OPTIONS
( REMOTE_AUTHID 'USERNAME' REMOTE_PASSWORD '<PASSWORD>' );
```
Can anybody tell me how DB2 stores this credentials internally and if there is any way to read AUTHID and PASSWORD from the database?
I would exprect that they must be stored in plaintext as they must be send to another Server as login credentials. But that could open attack vectors as Mallory could recover the credentials.
Are there any security measures that must be applied to protect the passwords saved for use with wrappers and user mappings?<issue_comment>username_1: It does exactly what you probably *think* it does, gives `-1` for negative numbers, `0` for zero, and `1` for positive numbers.
However, you should generally avoid function-like macros since they will *not* do what you expect if, for example, you try to calculate `SIGN(value++)`. Since they're simple text substitutions, that would resolve to:
```
((value++ < 0) ? -1 : (value++ > 0)
```
You're far better off just using *real* functions and letting the compiler inline them if it decides it's worth it. You can also suggest to the compiler that inlining it, with the `inline` keyword, but keep in mind it *is* a suggestion.
Upvotes: 2 <issue_comment>username_2: That macro got a stray parenthesis.
It looks like it is meant to be an implementation of signum function, which returns -1, 1 or 0 depending on value of argument.
For sake of being safe and writing C++ code, it is prudent
to replace macro by template, similar to
```
template
int SIGN( T x )
{
return (x < T(0)) ? -1 : (x > T(0));
}
```
First comparision is argument of trenary operator ?:. Ternary would return -1 if expression evaluates to true , i.e. x is less than 0, otherwise it would return result of x > T(0).
That expression would evaluated to 0 if x equals to 0, otherwise it would be evaluated to 1.
Note that my implementation is not ideal, you can find better implementation elsewhere on SO.
An alternative expression can be:
```
return (T(0)x);
```
Which may be more effective with platforms that implement certain CPU instructions
Upvotes: 1 <issue_comment>username_3: First, the macro doesn't compute anything. It is substituted into a source code, expanded, and the resulting text gets compiled. What the resulting text is, depends on the way you use the macro, especially on what parameter you give.
Second, the macro lacks one closing paren, so it probably would not give you a meaningful expression to be compiled.
Third, even when you add the lacking paren:
```
#define SIGN(x) ((x < 0) ? -1 : (x > 0))
```
it is possible you get unexpected results if you use the macro in a non-simplest way. For example,
```
SIGN(a ^ b)
```
would result in
```
((a ^ b < 0) ? -1 : (a ^ b > 0))
```
which is interpreted in C and C++ as
```
((a ^ (b < 0)) ? -1 : (a ^ (b > 0)))
```
which certainly is *not* what we intend.
You should add parentheses to avoid unwanted operators binding – for:
```
#define SIGN(x) (((x) < 0) ? -1 : ((x) > 0))
```
the above example will yield a sensible expression
```
(((a ^ b) < 0) ? -1 : ((a ^ b) > 0))
```
but that still doesn't protect you against unwanted double increment/decrement in case of plus-plus or minus-minus operators or double execution of a function in case the expression substituted for `x` contains a function call.
Upvotes: 3 [selected_answer]<issue_comment>username_4: If you use it with values only and not expressions that macro will produce -1, 0, 1, otherwise you may have serious problems. The tricky part is (x>0). Lets read the standard:
>
> **5.9 Relational operators [expr.rel]**
>
>
> The operators < (less than), > (greater than), <= (less than or equal
> to), and >= (greater than or equal to) all yield false or true. The
> type of the result is bool.
>
>
>
and
>
> **3.9.1 Fundamental types [basic.fundamental]**
>
>
> Values of type bool are either true or false. Values of type bool participate in integral promotions (4.5).
>
>
>
Thus x>0 is either `true` or `false`.
>
> **4.5 Integral promotions [conv.prom]**
>
>
> A prvalue of type bool can be converted to a prvalue of type int, with false becoming zero and true becoming one.
>
>
>
and is promoted to either `1` or `0` (respectively).
Upvotes: 0 |
2018/03/22 | 370 | 1,129 | <issue_start>username_0: What I'm trying to do can be explained with this pseudo-code:
if `variable_text1` is either "1", "2", "3" then under the new column called `rating` put "1-3"
Pretty simple but writing it in the "dumb" way is pretty long
```
Table.AddColumn(#"Added cluster_rating", "rating", each if [variable_text1] = "1" then "1-3" else
if [variable_text1] = "2" then "1-3" else
if [variable_text1] = "3" then "1-3" else
null)
```
Problem is when there are a lot of possible textual variable to pick from...is there a smarter way to write this?<issue_comment>username_1: How about using this as your custom column?
```
if Number.FromText([variable_text1]) >= 1 and
Number.FromText([variable_text1]) <= 3
then "1-3"
else null
```
Upvotes: 0 <issue_comment>username_2: It might be easier to implement in PowerBI as a calculated column:
```
IF [variable_text1] In {"1", "2", "3"}, "1-3"
```
No need to use null, it's a default condition for false outcome.
[Edit]:
If you must use power query, try;
```
if List.Contains({"1","2","3"}, [variable_text1]) then "1-3" else null
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 438 | 1,686 | <issue_start>username_0: I'd like to read a .xlsx using python pandas. The problem is the at the beginning of the excel file, it has some additional data like title or description of the table and tables contents starts. That introduce the unnamed columns because pandas DataReader takes it as the columns.
But tables contents starts after few lines later.
```
A B C
this is description
last updated: Mar 18th,2014
Table content
Country Year Product_output
Canada 2017 3002
Bulgaria 2016 2201
...
```
The table content starts in line 4. And columns must be "Country", "year", "proudct\_output" instead "this is description", "unnamed", "unnamed". For this specific case, setting `skiprows` parameter to 3 solved the issue(from <NAME>). But I have to deal with many excel files and I don't know how many rows to skip in advance.
I think there might be a solution since each table column header has a filter.<issue_comment>username_1: How about using this as your custom column?
```
if Number.FromText([variable_text1]) >= 1 and
Number.FromText([variable_text1]) <= 3
then "1-3"
else null
```
Upvotes: 0 <issue_comment>username_2: It might be easier to implement in PowerBI as a calculated column:
```
IF [variable_text1] In {"1", "2", "3"}, "1-3"
```
No need to use null, it's a default condition for false outcome.
[Edit]:
If you must use power query, try;
```
if List.Contains({"1","2","3"}, [variable_text1]) then "1-3" else null
```
Upvotes: 2 [selected_answer] |
2018/03/22 | 1,246 | 4,140 | <issue_start>username_0: I am trying to test my redux-sagas with the redux-saga-test-plan library to make things easier. All tests are run in a JEST environment.
To help me structure my tests on a forked saga I followed the documentation here: <https://github.com/jfairbank/redux-saga-test-plan/blob/master/docs/integration-testing/forked-sagas.md>
But when I try to run the test i get this error:
```
TypeError: Cannot read property 'name' of undefined
12 | .put(setMenu(menuList))
13 | .dispatch('SET_MENU_REQUEST', menuList)
> 14 | .run()
15 | })
16 |
```
**My test (updated):**
```
import { expectSaga } from 'redux-saga-test-plan'
import { call, put, takeLatest, takeEvery } from "redux-saga/effects";
import menuSaga from '../../sagas/MenuSaga'
import { applyMenu } from '../../sagas/MenuSaga'
import { menuList } from '../../stubs/menuList'
import { setMenu } from '../../reducers/menuReducer'
it("Sets a new menu", () => {
return expectSaga(applyMenu)
.put(setMenu(menuList))
.dispatch('SET_MENU_REQUEST', menuList)
.run()
})
```
**update:**
I found some [documentation](http://redux-saga-test-plan.jeremyfairbank.com/unit-testing/saga-helpers.html) on how to utilize effect-helpers (takeEvery, takeLatest) and tried that too, but to no effect, it just causes a new error.
test with effect-helper:
```
it("Sets a new menu", () => {
return expectSaga(menuSaga)
.next()
.put(setMenu(menuList))
.takeEvery('SET_MENU_REQUEST', applyMenu)
.finish()
.isDone()
})
```
The error it throws:
```
TypeError: (0 , _reduxSagaTestPlan.expectSaga)(...).next is not a function
10 |
11 | return expectSaga(menuSaga)
> 12 | .next()
13 | .put(setMenu(menuList))
14 | .takeEvery('SET_MENU_REQUEST', applyMenu)
15 | .finish()
```
**The saga I am trying to test:**
```
import {fork, put, select, call} from 'redux-saga/effects'
import {takeEvery, takeLatest} from 'redux-saga'
import { handleRequest } from './serverSaga'
import { setMenu } from '../reducers/menuReducer'
const POST_MENU_REQUEST = 'POST_MENU_REQUEST'
const GET_MENU_REQUEST = 'GET_MENU_REQUEST'
const SET_MENU_REQUEST = 'SET_MENU_REQUEST'
export function setMenuRequest(menu) {return {type: SET_MENU_REQUEST, menu}}
export function postMenuRequest(data) {return {type: POST_MENU_REQUEST, data}}
export function getMenuRequest() {return {type: GET_MENU_REQUEST}}
export function* applyMenu(menu) {
yield put(setMenu(menu))
}
function* postNewMenu(data){
yield call(handleRequest, '/admin/menu' ,'POST', data)
}
function* getMenu(){
let response = yield call(handleRequest, "/admin/menu", "GET")
if(response){
yield put(setMenu(response))
}
}
export default function* menuSaga(){
yield [
fork(function*() {
yield takeEvery(POST_MENU_REQUEST, postNewMenu)
}),
fork(function*() {
yield takeEvery(GET_MENU_REQUEST, getMenu)
}),
fork(function*(){
yield takeEvery(SET_MENU_REQUEST, applyMenu)
})
]
}
```
As you can see I have tried to export the generator-function that I want to test, even though I don't think this is optimal since the test shouldn't require me to change my code just to test it, so I'm probably missing something.
The stub menuList has a structure like this:
```
Date: '',
Id: '',
ClosingTime: '',
MenuItems: [],
```
It's proving to be not-so-straigthforward to test my sagas since they are all structured like this one (forked) and there doesn't seem to be a lot of documentation as to how to test them properly.<issue_comment>username_1: Probably, your problem is that you are importing and using *expectSaga* from redux-saga-test-plan when it should be *testSaga*
Upvotes: 1 <issue_comment>username_2: The problem is that your are mixing redux-saga-test-plan's unit tests with their integration tests.
```
expectSaga(menuSaga) // this is an integration test function
.next() // this is a unit test function
.put(setMenu(menuList))
.takeEvery('SET_MENU_REQUEST', applyMenu)
.finish()
```
see: <https://redux-saga-test-plan.jeremyfairbank.com/integration-testing/>
Upvotes: 0 |
2018/03/22 | 981 | 3,956 | <issue_start>username_0: I am currently facing the following problem with a `Menu Strip` containing several different settings such as:
* Show X
* Show Y
* Show Z
All those items have corresponding properties of the type `bool`, because those variables are also passed to other classes. Currently, when I click on "Show Y", I have a dedicated function called `HandleShowY()` which toggles the `bool` and the checkmark within the Menu Strip Item.
A new method for every newly added property seems like a huge code smell to me and requires a ton of added overhead for each new property. Thus, I came up with the idea to make a generic `HandleMenuStripItemBool()` which receives the property and the menu item by reference, such that only one method exists to handle this type of behaviour.
Unfortunately, I am running into problems while trying to pass my `bool` property to this method by reference, my knowledge of `action`, `func` and `delegate` has mostly faded away and only confuses me more and more after every new tutorial I read.
Example code:
```
// different properties of type bool, defined in form1
private bool ShowX { get; set; }
private bool ShowY { get; set; }
// generic menu strip item bool handler
private void HandleMenuStripItemBool(bool boolProp, ToolStripMenuItem menuItem)
{
// toggle bool depending on current value
// add check mark to or remove check mark from ToolStripMenuItem
}
// click event of the "Show X" menu strip item, defined in form1
private void showXToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleMenuStripItemBool(ShowX, showXToolStripMenuItem);
}
// click event of the "Show Y" menu strip item, defined in form1
private void showYToolStripMenuItem_Click(object sender, EventArgs e)
{
HandleMenuStripItemBool(ShowY, showYToolStripMenuItem);
}
```
TL;DR: what is the best way to create a method which receives a property of the type `bool` by reference, in such a way that the method can be reused for several other properties?
Thanks in advance.<issue_comment>username_1: You can pass it as reference and work on it inside the method:
```
bool testBool;
ToggleBoolValue(ref testBool);
private void ToggleBoolValue(ref bool toggle)
{
toggle = !toggle;
// some other tasks
}
```
Upvotes: 0 <issue_comment>username_2: **If** you're using a very modern version of C# (7.0 or later, I think), then you can make your properties be `ref` returning, and then use `ref` as Michal suggested:
```
using System;
public class Bob
{
static void Main()
{
var b = new Bob();
b.showYToolStripMenuItem_Click();
Console.WriteLine(b.ShowY);
Console.ReadLine();
}
// different properties of type bool, defined in form1
private ref bool ShowX { get { return ref _showX; } }
private ref bool ShowY { get { return ref _showY; } }
private bool _showX = false;
private bool _showY = false;
// generic menu strip item bool handler
private void HandleMenuStripItemBool(ref bool boolProp)
{
boolProp = true;
}
// click event of the "Show X" menu strip item, defined in form1
private void showXToolStripMenuItem_Click()
{
HandleMenuStripItemBool(ref ShowX);
}
// click event of the "Show Y" menu strip item, defined in form1
private void showYToolStripMenuItem_Click()
{
HandleMenuStripItemBool(ref ShowY);
}
}
```
(Main added and irrelevant parameters removed to make this a self-contained console demo)
Upvotes: 0 <issue_comment>username_3: While not specifically answering how to pass the bool property by reference, why not just use the `Checked` value of the menu item, in which case you won't need to maintain the value of the bool property, and will only have a single source of truth
```
private bool ShowX
{
get { return showXToolStripMenuItem.Checked; }
set { showXToolStripMenuItem.Checked = value; }
}
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 1,368 | 3,376 | <issue_start>username_0: I think "end" will be print in for loop, but this is wrong, can you tell me why. This is code:
```
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
for (NSUInteger i = 0; i < 1000; i++) {
dispatch_async(queue, ^{
NSLog(@"i:%lu", (unsigned long)i);
});
}
dispatch_async(queue, ^{
NSLog(@"end:%@", [NSThread currentThread]);
});
```
Result:
```
2018-03-22 19:26:33.812371+0800 MyIOSNote[96704:912772] i:990
2018-03-22 19:26:33.812671+0800 MyIOSNote[96704:912801] i:991
2018-03-22 19:26:33.812935+0800 MyIOSNote[96704:912662] i:992
2018-03-22 19:26:33.813295+0800 MyIOSNote[96704:912802] i:993
2018-03-22 19:26:33.813552+0800 MyIOSNote[96704:912766] i:994
2018-03-22 19:26:33.813856+0800 MyIOSNote[96704:912778] i:995
2018-03-22 19:26:33.814299+0800 MyIOSNote[96704:912803] i:996
2018-03-22 19:26:33.814648+0800 MyIOSNote[96704:912779] i:997
2018-03-22 19:26:33.814930+0800 MyIOSNote[96704:912759] i:998
2018-03-22 19:26:33.815361+0800 MyIOSNote[96704:912804] i:999
2018-03-22 19:26:33.815799+0800 MyIOSNote[96704:912805] end:{number = 3, name = (null)}
```<issue_comment>username_1: For loop code runs in main Queue (Serial) so the for loop ends then the end statement is printed , if you wrapped the for loop inside the async like this
```
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
for (NSUInteger i = 0; i < 1000; i++) {
NSLog(@"i:%lu", (unsigned long)i);
}
});
dispatch_async(queue, ^{
NSLog(@"end:%@", [NSThread currentThread]);
});
```
you will get this

Upvotes: 0 <issue_comment>username_2: Look at the order of execution. You first enqueue 1000 blocks to print a number. Then you enqueue the block to print "end". All of those blocks are enqueued to run asynchronously on the same concurrent background queue. All 1001 calls to `dispatch_async` are being done in order, one at a time, on whatever thread this code is being run on which is from a different queue all of the enqueued blocks will be run on.
The concurrent queue will pop each block in the order it was enqueued and run it. Since it is a concurrent queue and since each is to be run asynchronously, in theory, some of them could be a bit out of order. But in general, the output will appear in the same order because each block does exactly the same thing - a simple `NSLog` statement.
But the short answer is that "end" is printed last because it was enqueued last, after all of the other blocks have been enqueued.
What may help is to log each call as it is enqueued:
```
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
for (NSUInteger i = 0; i < 1000; i++) {
NSLog(@"enqueue i: %lu", (unsigned long)i);
dispatch_async(queue, ^{
NSLog(@"run i: %lu", (unsigned long)i);
});
}
NSLog(@"enqueue end");
dispatch_async(queue, ^{
NSLog(@"run end: %@", [NSThread currentThread]);
});
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: To combine both of the previous answers, the reason you see `end` printed last is because you enqueue serially, but each block executes very quickly. By the time you enqueue the log of `end`, all the other blocks have already executed.
Upvotes: 0 |
2018/03/22 | 2,336 | 6,143 | <issue_start>username_0: Here is my package.json:
```
{
"name": "DFS",
"version": "1.0.0",
"description": "DFS App",
"author": "asd",
"private": true,
"nodemonConfig": {
"delay": "2500"
},
"scripts": {
"postinstall": "npm run build",
"dev": "node build/dev-server.js",
"start": "node build/dev-server.js",
"build": "node build/build.js",
"unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run",
"e2e": "node test/e2e/runner.js",
"test": "npm run unit && npm run e2e",
"lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs",
"deploy": "git subtree push --prefix dist heroku master"
},
"dependencies": {
"axios": "^0.16.2",
"connect-history-api-fallback": "^1.5.0",
"express-sslify": "^1.2.0",
"global": "^4.3.2",
"heroku-ssl-redirect": "0.0.4",
"less": "^3.0.1",
"less-loader": "^4.0.5",
"node-sass": "^4.7.2",
"npm-watch": "^0.3.0",
"sass-loader": "^6.0.6",
"style-loader": "^0.20.2",
"vee-validate": "^2.0.0-rc.14",
"vue": "^2.3.3",
"vue-router": "^2.3.1",
"vuetify": "^1.0.3",
"vuex": "^3.0.1",
"webpack-dev-server": "^3.0.0",
"webpack-watch": "^0.2.0"
},
"devDependencies": {
"autoprefixer": "^7.1.2",
"babel-core": "^6.22.1",
"babel-eslint": "^7.1.1",
"babel-helper-vue-jsx-merge-props": "^2.0.3",
"babel-loader": "^7.1.1",
"babel-plugin-istanbul": "^4.1.1",
"babel-plugin-syntax-jsx": "^6.18.0",
"babel-plugin-transform-runtime": "^6.22.0",
"babel-plugin-transform-vue-jsx": "^3.5.0",
"babel-preset-env": "^1.3.2",
"babel-preset-stage-2": "^6.22.0",
"babel-register": "^6.22.0",
"chai": "^3.5.0",
"chalk": "^2.0.1",
"chromedriver": "^2.27.2",
"connect-history-api-fallback": "^1.3.0",
"copy-webpack-plugin": "^4.0.1",
"cross-env": "^5.0.1",
"cross-spawn": "^5.0.1",
"css-loader": "^0.28.0",
"cssnano": "^3.10.0",
"eslint": "^3.19.0",
"eslint-config-standard": "^6.2.1",
"eslint-friendly-formatter": "^3.0.0",
"eslint-loader": "^1.7.1",
"eslint-plugin-html": "^3.1.0",
"eslint-plugin-import": "^2.7.0",
"eslint-plugin-node": "^5.2.0",
"eslint-plugin-promise": "^3.4.0",
"eslint-plugin-standard": "^2.0.1",
"eslint-plugin-vue": "^4.0.0",
"eventsource-polyfill": "^0.9.6",
"express": "^4.14.1",
"extract-text-webpack-plugin": "^2.0.0",
"file-loader": "^0.11.1",
"friendly-errors-webpack-plugin": "^1.1.3",
"html-webpack-plugin": "^2.28.0",
"http-proxy-middleware": "^0.17.3",
"inject-loader": "^3.0.0",
"karma": "^1.4.1",
"karma-coverage": "^1.1.1",
"karma-mocha": "^1.3.0",
"karma-phantomjs-launcher": "^1.0.2",
"karma-phantomjs-shim": "^1.4.0",
"karma-sinon-chai": "^1.3.1",
"karma-sourcemap-loader": "^0.3.7",
"karma-spec-reporter": "0.0.31",
"karma-webpack": "^2.0.2",
"lolex": "^2.0.0",
"mocha": "^3.2.0",
"nightwatch": "^0.9.12",
"node-notifier": "^5.1.2",
"opn": "^5.1.0",
"optimize-css-assets-webpack-plugin": "^2.0.0",
"ora": "^1.2.0",
"phantomjs-prebuilt": "^2.1.15",
"portfinder": "^1.0.13",
"postcss-import": "^11.0.0",
"postcss-loader": "^2.0.8",
"postcss-url": "^7.2.1",
"rimraf": "^2.6.0",
"selenium-server": "^3.0.1",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"sinon": "^2.1.0",
"sinon-chai": "^2.8.0",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",
"sw-precache-webpack-plugin": "^0.11.4",
"ts-loader": "^3.5.0",
"uglify-es": "^3.0.25",
"url-loader": "^0.5.8",
"vue-loader": "^12.1.0",
"vue-style-loader": "^3.0.1",
"vue-template-compiler": "^2.3.3",
"webpack": "^2.6.1",
"webpack-bundle-analyzer": "^2.2.1",
"webpack-cli": "^2.0.9",
"webpack-dev-middleware": "^1.10.0",
"webpack-hot-middleware": "^2.18.0",
"webpack-merge": "^4.1.0"
},
"engines": {
"node": ">= 4.0.0",
"npm": ">= 3.0.0"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
]
}
```
My main.js:
```
import Vue from 'vue'
import Vuetify from 'vuetify' // eslint-disable-line no-unused-vars
// import App from './App'
// import router from './router'
Vue.use(Vuetify)
// Vue.config.productionTip = false
new Vue({ // eslint-disable-line no-new
el: '#app',
// router,
template: 'hi there'
// components: { App },
// template: ''
})
```
My App.vue
```
123
export default {
name: 'App'
}
```
I am using Heroku for the app hosting. When I try to visit site with desktop browser all is okay, but when I try to load it via mobile browser it shows the blank page.
For the other hand deploying this repo: <https://github.com/deepak-singh/vue-blog-pwa>
is successfully done and loading via mobile or desktop browser is successful.
Also I found that this line causes blank page in my vue app:
```
Vue.use(Vuetify)
```
But! This line is present in vue-pwa-blog repo file. So I can not understand what may I doing wrong?<issue_comment>username_1: This is happening because when a PWA is installed and opened on a phone it rewrites the URL to /index.html whereas the vuetify app is rendered at /.
Just re-adjust your vue-router to load the component at /index.html too and it should work.
Your router.js could look something like this:
```
{
path: '/',
name: 'App',
component: App
},
{
path: '/index.html',
name: 'App',
component: App
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: My routers are like this:
```
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/index.html',
name: 'HelloWorld',
component: HelloWorld
}
]
})
```
Still blank page.. If i remove my Vue.use(Vuetify) from main.js works..
Package.json ->
```
"dependencies": {
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"vuetify": "^1.1.6"
},
```
Upvotes: 0 |
2018/03/22 | 823 | 3,144 | <issue_start>username_0: I have downloaded App Owns Data from github - <https://github.com/Microsoft/PowerBI-Developer-Samples>. I have added Row Level Security by adding the following line:
```
generateTokenRequestParameters = new GenerateTokenRequest("View", null,
identities: new List{new EffectiveIdentity(username: "username", roles: new List { "Role A"}, datasets: new List { report.DatasetId })});
```
Currently, I can add only one username at a time. Is there any way using which I can multiple users and assign different roles to them?
Any help is appreciated!<issue_comment>username_1: In a single GenerateTokenRequest you need to pass an equal number of EffectiveIdentitys as the number of passed datasets. This means that for embedding a dashboard (may contain tiles with different datasets) you will be able to pass multiple EffectiveIdentity with different usernames. But for report embed (has a single dataset) you can only pass one username.
Upvotes: 0 <issue_comment>username_2: You need to add row level security by adding roles in power bi desktop -
1. Modeling => Manage Roles
2. Create
3. Give your role a name e.g Role A
4. Select a table under Tables to filter on
5. in the Table filter DAX expression add [column\_name\_here] = USERNAME()
6. The username that you pass into your GenerateTokenRequest will be passed to USERNAME()
Adding multiple usernames to the GenerateTokenRequest would be counter intuitive as it is designed to generate a token for a single user viewing the embedded report.
If you have different usernames in different tables for the same user then you could create a look up table where usernameA maps to username1 on table1, username2 on table 2 etc.
If you can provide more details on your use case I'd be happy to try and help
Upvotes: 2 [selected_answer]<issue_comment>username_3: A little late but... if you have multiple usernames assigned to a role, pass the usernames as a string path to RLS, parse it into a table, then return the row when it matches with a value in the column. It feels like a re-invention of the for loop...
We do this if we are not actually passing usernames, but for cases like multiple sales offices, or making a view that compares data from multiple user accounts, or when a user belongs to different hierarchies in an organization, or basically any time you want to use multiple filters..
example input using sales ids
```
//Username() = "020104010|020104061|020104303|020104304"
//DAX
var userIds = Username()
VAR tbl=
GENERATE (
GENERATESERIES(1,PATHLENGTH(UserIds),1),
ROW ( "Key", PATHITEM ( userIds, [value]))
)
VAR valueList =
SELECTCOLUMNS ( tbl, "Key", [Key] )
return [sales_id_column] in valueList
```
There is also a case when the table has a many to many relationship and cannot use multiple roles as identity. In that case the username looks like this:
```
Username() = "SalesHead:020104010|SalesLead:020104061|SalesUser:020104303"
```
and the code will have an extra step to parse the inner path after you change the ":" to a "|". This approach supports a claims-based authorization.
Upvotes: 0 |
2018/03/22 | 696 | 2,178 | <issue_start>username_0: Here we have a `textarea` in html file
```
some text
```
above in head I have next kind of string :
```
function do_resize(textbox) {
var maxrows=50;
var txt=textbox.value;
var cols=textbox.cols;
var arraytxt=txt.split('\n');
var rows=arraytxt.length;
for (i=0;imaxrows) {
document.getElementById("textvalue").rows = maxrows
}else{
document.getElementById("textvalue").rows = rows
}
}
```
When I click on text area of y `textrea` box don't changes .. I can't undestand why . Who can help me with ?
I want to get this one :
[](https://i.stack.imgur.com/w8ekE.png)
but I have got this one all the time :
[](https://i.stack.imgur.com/z58iH.png)<issue_comment>username_1: The issue is due to the height of the inline style. I suggest using another event instead of click ( In my example I use [Input Event](https://developer.mozilla.org/en-US/docs/Web/Events/input) -
the DOM input event is fired synchronously when the value of the textarea element is changed)
```js
function do_resize(textbox) {
var maxrows=50;
var txt=textbox.value;
var cols=textbox.cols;
var arraytxt=txt.split('\n');
var rows=arraytxt.length;
for (i=0;imaxrows) {
document.getElementById("textvalue").rows = maxrows
}else{
document.getElementById("textvalue").rows = rows
}
}
document.getElementById("textvalue").addEventListener('input', function (evt) {
do\_resize(this);
});
```
```html
some text
```
Upvotes: 1 <issue_comment>username_2: Try this code: <https://plnkr.co/edit/teZXdtA55JqZq9v0umdD?p=preview>
For reference:
```
some text
function do\_resize(textbox) {
var maxrows=50;
var txt=textbox.value;
var cols=textbox.cols;
var arraytxt=txt.split('\n');
var rows=arraytxt.length;
console.log(arraytxt)
for (i=0;i<arraytxt.length;i++){
rows+=parseInt(arraytxt[i].length/cols);
}
if (rows>maxrows) {
document.getElementById("textvalue").rows = maxrows
}else{
document.getElementById("textvalue").rows = rows
}
}
```
Upvotes: 0 |
2018/03/22 | 577 | 1,759 | <issue_start>username_0: I have created a graph from list of nodes using `networkx`. It has self loops. How to remove them? Following is sample:
```
import networkx as NX
G=NX.Graph()
G.add_edge(1,2)
G.add_edge(1,1)
print (G.edges())
[(1, 2), (1, 1)]
```
I don't want `(1, 1)` edges.<issue_comment>username_1: The method [`remove_edge`](https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.remove_edge.html?highlight=remove_edge#networkx.Graph.remove_edge) does what you need. Simply filter for when the edge source and destination are the same:
```
for u, v in G.edges_iter():
if u == v:
G.remove_edge(u,v)
```
Upvotes: 1 <issue_comment>username_2: (instructions for networkx 1.x below)
If you're using networkx 2.x try
```
G.remove_edges_from(nx.selfloop_edges(G))
```
If you have a `MultiGraph` (which for example `configuration_model` produces), this may not work if you have an older release of 2.x with a minor bug. If so and you don't want to upgrade, then you need to convert this into a list before removing edges.
```
G.remove_edges_from(list(nx.selfloop_edges(G)))
```
This bug has been corrected <https://github.com/networkx/networkx/issues/4068>.
---
In **version 1.x** (when I originally answered this question), it was:
```
G.remove_edges_from(G.selfloop_edges())
```
Upvotes: 6 [selected_answer]<issue_comment>username_3: The previous method will be deprecated: use nx.selfloop\_edges() instead
Upvotes: 2 <issue_comment>username_4: The selfloop methods were deprecated as graph methods in favor of networkx functions in version 2.0.
version 1.x:
```
G.remove_edges_from(G.selfloop_edges())
```
version 2.x:
```
G.remove_edges_from(nx.selfloop_edges(G))
```
Upvotes: 4 |
2018/03/22 | 10,477 | 13,683 | <issue_start>username_0: I am plotting the following data:
```
myDates = ['2017-05-17', '2017-05-24', '2017-05-25', '2017-05-26', '2017-05-27', '2017-05-29', '2017-05-31', '2017-06-01', '2017-06-03', '2017-06-04', '2017-06-05', '2017-06-06', '2017-06-07', '2017-06-08', '2017-06-10', '2017-06-11', '2017-06-12', '2017-06-13', '2017-06-15', '2017-06-16', '2017-06-17', '2017-06-18', '2017-06-19', '2017-06-20', '2017-06-21', '2017-06-22', '2017-06-23', '2017-06-24', '2017-06-25', '2017-06-26', '2017-06-27', '2017-06-28', '2017-06-29', '2017-06-30', '2017-07-01', '2017-07-02', '2017-07-04', '2017-07-05', '2017-07-07', '2017-07-08', '2017-07-10', '2017-07-13', '2017-07-15', '2017-07-16', '2017-07-17', '2017-07-18', '2017-07-19', '2017-07-20', '2017-07-23', '2017-07-24', '2017-07-25', '2017-07-27', '2017-07-28', '2017-07-29', '2017-07-31', '2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04', '2017-08-06', '2017-08-07', '2017-08-08', '2017-08-09', '2017-08-10', '2017-08-11', '2017-08-12', '2017-08-14', '2017-08-15', '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19', '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23', '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27', '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31', '2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04', '2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08', '2017-09-10', '2017-09-11', '2017-09-12', '2017-09-13', '2017-09-14', '2017-09-15', '2017-09-16', '2017-09-17', '2017-09-18', '2017-09-19', '2017-09-20', '2017-09-21', '2017-09-22', '2017-09-23', '2017-09-24', '2017-09-25', '2017-09-26', '2017-09-27', '2017-09-28', '2017-09-29', '2017-09-30', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06', '2017-10-07', '2017-10-08', '2017-10-09', '2017-10-10', '2017-10-12', '2017-10-13', '2017-10-14', '2017-10-15', '2017-10-16', '2017-10-18', '2017-10-19', '2017-10-20', '2017-10-21', '2017-10-22', '2017-10-23', '2017-10-25', '2017-10-26', '2017-10-27', '2017-10-28', '2017-10-30', '2017-10-31', '2017-11-01', '2017-11-03', '2017-11-04', '2017-11-05', '2017-11-08', '2017-11-09', '2017-11-10', '2017-11-11', '2017-11-12', '2017-11-13', '2017-11-14', '2017-11-15', '2017-11-18', '2017-11-19', '2017-11-20', '2017-11-21', '2017-11-22', '2017-11-23', '2017-11-24', '2017-11-25', '2017-11-26', '2017-11-27', '2017-11-28', '2017-11-29', '2017-11-30', '2017-12-01', '2017-12-02', '2017-12-03', '2017-12-04', '2017-12-05', '2017-12-06', '2017-12-07', '2017-12-08', '2017-12-09', '2017-12-10', '2017-12-11', '2017-12-12', '2017-12-13', '2017-12-14', '2017-12-15', '2017-12-16', '2017-12-17', '2017-12-18', '2017-12-19', '2017-12-20', '2017-12-21', '2017-12-22', '2017-12-23', '2017-12-24', '2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28', '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11', '2018-01-12', '2018-01-13', '2018-01-14', '2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18', '2018-01-19', '2018-01-20', '2018-01-21', '2018-01-22', '2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26', '2018-01-27', '2018-01-28', '2018-01-29', '2018-01-30', '2018-01-31', '2018-02-01', '2018-02-02', '2018-02-03', '2018-02-04', '2018-02-05', '2018-02-06', '2018-02-07', '2018-02-08', '2018-02-09', '2018-02-10', '2018-02-11', '2018-02-12', '2018-02-13', '2018-02-14', '2018-02-15', '2018-02-17', '2018-02-18', '2018-02-19', '2018-02-20', '2018-02-21', '2018-02-22', '2018-02-23', '2018-02-24', '2018-02-25', '2018-02-26', '2018-02-27', '2018-02-28', '2018-03-01', '2018-03-02', '2018-03-03', '2018-03-04', '2018-03-05', '2018-03-06', '2018-03-07', '2018-03-08', '2018-03-09', '2018-03-11', '2018-03-13', '2018-03-14', '2018-03-15', '2018-03-16', '2018-03-17', '2018-03-18', '2018-03-19', '2018-03-20', '2018-03-21']
myValues = [100, 101, 105, 106, 109, 110, 111, 165, 189, 193, 195, 196, 203, 210, 211, 214, 223, 224, 225, 226, 230, 231, 240, 249, 257, 266, 270, 273, 274, 282, 285, 291, 298, 300, 301, 303, 304, 306, 307, 308, 310, 311, 314, 315, 320, 322, 325, 328, 330, 342, 343, 346, 348, 349, 373, 380, 387, 391, 392, 395, 397, 401, 403, 408, 414, 420, 421, 422, 475, 477, 481, 484, 487, 490, 492, 500, 503, 504, 510, 511, 512, 515, 520, 521, 524, 526, 529, 530, 531, 534, 538, 541, 548, 553, 561, 565, 569, 574, 581, 585, 588, 592, 593, 597, 599, 602, 605, 608, 612, 615, 617, 624, 626, 631, 635, 638, 640, 644, 649, 652, 654, 656, 663, 665, 667, 676, 682, 684, 685, 686, 688, 691, 692, 708, 711, 712, 713, 714, 716, 717, 718, 719, 749, 755, 757, 758, 761, 762, 763, 764, 771, 772, 774, 778, 781, 788, 821, 835, 840, 848, 855, 861, 869, 884, 894, 913, 919, 928, 933, 940, 946, 949, 957, 965, 974, 984, 989, 996, 1001, 1055, 1057, 1059, 1067, 1079, 1083, 1092, 1101, 1109, 1112, 1116, 1121, 1138, 1159, 1174, 1192, 1204, 1222, 1230, 1253, 1264, 1270, 1277, 1287, 1293, 1298, 1301, 1313, 1326, 1330, 1336, 1354, 1361, 1367, 1376, 1404, 1405, 1437, 1465, 1479, 1533, 1553, 1571, 1584, 1600, 1624, 1631, 1643, 1663, 1672, 1679, 1690, 1696, 1707, 1712, 1716, 1725, 1728, 1733, 1739, 1740, 1741, 1750, 1755, 1762, 1764, 1788, 1792, 1800, 1811, 1815, 1822, 1829, 1836, 1842, 1843, 1849, 1850, 1851, 1855, 1858, 1862, 1863, 1865, 1867, 1869, 1871, 1872, 1874, 1875, 1876, 1878, 1882, 1885]
```
`myDates` is a list of dates (formatted using `datetime`). `myValues` is a list of integers. And I am making the following plot:
```
import matplotlib.pyplot as plt
plt.plot_date(x = myDates, y = myValues)
plt.xlabel('Dates')
plt.ylabel('Cumulative values')
plt.show()
```
However, the labels in the x axes are not clearly visible. How can I make ticks only for year-month values? Concretely, I would like ticks for: `2017-05, 2017-06, 2017-07, ..., 2018-02, 2018-03`. If possible, I'd like the text at an angle so it doesn't run on top of the next tick label.<issue_comment>username_1: You should be able to get what you need with:
```
f, ax = plt.subplots(figsize=(8,8))
ax.plot_date(x = myDates, y = myValues)
ax.set_xticklabels(myDates, rotation=45, size=20)
ax.set_ylabel('Cumulative # of wallet addresses')
plt.show()
```
Just change the size and rotation set in line: `ax.set_xticklabels()`
EDIT:
```
f, ax = plt.subplots(figsize=(20,10))
ax.plot_date(x=myDates, y=myValues)
ax.set_ylabel('Cumulative # of wallet addresses')
ax.yaxis.set_tick_params(labelsize=14) # Sets size of the y ticklabels
ax.set_xticks(myDates) # Sets the positions of the ticks
ax.set_xticklabels(myDates, rotation=45, size=20, ha="right") # Sets a label on each tick
ax.xaxis.set_tick_params(length=12) # Sets length of the ticks
# Hides ticks and labels according to their position (here 1 in 7 is shown)
x = 0
for label, tick in zip(ax.xaxis.get_ticklabels(), ax.xaxis.majorTicks):
if x % 7 != 0 :
label.set_visible(False)
tick.set_visible(False)
x += 1
plt.show()
```
Changing the modulo value in `if x % 7 != 0` modifies the number of ticks you will show on the plot. Bigger value for fewer ticks and labels. It is important to set ha="right" otherwise the rotation makes it uncomfortable to see which label goes with which tick.
Upvotes: 2 <issue_comment>username_2: As @ImportanceOfBeingErnest pointed out, `myDates` were strings. Once I formatted them properly as dates using the following code:
```
myDates = [datetime.datetime.strptime(d, '%Y-%m-%d') for d in myDates]
```
it all worked out, i.e. the plot automatically set ticks for the month-year only.
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can go the lazy way and use [pandas.to\_datetime](https://pandas.pydata.org/pandas-docs/stable/timeseries.html) to convert your x-axis values to date times (rather than strings) and let `matplotlib` worry about getting a better spacing/rotation using [fig.autofmt\_xdate](https://matplotlib.org/1.3.1/users/recipes.html)`
```
import matplotlib.pyplot as plt
import pandas as pd
myDates = ['2017-05-17', '2017-05-24', '2017-05-25', '2017-05-26', '2017-05-27', '2017-05-29', '2017-05-31', '2017-06-01', '2017-06-03', '2017-06-04', '2017-06-05', '2017-06-06', '2017-06-07', '2017-06-08', '2017-06-10', '2017-06-11', '2017-06-12', '2017-06-13', '2017-06-15', '2017-06-16', '2017-06-17', '2017-06-18', '2017-06-19', '2017-06-20', '2017-06-21', '2017-06-22', '2017-06-23', '2017-06-24', '2017-06-25', '2017-06-26', '2017-06-27', '2017-06-28', '2017-06-29', '2017-06-30', '2017-07-01', '2017-07-02', '2017-07-04', '2017-07-05', '2017-07-07', '2017-07-08', '2017-07-10', '2017-07-13', '2017-07-15', '2017-07-16', '2017-07-17', '2017-07-18', '2017-07-19', '2017-07-20', '2017-07-23', '2017-07-24', '2017-07-25', '2017-07-27', '2017-07-28', '2017-07-29', '2017-07-31', '2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04', '2017-08-06', '2017-08-07', '2017-08-08', '2017-08-09', '2017-08-10', '2017-08-11', '2017-08-12', '2017-08-14', '2017-08-15', '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19', '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23', '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27', '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31', '2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04', '2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08', '2017-09-10', '2017-09-11', '2017-09-12', '2017-09-13', '2017-09-14', '2017-09-15', '2017-09-16', '2017-09-17', '2017-09-18', '2017-09-19', '2017-09-20', '2017-09-21', '2017-09-22', '2017-09-23', '2017-09-24', '2017-09-25', '2017-09-26', '2017-09-27', '2017-09-28', '2017-09-29', '2017-09-30', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06', '2017-10-07', '2017-10-08', '2017-10-09', '2017-10-10', '2017-10-12', '2017-10-13', '2017-10-14', '2017-10-15', '2017-10-16', '2017-10-18', '2017-10-19', '2017-10-20', '2017-10-21', '2017-10-22', '2017-10-23', '2017-10-25', '2017-10-26', '2017-10-27', '2017-10-28', '2017-10-30', '2017-10-31', '2017-11-01', '2017-11-03', '2017-11-04', '2017-11-05', '2017-11-08', '2017-11-09', '2017-11-10', '2017-11-11', '2017-11-12', '2017-11-13', '2017-11-14', '2017-11-15', '2017-11-18', '2017-11-19', '2017-11-20', '2017-11-21', '2017-11-22', '2017-11-23', '2017-11-24', '2017-11-25', '2017-11-26', '2017-11-27', '2017-11-28', '2017-11-29', '2017-11-30', '2017-12-01', '2017-12-02', '2017-12-03', '2017-12-04', '2017-12-05', '2017-12-06', '2017-12-07', '2017-12-08', '2017-12-09', '2017-12-10', '2017-12-11', '2017-12-12', '2017-12-13', '2017-12-14', '2017-12-15', '2017-12-16', '2017-12-17', '2017-12-18', '2017-12-19', '2017-12-20', '2017-12-21', '2017-12-22', '2017-12-23', '2017-12-24', '2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28', '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11', '2018-01-12', '2018-01-13', '2018-01-14', '2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18', '2018-01-19', '2018-01-20', '2018-01-21', '2018-01-22', '2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26', '2018-01-27', '2018-01-28', '2018-01-29', '2018-01-30', '2018-01-31', '2018-02-01', '2018-02-02', '2018-02-03', '2018-02-04', '2018-02-05', '2018-02-06', '2018-02-07', '2018-02-08', '2018-02-09', '2018-02-10', '2018-02-11', '2018-02-12', '2018-02-13', '2018-02-14', '2018-02-15', '2018-02-17', '2018-02-18', '2018-02-19', '2018-02-20', '2018-02-21', '2018-02-22', '2018-02-23', '2018-02-24', '2018-02-25', '2018-02-26', '2018-02-27', '2018-02-28', '2018-03-01', '2018-03-02', '2018-03-03', '2018-03-04', '2018-03-05', '2018-03-06', '2018-03-07', '2018-03-08', '2018-03-09', '2018-03-11', '2018-03-13', '2018-03-14', '2018-03-15', '2018-03-16', '2018-03-17', '2018-03-18', '2018-03-19', '2018-03-20', '2018-03-21']
myValues = [100, 101, 105, 106, 109, 110, 111, 165, 189, 193, 195, 196, 203, 210, 211, 214, 223, 224, 225, 226, 230, 231, 240, 249, 257, 266, 270, 273, 274, 282, 285, 291, 298, 300, 301, 303, 304, 306, 307, 308, 310, 311, 314, 315, 320, 322, 325, 328, 330, 342, 343, 346, 348, 349, 373, 380, 387, 391, 392, 395, 397, 401, 403, 408, 414, 420, 421, 422, 475, 477, 481, 484, 487, 490, 492, 500, 503, 504, 510, 511, 512, 515, 520, 521, 524, 526, 529, 530, 531, 534, 538, 541, 548, 553, 561, 565, 569, 574, 581, 585, 588, 592, 593, 597, 599, 602, 605, 608, 612, 615, 617, 624, 626, 631, 635, 638, 640, 644, 649, 652, 654, 656, 663, 665, 667, 676, 682, 684, 685, 686, 688, 691, 692, 708, 711, 712, 713, 714, 716, 717, 718, 719, 749, 755, 757, 758, 761, 762, 763, 764, 771, 772, 774, 778, 781, 788, 821, 835, 840, 848, 855, 861, 869, 884, 894, 913, 919, 928, 933, 940, 946, 949, 957, 965, 974, 984, 989, 996, 1001, 1055, 1057, 1059, 1067, 1079, 1083, 1092, 1101, 1109, 1112, 1116, 1121, 1138, 1159, 1174, 1192, 1204, 1222, 1230, 1253, 1264, 1270, 1277, 1287, 1293, 1298, 1301, 1313, 1326, 1330, 1336, 1354, 1361, 1367, 1376, 1404, 1405, 1437, 1465, 1479, 1533, 1553, 1571, 1584, 1600, 1624, 1631, 1643, 1663, 1672, 1679, 1690, 1696, 1707, 1712, 1716, 1725, 1728, 1733, 1739, 1740, 1741, 1750, 1755, 1762, 1764, 1788, 1792, 1800, 1811, 1815, 1822, 1829, 1836, 1842, 1843, 1849, 1850, 1851, 1855, 1858, 1862, 1863, 1865, 1867, 1869, 1871, 1872, 1874, 1875, 1876, 1878, 1882, 1885]
fig, ax = plt.subplots()
plt.xlabel('Dates')
plt.ylabel('Cumulative values')
ax.plot_date(x = pd.to_datetime(myDates), y = myValues)
fig.autofmt_xdate()
plt.show()
```
If you want to have full control over how many, where, and the precise rotation of your `xticks` and `xticklabels` you need to use `ax.set_xticklabels` as suggested by other answers.
Upvotes: 2 |
2018/03/22 | 5,716 | 8,492 | <issue_start>username_0: I have an object with many record types, and I need to populate some fields on it whenever it is created.
For example, I have an object called "CustomObj" with a field called "CustomF" with these 2 Record Types "RecType1" and "RecType2".
On the creation of a new "CustomObj" I need to populate the field the "CustomF" by "Hello" when the record type is "RecType1"
and by "Bye" when the record type is "RecType2"
Can I do that using the URL Hacking or I have to create 1 visualforce page to select the record type then redirect to the standard page with the values to populate this field or there is another approach?
What is the best practice?
How can I know the RecordType selected from the url itself ?
Thank you.<issue_comment>username_1: You should be able to get what you need with:
```
f, ax = plt.subplots(figsize=(8,8))
ax.plot_date(x = myDates, y = myValues)
ax.set_xticklabels(myDates, rotation=45, size=20)
ax.set_ylabel('Cumulative # of wallet addresses')
plt.show()
```
Just change the size and rotation set in line: `ax.set_xticklabels()`
EDIT:
```
f, ax = plt.subplots(figsize=(20,10))
ax.plot_date(x=myDates, y=myValues)
ax.set_ylabel('Cumulative # of wallet addresses')
ax.yaxis.set_tick_params(labelsize=14) # Sets size of the y ticklabels
ax.set_xticks(myDates) # Sets the positions of the ticks
ax.set_xticklabels(myDates, rotation=45, size=20, ha="right") # Sets a label on each tick
ax.xaxis.set_tick_params(length=12) # Sets length of the ticks
# Hides ticks and labels according to their position (here 1 in 7 is shown)
x = 0
for label, tick in zip(ax.xaxis.get_ticklabels(), ax.xaxis.majorTicks):
if x % 7 != 0 :
label.set_visible(False)
tick.set_visible(False)
x += 1
plt.show()
```
Changing the modulo value in `if x % 7 != 0` modifies the number of ticks you will show on the plot. Bigger value for fewer ticks and labels. It is important to set ha="right" otherwise the rotation makes it uncomfortable to see which label goes with which tick.
Upvotes: 2 <issue_comment>username_2: As @ImportanceOfBeingErnest pointed out, `myDates` were strings. Once I formatted them properly as dates using the following code:
```
myDates = [datetime.datetime.strptime(d, '%Y-%m-%d') for d in myDates]
```
it all worked out, i.e. the plot automatically set ticks for the month-year only.
Upvotes: 1 [selected_answer]<issue_comment>username_3: You can go the lazy way and use [pandas.to\_datetime](https://pandas.pydata.org/pandas-docs/stable/timeseries.html) to convert your x-axis values to date times (rather than strings) and let `matplotlib` worry about getting a better spacing/rotation using [fig.autofmt\_xdate](https://matplotlib.org/1.3.1/users/recipes.html)`
```
import matplotlib.pyplot as plt
import pandas as pd
myDates = ['2017-05-17', '2017-05-24', '2017-05-25', '2017-05-26', '2017-05-27', '2017-05-29', '2017-05-31', '2017-06-01', '2017-06-03', '2017-06-04', '2017-06-05', '2017-06-06', '2017-06-07', '2017-06-08', '2017-06-10', '2017-06-11', '2017-06-12', '2017-06-13', '2017-06-15', '2017-06-16', '2017-06-17', '2017-06-18', '2017-06-19', '2017-06-20', '2017-06-21', '2017-06-22', '2017-06-23', '2017-06-24', '2017-06-25', '2017-06-26', '2017-06-27', '2017-06-28', '2017-06-29', '2017-06-30', '2017-07-01', '2017-07-02', '2017-07-04', '2017-07-05', '2017-07-07', '2017-07-08', '2017-07-10', '2017-07-13', '2017-07-15', '2017-07-16', '2017-07-17', '2017-07-18', '2017-07-19', '2017-07-20', '2017-07-23', '2017-07-24', '2017-07-25', '2017-07-27', '2017-07-28', '2017-07-29', '2017-07-31', '2017-08-01', '2017-08-02', '2017-08-03', '2017-08-04', '2017-08-06', '2017-08-07', '2017-08-08', '2017-08-09', '2017-08-10', '2017-08-11', '2017-08-12', '2017-08-14', '2017-08-15', '2017-08-16', '2017-08-17', '2017-08-18', '2017-08-19', '2017-08-20', '2017-08-21', '2017-08-22', '2017-08-23', '2017-08-24', '2017-08-25', '2017-08-26', '2017-08-27', '2017-08-28', '2017-08-29', '2017-08-30', '2017-08-31', '2017-09-01', '2017-09-02', '2017-09-03', '2017-09-04', '2017-09-05', '2017-09-06', '2017-09-07', '2017-09-08', '2017-09-10', '2017-09-11', '2017-09-12', '2017-09-13', '2017-09-14', '2017-09-15', '2017-09-16', '2017-09-17', '2017-09-18', '2017-09-19', '2017-09-20', '2017-09-21', '2017-09-22', '2017-09-23', '2017-09-24', '2017-09-25', '2017-09-26', '2017-09-27', '2017-09-28', '2017-09-29', '2017-09-30', '2017-10-01', '2017-10-02', '2017-10-03', '2017-10-04', '2017-10-05', '2017-10-06', '2017-10-07', '2017-10-08', '2017-10-09', '2017-10-10', '2017-10-12', '2017-10-13', '2017-10-14', '2017-10-15', '2017-10-16', '2017-10-18', '2017-10-19', '2017-10-20', '2017-10-21', '2017-10-22', '2017-10-23', '2017-10-25', '2017-10-26', '2017-10-27', '2017-10-28', '2017-10-30', '2017-10-31', '2017-11-01', '2017-11-03', '2017-11-04', '2017-11-05', '2017-11-08', '2017-11-09', '2017-11-10', '2017-11-11', '2017-11-12', '2017-11-13', '2017-11-14', '2017-11-15', '2017-11-18', '2017-11-19', '2017-11-20', '2017-11-21', '2017-11-22', '2017-11-23', '2017-11-24', '2017-11-25', '2017-11-26', '2017-11-27', '2017-11-28', '2017-11-29', '2017-11-30', '2017-12-01', '2017-12-02', '2017-12-03', '2017-12-04', '2017-12-05', '2017-12-06', '2017-12-07', '2017-12-08', '2017-12-09', '2017-12-10', '2017-12-11', '2017-12-12', '2017-12-13', '2017-12-14', '2017-12-15', '2017-12-16', '2017-12-17', '2017-12-18', '2017-12-19', '2017-12-20', '2017-12-21', '2017-12-22', '2017-12-23', '2017-12-24', '2017-12-25', '2017-12-26', '2017-12-27', '2017-12-28', '2017-12-29', '2017-12-30', '2017-12-31', '2018-01-01', '2018-01-02', '2018-01-03', '2018-01-04', '2018-01-05', '2018-01-06', '2018-01-07', '2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11', '2018-01-12', '2018-01-13', '2018-01-14', '2018-01-15', '2018-01-16', '2018-01-17', '2018-01-18', '2018-01-19', '2018-01-20', '2018-01-21', '2018-01-22', '2018-01-23', '2018-01-24', '2018-01-25', '2018-01-26', '2018-01-27', '2018-01-28', '2018-01-29', '2018-01-30', '2018-01-31', '2018-02-01', '2018-02-02', '2018-02-03', '2018-02-04', '2018-02-05', '2018-02-06', '2018-02-07', '2018-02-08', '2018-02-09', '2018-02-10', '2018-02-11', '2018-02-12', '2018-02-13', '2018-02-14', '2018-02-15', '2018-02-17', '2018-02-18', '2018-02-19', '2018-02-20', '2018-02-21', '2018-02-22', '2018-02-23', '2018-02-24', '2018-02-25', '2018-02-26', '2018-02-27', '2018-02-28', '2018-03-01', '2018-03-02', '2018-03-03', '2018-03-04', '2018-03-05', '2018-03-06', '2018-03-07', '2018-03-08', '2018-03-09', '2018-03-11', '2018-03-13', '2018-03-14', '2018-03-15', '2018-03-16', '2018-03-17', '2018-03-18', '2018-03-19', '2018-03-20', '2018-03-21']
myValues = [100, 101, 105, 106, 109, 110, 111, 165, 189, 193, 195, 196, 203, 210, 211, 214, 223, 224, 225, 226, 230, 231, 240, 249, 257, 266, 270, 273, 274, 282, 285, 291, 298, 300, 301, 303, 304, 306, 307, 308, 310, 311, 314, 315, 320, 322, 325, 328, 330, 342, 343, 346, 348, 349, 373, 380, 387, 391, 392, 395, 397, 401, 403, 408, 414, 420, 421, 422, 475, 477, 481, 484, 487, 490, 492, 500, 503, 504, 510, 511, 512, 515, 520, 521, 524, 526, 529, 530, 531, 534, 538, 541, 548, 553, 561, 565, 569, 574, 581, 585, 588, 592, 593, 597, 599, 602, 605, 608, 612, 615, 617, 624, 626, 631, 635, 638, 640, 644, 649, 652, 654, 656, 663, 665, 667, 676, 682, 684, 685, 686, 688, 691, 692, 708, 711, 712, 713, 714, 716, 717, 718, 719, 749, 755, 757, 758, 761, 762, 763, 764, 771, 772, 774, 778, 781, 788, 821, 835, 840, 848, 855, 861, 869, 884, 894, 913, 919, 928, 933, 940, 946, 949, 957, 965, 974, 984, 989, 996, 1001, 1055, 1057, 1059, 1067, 1079, 1083, 1092, 1101, 1109, 1112, 1116, 1121, 1138, 1159, 1174, 1192, 1204, 1222, 1230, 1253, 1264, 1270, 1277, 1287, 1293, 1298, 1301, 1313, 1326, 1330, 1336, 1354, 1361, 1367, 1376, 1404, 1405, 1437, 1465, 1479, 1533, 1553, 1571, 1584, 1600, 1624, 1631, 1643, 1663, 1672, 1679, 1690, 1696, 1707, 1712, 1716, 1725, 1728, 1733, 1739, 1740, 1741, 1750, 1755, 1762, 1764, 1788, 1792, 1800, 1811, 1815, 1822, 1829, 1836, 1842, 1843, 1849, 1850, 1851, 1855, 1858, 1862, 1863, 1865, 1867, 1869, 1871, 1872, 1874, 1875, 1876, 1878, 1882, 1885]
fig, ax = plt.subplots()
plt.xlabel('Dates')
plt.ylabel('Cumulative values')
ax.plot_date(x = pd.to_datetime(myDates), y = myValues)
fig.autofmt_xdate()
plt.show()
```
If you want to have full control over how many, where, and the precise rotation of your `xticks` and `xticklabels` you need to use `ax.set_xticklabels` as suggested by other answers.
Upvotes: 2 |
2018/03/22 | 1,436 | 4,348 | <issue_start>username_0: I am facing two issues, bother are pretty much similar.
When I add this code to a blogger/blogspot page it works fine, but as soon as I switch to 'compose' mode from 'html' and save the post it changes the tag automatically and gives error link.
1. I am adding below code to blogger page where I want to show hide content, this doesn't work if I switch to 'compose' mode
```css
.cattext input {
display: none;
margin: 0 10% 0 0;
}
.catlink {
float:right;
margin: 0 10% 0 0;
}
input {
display: none;
}
.cattitle {
padding: 10px 10px; */
margin: 1em;
/* background: #333; */
color: #ffce00;
position: relative;
font-family: 'Open Sans';
font-weight: 700;
font-size: 20px;
letter-spacing: 2px;
cursor: default;
margin: 0 0 0 5%;
}
.cattext .text {
display:none;
margin-top:1em;
font-family: 'Open Sans';
font-size: 15px;
letter-spacing: 1.1px;
margin: 0 0 0 5%;
}
.cattext input#button:checked ~ .text {
display:block;
}
```
```html
Cool Keychains
Lorem ipsum dolor sit amet, eum delenit constituto in. Mea ut senserit voluptatum efficiantur, an usu vidit augue consequat. Mei iusto everti ocurreret no. Eum ut vidisse facilisis definitiones. Per melius honestatis ei, justo illum dicat sit eu, ex sit vidit ponderum. Ei quod ludus deseruisse vis, eu nihil percipit inciderint his.
```
2. The 'next' 'previous' slider buttons also stops working (adds a href tag automatically) when I switch to 'compose' and save post, below is the code and the slider script.
```js
var slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
var i;
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");
if (n > slides.length) {slideIndex = 1}
if (n < 1) {slideIndex = slides.length}
for (i = 0; i < slides.length; i++) {
slides[i].style.display = "none";
}
for (i = 0; i < dots.length; i++) {
dots[i].className = dots[i].className.replace(" active", "");
}
slides[slideIndex-1].style.display = "block";
dots[slideIndex-1].className += " active";
}
```
```css
* {box-sizing: border-box}
body {font-family: Verdana, sans-serif; margin:0}
.mySlides {display: none;
opacity: 1;
}
img {vertical-align: middle;}
/* Slideshow container */
.slideshow-container {
max-width: auto;
position: relative;
margin: auto;
}
/* Next & previous buttons */
.prev, .next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -22px;
color: grey;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
border-radius: 0 0 0 0;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 0 0 0 0;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
background-color: rgba(0,0,0,0.8);
}
/* Fading animation */
.fade {
-webkit-animation-name: fade;
-webkit-animation-duration: 1.5s;
animation-name: fade;
animation-duration: 1.5s;
}
@-webkit-keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
@keyframes fade {
from {opacity: .4}
to {opacity: 1}
}
/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
.prev, .next,.text {font-size: 11px}
}
```
```html
❮
❯
```<issue_comment>username_1: Blogger editor automatically adds href attribute to elements without href, so you can use another element like instead of or if you want to use anyway, add href like this `href='javascript:void(0)'`
Upvotes: 1 <issue_comment>username_2: Actually, this is a great way to see that you should be using `button`s (type=button). I am convinced that many frameworks use `a` too often where `button` should be used. You want to do an action on the page that does not change navigation for the user, use button.
If you want to stick with `a`, you can do something like this:
```
document.querySelectorAll("a[href$='/null']").forEach(function(btn) {
btn.addEventListener("click", function(event) {
event.preventDefault();
});
});
```
Upvotes: 0 |
2018/03/22 | 841 | 3,095 | <issue_start>username_0: ```
type Container = T extends any[] ? ArrayContainer : ObjectContainer
type ArrayContainer = {
set(arr: T, index: number): void
}
type ObjectContainer = {
set(obj: T): void
}
const testContainer = {} as any as Container<{ boxedNumber: number } | number>
// Does not compile
testContainer.set(33)
```
The conditional type decides to return an `ObjectContainer<{ boxedNumber: number }> | ObjectContainer` making calling any function on ObjectContainer impossible.
Is there any way to force the return of an `ObjectContainer<{ boxedNumber: number } | number>`?
Using the latest 2.8 version available.<issue_comment>username_1: Seems you need additional type parameter.
```
type Container = T extends any[] ? ArrayContainer : ObjectContainer;
type ArrayContainer = {
set(arr: T, index: number): void
}
type ObjectContainer = {
set(obj: T): void
}
const testContainer = {} as Container<{}, number>;
testContainer.set(10);
```
Upvotes: 0 <issue_comment>username_2: The problem is that conditional types will iterate over the types in a union and apply the condition to each item in the union and union the result, so the result of `Container<{ boxedNumber: number } | number>` will be equivalent to `ObjectContainer | ObjectContainer<{ boxedNumber: number; }>` not `ObjectContainer`.
You could create an intersection type of `Container<{ boxedNumber: number }>` and Container which will behave similarly to what you expect from `Container`
```
const testContainer = {} as any as Container<{ boxedNumber: number }> & Container
testContainer.set(33)
testContainer.set({ boxedNumber: 19})
```
Upvotes: 1 <issue_comment>username_3: As pointed out by @TitianCernicovaDragomir, your issue is that conditional types with a bare type parameter `T` in `T extends XXX ? YYY : ZZZ` ends up distributing over a union in `T`. This is [as designed](https://github.com/Microsoft/TypeScript/issues/21870), but there is a [de-facto standard workaround](https://github.com/Microsoft/TypeScript/issues/21870#issuecomment-364763990) for it: "box" the `T` and `XXX` into a one-tuple as in `[T] extends [XXX] ? YYY : ZZZ`. This makes the conditional not depend on a bare type parameter and it no longer breaks up the union. (Anything where the `T` ends up in a covariant position should work... `{a: T} extends {a: XXX}` would also work). This is likely to keep working and be supported since [@ahejlsberg](https://github.com/ahejlsberg) is the one recommending it and he is the [main architect of conditional types](https://github.com/Microsoft/TypeScript/pull/21316) in TypeScript.
So in your case you would do
```
type Container = [T] extends [any[]] ? ArrayContainer : ObjectContainer
```
And it will interpret `Container` as `ObjectContainer`, as you want.
But note that now `Container` is interpreted as `ObjectContainer`, since `string | number[]` is not by itself an array. Is that okay? Should it be `ObjectContainer | ArrayContainer`? Or `ObjectContainer & ArrayContainer`? Or something else? Not sure.
Hope that helps; good luck.
Upvotes: 3 [selected_answer] |
2018/03/22 | 220 | 768 | <issue_start>username_0: If I do `console.log(myObject)` the result like this :
[](https://i.stack.imgur.com/iV6wH.png)
I want to calculate the `length`
I try `myObject.lenght`, but it does not work
How can I solve this problem?
Seems this must convert first to normal object<issue_comment>username_1: `Object.keys` will return an array containing all the keys in your object, which you must pass as parameter.
Get the length of this array instead.
Upvotes: 0 <issue_comment>username_2: In JS, objects don't have a `length` property, you can use the `Object.keys(--your desired object--)` and get its length like this `Object.keys(myObject).length`. I hope it helps.
Upvotes: 4 [selected_answer] |
2018/03/22 | 907 | 3,087 | <issue_start>username_0: I have three pages.
Page 1 gets the Email/ Username of user (Same like Gmail).
Page 2 gets password and redirects to successful login page.
Issue i am facing:
I am able to get user-agents , ip , timestamp when i enter email in page 1 and redirected to page 2. All values are successfully saved in DB.
Now in page 2 i enter password but it doesn't get saved in DB.
Following are Result in DB:
```
ip:
"xxx.xxx.xxx.xx"
mobile:
"vvccc"
timestamp:
"22/2/2018 16:23:56:966"
useragent:
"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleW..."
```
```js
firebase.initializeApp(config);
var userAgent = window.navigator.userAgent;
var req = new XMLHttpRequest();
var ip;
var timestamp;
req.onload = function () {
var d = new Date();
var dateformat = d.toTimeString();
dateformat = dateformat.split(' ')[0];
ip = JSON.parse(req.response).ip;
timestamp = d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear() + ' ' + dateformat + ':' + d.getMilliseconds();
//savedata(ip,userAgent, d.getDate()+'/'+ d.getMonth()+'/'+ d.getFullYear()+' '+dateformat+':'+ d.getMilliseconds());
console.log(ip + ' ' + userAgent + ' ' + dateformat);
//Use ip asynchronously here
};
req.open("GET", "https://api.ipify.org/?format=json");
req.send();
var database = firebase.database();
var nextbutton = document.getElementById('Button1'); // Data from page 1 successfully reditected to page 2.
var pass = document.getElementById('Button2'); // Now from page 2 i redirected to page 3 , but I am unable to save its value in table.
var mobileno = document.getElementById('identifierId'); //page 1 textbox id
var password = document.getElementById('identifierId2'); //page 2 textbox id -> Unable to get its data
nextbutton.addEventListener('click', function () {
//var d = new Date();
//var dateformat = d.toTimeString();
//dateformat = dateformat.split(' ')[0];
//window.location.href = "http://stackoverflow.com";
var ip = JSON.parse(req.response).ip;
// savedata(ip, userAgent, d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear() + ' ' + dateformat + ':' + d.getMilliseconds());
console.log(ip + ' ' + userAgent);
database.ref('/email').push({
mobile: mobileno.value,
ip: ip,
useragent: userAgent,
timestamp: timestamp
}
)
console.log("meesage sent" + mobileno.value)
})
pass.addEventListener('click', function () {
var ip = JSON.parse(req.response).ip;
console.log(ip + ' ' + userAgent);
database.ref('/email').push({
passw: <PASSWORD>
}
)
console.log("meesage sent" + password.value)
})
```<issue_comment>username_1: `Object.keys` will return an array containing all the keys in your object, which you must pass as parameter.
Get the length of this array instead.
Upvotes: 0 <issue_comment>username_2: In JS, objects don't have a `length` property, you can use the `Object.keys(--your desired object--)` and get its length like this `Object.keys(myObject).length`. I hope it helps.
Upvotes: 4 [selected_answer] |
2018/03/22 | 704 | 2,251 | <issue_start>username_0: I'm trying to send an email to multiple emails, so I did a query to my users tables but the result is an array with keys that don't work `mail->to()`.
I need an array like this: `$owners = ['<EMAIL>', '<EMAIL>','<EMAIL>'];` from database.
My query:
```
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
```
I also try use `->toArray()` but comes with keys.
Email:
```
Mail::send('email-view', $data, function($message) use ($data, $owners)
{
$message->from('<EMAIL>' , 'FROM');
$message->to($owners)->subject('subject');
});
```<issue_comment>username_1: ```
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email')->toArray();
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can use [`->pluck()`](https://laravel.com/docs/5.6/collections#method-pluck), like this:
```
$owners = DB::table('users')->select('email')->where('active', 1)->where('userType', 1)->get();
$emailList = $owners->pluck('email');
```
Upvotes: 1 <issue_comment>username_3: First of all, the where condition is not proper in your query builder code.
It has to be like:
```
$query->where([
['column_1', '=', 'value_1'],
['column_2', '<>', 'value_2'],
[COLUMN, OPERATOR, VALUE],
...
])
```
>
> You can use `pluck()` to get the list in Laravel 5.
>
>
>
All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:
```
foreach ($owners as $owner) {
echo $owner->filed_name;
echo $owner->filed_name;
...
}
```
There is no restriction for using the core PHP code while using a PHP framework. You may refer the official [PHP Arrays Manual](http://php.net/manual/en/language.types.array.php) page to work with the language construct.
If you need to convert JSON to array, use:
>
> ***json\_decode($owners);***
>
>
>
Upvotes: 0 <issue_comment>username_4: ```
$owners = DB::table('users')->where('active', 1)->where('userType', 1)->pluck('email');
```
or
```
$owners = User::where('active', 1)->where('userType', 1)->pluck('email');
```
here User is your model name
Upvotes: 0 |
2018/03/22 | 3,146 | 8,944 | <issue_start>username_0: I am trying to show a non dismissable dialog after verifying the textfields in a form but it keeps printing:
```
03-22 12:34:46.373 8974-9001/com.mywebsite I/flutter: ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
03-22 12:34:46.397 8974-9001/com.mywebsite I/flutter: The following assertion was thrown while handling a gesture:
03-22 12:34:46.397 8974-9001/com.mywebsite I/flutter: Navigator operation requested with a context that does not include a Navigator.
03-22 12:34:46.397 8974-9001/com.mywebsite I/flutter: The context used to push or pop routes from the Navigator must be that of a widget that is a
03-22 12:34:46.397 8974-9001/com.mywebsite I/flutter: descendant of a Navigator widget.
03-22 12:34:46.404 8974-9001/com.mywebsite I/flutter: When the exception was thrown, this was the stack:
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #0 Navigator.of. (package:flutter/src/widgets/navigator.dart:725:9)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #1 Navigator.of (package:flutter/src/widgets/navigator.dart:731:6)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #2 showDialog (package:flutter/src/material/dialog.dart:486:20)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #3 SignupBodyState.\_showProgressDialog (package:truck\_am\_easy/signup.dart:310:5)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #4 SignupBodyState.\_verifyInputs (package:truck\_am\_easy/signup.dart:332:9)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #5 \_InkResponseState.\_handleTap (package:flutter/src/material/ink\_well.dart:478:14)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #6 \_InkResponseState.build. (package:flutter/src/material/ink\_well.dart:530:30)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #7 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #8 TapGestureRecognizer.\_checkUp (package:flutter/src/gestures/tap.dart:161:9)
03-22 12:34:46.419 8974-9001/com.mywebsite I/flutter: #9 TapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:123:7)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #10 GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:156:27)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #11 BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:147:20)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #12 BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:121:22)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #13 BindingBase&GestureBinding.\_handlePointerEvent (package:flutter/src/gestures/binding.dart:101:7)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #14 BindingBase&GestureBinding.\_flushPointerEventQueue (package:flutter/src/gestures/binding.dart:64:7)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #15 BindingBase&GestureBinding.\_handlePointerDataPacket (package:flutter/src/gestures/binding.dart:48:7)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #16 \_invoke1 (file:///b/build/slave/Linux\_Engine/build/src/flutter/lib/ui/hooks.dart:134)
03-22 12:34:46.420 8974-9001/com.mywebsite I/flutter: #17 \_dispatchPointerDataPacket (file:///b/build/slave/Linux\_Engine/build/src/flutter/lib/ui/hooks.dart:91)
03-22 12:34:46.425 8974-9001/com.mywebsite I/flutter: Handler: onTap
03-22 12:34:46.425 8974-9001/com.mywebsite I/flutter: Recognizer:
03-22 12:34:46.425 8974-9001/com.mywebsite I/flutter: TapGestureRecognizer#01b7d(debugOwner: GestureDetector, state: ready, won arena, finalPosition:
03-22 12:34:46.425 8974-9001/com.mywebsite I/flutter: Offset(187.0, 542.0), sent tap down)
03-22 12:34:46.425 8974-9001/com.mywebsite I/flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
```
but refused to show the dialog.
Please what am I doing wrong?
Part of my Code
---------------
```
@override
Widget build(BuildContext context) {
return new MediaQuery(
data: new MediaQueryData(),
child: new MaterialApp(
home: _buildHomeUI(),
));
}
Widget _buildHomeUI() {
return new Scaffold(
key: _scaffoldKey,
body: new SafeArea(
top: false,
bottom: false,
child: new Container(
decoration: new BoxDecoration(color: MyColors.colorPrimary),
child: new ListView(
children: [
// I removed the text fields.
new Container(
decoration:
new BoxDecoration(color: MyColors.colorBackground),
padding: const EdgeInsets.only(
top: 10.0, left: 15.0, right: 15.0),
child: new Form(
key: \_formKey1,
autovalidate: \_autoValidate,
child: new Column(
children: [
new Container(
margin: const EdgeInsets.symmetric(
horizontal: 50.0, vertical: 25.0),
padding:
const EdgeInsets.symmetric(horizontal: 30.0),
decoration: new BoxDecoration(
borderRadius: new BorderRadius.circular(30.0),
color: MyColors.colorAccent),
child: new Container(
margin:
const EdgeInsets.symmetric(horizontal: 10.0),
padding:
const EdgeInsets.symmetric(vertical: 5.0),
child: new FlatButton(
onPressed: \_verifyInputs,
child: const Text(Strings.signUp),
highlightColor: MyColors.colorAccentDark,
textColor: Colors.white),
),
),
],
),
),
)
],
)),
));
}
void \_showProgressDialog() {
showDialog(
context: context,
barrierDismissible: false,
child: new Dialog(
child: new Row(
mainAxisSize: MainAxisSize.min,
children: [
new CircularProgressIndicator(),
new Text(
"Creating your details...",
style: const TextStyle(fontFamily: Strings.customFont),
)
],
),
));
}
void \_verifyInputs() {
final form = \_formKey1.currentState;
if (form.validate()) {
if (checkBoxValue) {
form.save();
\_showProgressDialog();
\_parseResponse();
} else {
final snackBar = new SnackBar(
content: new Text(
"Please accept the terms and conditions",
style: const TextStyle(fontFamily: Strings.customFont),
),
);
\_scaffoldKey.currentState.showSnackBar(snackBar);
}
} else {
\_autoValidate = true;
}
}
void \_parseResponse() async {
Map response = await registerUser();
Navigator.pop(context);
print(response);
}
```<issue_comment>username_1: I struggled with this problem some days ago.
After a lot of exception trapping and printing, I solved a similar problem by wrapping all of the `body` property of the `Scaffold` in a `Builder` widget and using `Builder`'s context as the context to use for Navigator operations.
More about this, with an explaination, can be found under the `BuildContext` documentation page:
<https://docs.flutter.io/flutter/widgets/BuildContext-class.html>
Following a similar pattern helped me solve my problem.
**Edit**: here's a code sample, where my `build` method returns a `Builder` that wraps actual wiget building.
```
Widget build(BuildContext context) {
// TODO: implement build
return new Builder(
builder: (ctx) {
return new Scaffold(
key: scaffoldKey,
appBar: new AppBar(
title: new Text ("${sector.name} Sector" ,
style: new TextStyle(
fontFamily: "Exo",
fontWeight: FontWeight.w900,
)),
actions: [
\_menuSystemsList(ctx),
\_mainMenuActions(ctx)
] ,
),
body: new Builder (
builder: (ctx2) => \_makeHexmapSector(ctx2)
),
);
}
);
}
```
Upvotes: 4 <issue_comment>username_2: I had same problem all i did was removed `MaterialApp` from `class` and moved it inside of `runApp()` in `void main()`.
Upvotes: 3 <issue_comment>username_3: The issue could be because of the MaterialApp context in the library.
Creating a new Widget as home in MaterialApp may solve this
```
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new HomeScreen());
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("Title"),
),
body: new Center(child: new Text("Click Me")),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.add),
backgroundColor: Colors.orange,
onPressed: () {
print("Clicked");
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new AddTaskScreen()),
);
},
),
);
}
}
```
Upvotes: 4 <issue_comment>username_4: I had a similar kind of problem it exception was caught by the gesture detector BUT IT WASNT FOR NAVIGATOR PUSH
it was caused while dealing with JSON data
inside of `toJson`, I had typed:
```
"price": this.img
```
instead of
```
"price": this.price
```
Upvotes: 0 |
2018/03/22 | 1,094 | 3,867 | <issue_start>username_0: Student
```
+----+-----------+--------------+
| id | First Name| Last Name |
+----+-----------+--------------+
| 1 | John | A |
+----+-----------+--------------+
| 2 | Jane | B |
+----+-----------+--------------+
```
Certifications
```
+----+------------------+
| id | Name |
+----+------------------+
| 1 | Certification 1 |
+----+------------------+
| 2 | Certification 2 |
+----+------------------+
| 3 | Certification 3 |
+----+------------------+
```
StudentCertifications
```
+----+------------+-----------------+
| id | StudentID | CertificationID |
+----+------------+-----------------+
| 1 | 1 | 1 |
+----+------------+-----------------+
| 2 | 1 | 2 |
+----+------------+-----------------+
| 3 | 1 | 3 |
+----+------------+-----------------+
```
What I Want to find through SQL Query :
StudentMissingCertifications
```
+----+------------+-----------------+
| id | StudentID | CertificationID |
+----+------------+-----------------+
| 1 | 2 | 1 |
+----+------------+-----------------+
| 2 | 2 | 2 |
+----+------------+-----------------+
| 3 | 2 | 3 |
+----+------------+-----------------+
```<issue_comment>username_1: Link all students with all certifications via `CROSS JOIN` then filter the ones that he already has with `NOT EXISTS`.
```
SELECT
StudentID = S.ID,
MissingCertificationID = C.ID
FROM
Student AS S
CROSS JOIN Certifications AS C
WHERE
NOT EXISTS (
SELECT
'student does not have the certification'
FROM
StudentCertifications X
WHERE
X.StudentID = S.ID AND
X.CertificationID = C.ID)
```
Upvotes: 1 <issue_comment>username_2: Using `NOT EXISTS`
```
SELECT * FROM Studients S CROSS JOIN Certifications C
WHERE NOT EXISTS
(
SELECT 1 FROM StudentCertifications SC WHERE SC.StudentId=S.Id AND SC.CertificationID=C.Id
)
```
Or using `EXCEPT`
```
SELECT S.ID,C.ID FROM Studients S CROSS JOIN Certifications C
EXCEPT
SELECT StudentId, CertificationID FROM StudentCertifications
```
Upvotes: 2 <issue_comment>username_3: Cross join to get all possible student/certifications, then left join to the student certificate table where the result is null.
```
select
s.Id as studentId,
s.Name as studentName,
c.Id as certId,
c.name as certName
from
#student s
cross join #cert c
left join #studentCert sc on s.Id = sc.studentId and c.Id = sc.certId
where
sc.studentId is null
```
Upvotes: 1 <issue_comment>username_4: Do the `join`s (i.e. `LEFT JOIN`) to find the students which have still not any certificates
```
select
s.id as StudentID, c.id as CertificationID
from Student s
left join StudentCertifications sc on sc.StudentID = s.id
cross join (select id from Certifications) c
where sc.StudentID is null
```
Upvotes: 0 <issue_comment>username_5: Solution for your problem:
```
select Student.id,[First Name],[Last Name],Certifications.id,name
from Student cross join Certifications
left join StudentCertifications
on
Student.id=StudentCertifications.Studentid
WHERE StudentCertifications.Studentid IS NULL
```
**OUTPUT:**
```
id First_Name Last_Name id name
2 Jane B 1 Certification 1
2 Jane B 2 Certification 2
2 Jane B 3 Certification 3
```
Please follow the link for demo:
>
> <http://sqlfiddle.com/#!18/866ce/16>
>
>
>
Upvotes: 2 [selected_answer]<issue_comment>username_6: If i understood well the question, this query is what you're looking for
```
SELECT First Name, Last Name FROM Student
WHERE Student.id NOT IN (SELECT StudentID From StudentCertifications)
```
Upvotes: 0 |
2018/03/22 | 1,105 | 3,938 | <issue_start>username_0: I have the following kotlin code to send an email with an attachment:
```
val file = File(directory, filename)
file.createNewFile()
file.writeText("My Text", Charsets.UTF_8)
// ---- file is written succesfully, now let us
// try to get the URI and pass it for the intent
val fileURI = FileProvider.getUriForFile(this, "com.mydomain.myapp", file!!)
val emailIntent = Intent(Intent.ACTION_SEND).apply {
putExtra(Intent.EXTRA_SUBJECT, "My subject"))
putExtra(Intent.EXTRA_TEXT, "My message")
putExtra(Intent.EXTRA_STREAM, fileURI)
}
emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.type = "text/plain"
startActivity(emailIntent)
```
Now, when I run the above code, I get an error:
```
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.XmlResourceParser android.content.pm.ProviderInfo.loadXmlMetaData(android.content.pm.PackageManager, java.lang.String)' on a null object reference
```
for the fileURI assignment line. If instead of FileProvider, if I use:
```
putExtra(Intent.EXTRA_STREAM, file!!.toURI())
```
as the extra intent parameter, then I get an error:
```
W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI. The default value was returned.
```
03-22 11:39:06.625 9620-9620/com.secretsapp.secretsapp W/Bundle: Attempt to cast generated internal exception:
```
W/Bundle: Key android.intent.extra.STREAM expected Parcelable but value was a java.net.URI. The default value was returned.
W/Bundle: Attempt to cast generated internal exception:
java.lang.ClassCastException: java.net.URI cannot be cast to android.os.Parcelable
at android.os.Bundle.getParcelable(Bundle.java:945)
```
The file is created under a sub-directory under the global `Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)` directory and the app has `Manifest.permission.WRITE_EXTERNAL_STORAGE` permission too. Any pointers on how I can get the URI for the file and attach it to the email intent ?<issue_comment>username_1: For your first attempt — which is the correct approach — your does not have an authority value of `com.mydomain.myapp`. The authority string in the element in the manifest must match the 2nd parameter that you pass to `getUriForFile()`. This is covered in [the documentation for `FileProvider`](https://developer.android.com/reference/android/support/v4/content/FileProvider.html).
For your second attempt, `toURI()` returns a `URI`, not a `Uri`. While you could switch that to `Uri.fromFile()`, you will then crash on Android 7.0+, once your `targetSdkVersion` climbs to 24 or higher. Use the `FileProvider` approach.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Use below code for send email with intent in Kotlin:
```
private fun sendEmail() {
val filename = "contacts_sid.vcf"
val filelocation = File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename)
val path = Uri.fromFile(filelocation)
val emailIntent = Intent(Intent.ACTION_SEND)
// set the type to 'email'
emailIntent.type = "vnd.android.cursor.dir/email"
val to = arrayOf("<EMAIL>")
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path)
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject")
startActivity(Intent.createChooser(emailIntent, "Send email..."))
}
```
Upvotes: 0 <issue_comment>username_3: Implementation of [username_1's answer](https://stackoverflow.com/a/49427906/4473512)
manifest:
```
...
...
```
res/xml/provider\_paths.xml
```
xml version="1.0" encoding="utf-8"?
```
Use Sankar' implementation, but to get file uri, authority must equal the one declared in manifest:
```
val fileURI = FileProvider.getUriForFile(context, "$packageName.fileprovider", yourFile)
```
Upvotes: 1 |
2018/03/22 | 761 | 2,703 | <issue_start>username_0: I have two tables:
**Table 1**
```
Name | Surname
```
**Table 2**
```
Introduce | Type
```
Introduce from Table 2 contains either Name or Surname or both from Table1. I'm listing all records from Table1 that are not present in Introduce and that's working just fine.
What I'm trying to do is limit those results using Type from Table2.
I'm trying such code:
```
select t1.Name, t1.Surname
from Table1 t1
where not exists (select 1 Introduce
from Table2 t2
where (t2.Introduce like ('%' + t1.Name+ '%')
or t2.Introduce LIKE ('%' + t1.Surname + '%'))
)
and exists (select Type
from Table2
where Type in (90, 120))
```
But there's no difference if I'm using `and exists...` or not, same results.<issue_comment>username_1: For your first attempt — which is the correct approach — your does not have an authority value of `com.mydomain.myapp`. The authority string in the element in the manifest must match the 2nd parameter that you pass to `getUriForFile()`. This is covered in [the documentation for `FileProvider`](https://developer.android.com/reference/android/support/v4/content/FileProvider.html).
For your second attempt, `toURI()` returns a `URI`, not a `Uri`. While you could switch that to `Uri.fromFile()`, you will then crash on Android 7.0+, once your `targetSdkVersion` climbs to 24 or higher. Use the `FileProvider` approach.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Use below code for send email with intent in Kotlin:
```
private fun sendEmail() {
val filename = "contacts_sid.vcf"
val filelocation = File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename)
val path = Uri.fromFile(filelocation)
val emailIntent = Intent(Intent.ACTION_SEND)
// set the type to 'email'
emailIntent.type = "vnd.android.cursor.dir/email"
val to = arrayOf("<EMAIL>")
emailIntent.putExtra(Intent.EXTRA_EMAIL, to)
// the attachment
emailIntent.putExtra(Intent.EXTRA_STREAM, path)
// the mail subject
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject")
startActivity(Intent.createChooser(emailIntent, "Send email..."))
}
```
Upvotes: 0 <issue_comment>username_3: Implementation of [username_1's answer](https://stackoverflow.com/a/49427906/4473512)
manifest:
```
...
...
```
res/xml/provider\_paths.xml
```
xml version="1.0" encoding="utf-8"?
```
Use Sankar' implementation, but to get file uri, authority must equal the one declared in manifest:
```
val fileURI = FileProvider.getUriForFile(context, "$packageName.fileprovider", yourFile)
```
Upvotes: 1 |
2018/03/22 | 1,206 | 4,214 | <issue_start>username_0: I created a new app and I am trying to use `react-native-firebase`. But I continually get this error:
>
> RNFirebase core module was not found natively on iOS, ensure you have
> correctly included the RNFirebase pod in your projects 'Podfile' and
> have run 'pod install'.
>
>
> See <http://invertase.link/ios> for the ios setup guide.
>
>
>
Steps that I have done:
1. `yarn add react-native-firebase`
2. `react-native link react-native-firebase`
3. Set up my .plist file from Google under .../myproject/ios/myproject
4. Ran `pod update`after ensuring I was using Ruby 2.5.0
5. Ran pod install
The pod file that I am currently using is:
```
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'
target 'MyProject' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
pod 'Firebase/Core'
pod 'Firebase/Database'
pod 'Firebase/Messaging'
target 'MyProjectTests' do
inherit! :search_paths
# Pods for testing
end
end
```
These are the versions that I am using:
```
"react": "^16.3.0-alpha.1",
"react-native": "0.54.2",
"react-native-firebase": "^3.3.1",
```<issue_comment>username_1: I had the same problem, while trying to fix it was making my app to crash on start up.
I moved it through the terminal under the `ios/AppFolder/` but the Xcode was never aware of this file.
What helped me was to open my project in Xcode. Then left-click on my `AppFolder > Add Files` and then add the `GoogleService-Info.plist`.
Upvotes: 0 <issue_comment>username_2: If you don't want to manually link, you can try installing RNFirebase as a pod install directly:
```
pod 'RNFirebase', :path => 'path/to/node_modules/react-native-firebase/ios'
```
Changing or hardcoding `HEADER_SEARCH_PATHS` did not help me. When the error recurs, it's not necessary to `rm -rf node_modules` nor delete the pod file etc, I found it useful to clear the cache.
Upvotes: 2 <issue_comment>username_3: I always prefer not to use pods with react native, however, the react-native-firebase's instructions for the non-pop installation will not work.
The reason for this is the package's search paths which assumes either /pods or /firebase
[](https://i.stack.imgur.com/0xAew.png)
Hence, to make it link properly follow these steps:
1. download firebase sdk
2. make a folder directly under ios and call it Firebase, copy the frameworks needed of the sdk in that folder WITHOUT keeping the sub-folders (note, you have not entered XCode yet)
3. If you haven't already npm install -s react-native-firebase
4. Open XCode and drag and drop the desired frameworks to the Frameworks-folder in XCode (Eg. in my example the contents of the Analytics, Messaging and DynamicLinks folder). Do not copy items when asked as you already have then in the Firebase subfolder of ios:
[](https://i.stack.imgur.com/cPxVV.png)
5. In XCode right-click Libraries and select "Add files to [project]". Find RNFirebase-project in node\_modules and select the RNFirebase.xcodeproj, do not "copy items"
[](https://i.stack.imgur.com/X6kDb.png)
6. In Project/Target settings go to Linked Frameworks and Libraries. Find and add libRNFirebase.a
[](https://i.stack.imgur.com/Mo5Ee.png)
7. In AppDelegate.m make adjustments as per the instructions from react-native-firebase, eg: `import and [FIRAPP configure];` in `didFinishLaunchingWithOptions`
8. In Header Search Paths AND Framework Search Paths, add `$(PROJECT_DIR)/Firebase`
9. Don't forget to add you GoogleServices-Info.plist to your project
Upvotes: 1 <issue_comment>username_4: I manually linked these react-native-firebase/\* packages with
```
react-native link @react-native-firebase/xxx
```
"@react-native-firebase/analytics","@react-native-firebase/app","@react-native-firebase/auth","@react-native-firebase/crashlytics","@react-native-firebase/messaging"
which generated pod spec in pod and it worked.
Upvotes: 0 |
2018/03/22 | 920 | 3,493 | <issue_start>username_0: I am building an application that requires sequencing multiple bootstrap-vue modals. Specifically, a button in a nested component should open the 'manage' modal. The 'manage' modal contains buttons that, when clicked, should close the 'manage' modal and open another modal (e.g. 'edit', 'add', 'complete' etc).
Rather than passing props/emitting events up and down so that these can be triggered from different nested components, I would like to have one value in my store, `this.$store.state.general.activeModal`, that determines which modal is showing (if any)
**Question: How can I create a set of modals in my main app page that render if a value in the state is changed?**
My main app will look like this:
```
```
e.g. modal1 should show when `this.$store.state.general.activeModal` gets set to 'modal1' and close when the value is changed to something else.
I tried creating a computed variable "showModal1" that is true when `store.etc.activeModal=='modal1'`and false otherwise, then using `v-modal="showModal1"` to show/hide the modal, but it just ended up creating two copies of the modal every time the value in the store matched (apparently computed values trigger twice when a value in store is changed?)
Any help would be great!<issue_comment>username_1: I would suggest you to use the `b-modal` component's methods : .show() and .hide() inside a watcher which will catch your state mutations :
```
```
Don't pay attention to mapGetters, you have to watch your store getters/state. Supposed here that activeModal is your state value.
```
computed : {
...mapGetters([
'activeModal'
])
},
watch : {
activeModal(newActiveModal, oldActiveModal) {
// If an old value was setted, we want to hide it in anyway.
if (oldActiveModal) this.$refs[oldActiveModal].hide()
// If the new value is falsy, do nothing
if (!newActiveModal) return
this.$refs[newActiveModal].show()
}
}
```
Upvotes: 0 <issue_comment>username_2: Although not bootstrap-vue, we have had success with Bootstrap Modals with the simple `v-if` directive. The modal only shows/renders if the condition is true.
Using Vuex, you can have a computed property for activeModal and a v-if on each modal for `v-if="activeModal == 'modalName'"`. In our modals, we used Vue lifecycle `mounted` to show our modal, and register an emit (bootstrap-vue might handle that differently...)
`$('#' + this.modalId).on('hide.bs.modal', () => {
this.$emit('closeModal')
//this would set the v-if in parent Component to false, un-rendering the modal component
})`
Upvotes: 0 <issue_comment>username_3: You could create a computed property for the visibility of each modal, for example:
```
computed: {
modal1Visible() {
return this.$store.state.activeModal === 'modal1';
}
}
```
Then set the `visible` property of the b-modal:
```
```
To handle closing modals, you can use the `hide` event in combination with a store action or mutation which sets the value of `this.$store.state.activeModal`, for example:
```
```
This means if you close the modal via the `v-b-modal` directive, the close button, or some other method:
1. The modal will emit a `hide` event
2. The `activeModalSet` mutation will be triggered, setting `this.$store.activeModal` to `null`
3. The `modal1Visible` computed property will now evaluate to `false`
4. The `visible` property of the modal will be false, so the modal will be hidden.
Upvotes: 2 |
2018/03/22 | 765 | 1,874 | <issue_start>username_0: In q, say someone was naughty and created a function that sometimes returns a table with a mixed-type column:
```
t:([] c1:(`a;"dfdf";`b;"ccvcv"))
```
and sometimes a table with a symbol-only column:
```
t:([] c1:`a`dfdf`b`ccvcv)
```
I want to update `c1` to contain only symbols in a try-catch in case `t`c1` already contains only symbols. But I have a hard time translating the statement
```
update c1:`$c1 from t where 10h=type each c1
```
into the `![t;c;b;a]` syntax which works with the try-catch `@` operator
```
t:([] c1:(`a;"dfdf";`b;"ccvcv"));
c:enlist(=;type each `c1;10h);
b:0b;
a:(enlist`c1)!(enlist `$`c1); / TYPE ERROR
@[![;c;b;a];t;`continue] / this is what I want to do
```
Thanks for the help<issue_comment>username_1: Your `a` should be defined like so:
```
a:(enlist`c1)!enlist($;enlist`;`c1)
```
You can get this by using `parse` on your original `update` Q-SQL statement:
```
q)parse "update c1:`$c1 from t where 10h=type each c1"
!
`t
,,(=;10h;(k){x'y};@:;`c1))
0b
(,`c1)!,($;,`;`c1)
```
Noting that `,` in k is `enlist` in Q
You also need to change your definition of `c`:
```
c:enlist(=;(each;type;`c1);10h);
```
Putting it all together:
```
q)t:([] c1:(`a;"dfdf";`b;"ccvcv"))
q)c:enlist(=;(each;type;`c1);10h);
q)b:0b;
q)a:(enlist`c1)!enlist($;enlist`;`c1)
q)![t;c;b;a]
c1
-----
a
dfdf
b
ccvcv
```
But as pointed out in another answer, best to avoid functional form wherever possible
Upvotes: 4 [selected_answer]<issue_comment>username_2: Sometimes it's best to avoid functional selects, if your use case permits then `@` amend is a great alternative which can be particularly useful in place of update statements.
```
q)@[t;`c1;{$[10=type x;`$x;x]}each]
c1
-----
a
dfdf
b
ccvcv
```
Or if you still wish to use try-catch:
```
q)@[t;`c1;{@[`$;x;x]}each]
c1
-----
a
dfdf
b
ccvcv
```
Upvotes: 2 |
2018/03/22 | 616 | 2,342 | <issue_start>username_0: currently I am developing web push notification service for our project. The problem I am facing is that my service worker in Google Chrome receives push signal, but won't show it as notification, although I am able to log data to dev console. I tried it on Firefox and also on Chrome in another devices and it does work. I tried to restore chrome settings, but it's not helping. Here is my service worker code:
```
'use strict';
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
var payloadJson = JSON.parse(event.data.text());
const title = payloadJson.title;
const options = {
body: payloadJson.message,
icon: 'img/img.png',
badge: 'img/img2.png'
};
event.waitUntil(self.registration.showNotification(title, options));
});
```
After push service worker logs messages as expected:
[Dev tools console log](https://i.stack.imgur.com/NkLvX.png)
As I mentioned I tested it on chrome with another device which had Chrome v64 meanwhile mines is v65.0.3325.162 Both of devices runs on Mac OS High Sierra 10.13.3
EDIT:
So i found some strange behaviour, after completely deleting chrome with all cached files and reinstalling it I was able to make it work, but now the issue is, that if I wait till notification will dissaper it will not be shown next time. Everything works until I click close on notification.<issue_comment>username_1: To send a notification, the payload must use the [`notification` key](https://firebase.google.com/docs/cloud-messaging/admin/send-messages#defining_the_message_payload):
```
var payload = {
notification: {
title: 'My Title',
body : 'TEST'
}
};
```
See this answer: <https://stackoverflow.com/a/47379794/2292766>
Upvotes: -1 <issue_comment>username_2: I've discovered that if the `options` argument for the `showNotification()` is invalid, i.e. the file(s) specified in either the `icon` or `image` field don't exist, then the method call silently resolves without raising an error or anything. This is probably why you see the `push` event coming in yet not seeing the notification itself. I'm not sure about the connection with the behavior you explained after reinstalling the service worker, though.
Upvotes: 0 |
2018/03/22 | 1,055 | 3,557 | <issue_start>username_0: I have a function that uses the `len` function on one of it's parameters and iterates over the parameter. Now I can choose whether to annotate the type with `Iterable` or with `Sized`, but both gives errors in `mypy`.
```
from typing import Sized, Iterable
def foo(some_thing: Iterable):
print(len(some_thing))
for part in some_thing:
print(part)
```
Gives
```
error: Argument 1 to "len" has incompatible type "Iterable[Any]"; expected "Sized"
```
While
```
def foo(some_thing: Sized):
...
```
Gives
```
error: Iterable expected
error: "Sized" has no attribute "__iter__"
```
Since there is no `Intersection` as discussed in [this issue](https://github.com/python/typing/issues/213) I need to have some kind of mixed class.
```
from abc import ABCMeta
from typing import Sized, Iterable
class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta):
pass
def foo(some_thing: SizedIterable):
print(len(some_thing))
for part in some_thing:
print(part)
foo(['a', 'b', 'c'])
```
This gives an error when using `foo` with a `list`.
```
error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable"
```
This is not too surprising since:
```
>>> SizedIterable.__subclasscheck__(list)
False
```
So I defined a `__subclasshook__` (see [docs](https://docs.python.org/3/library/abc.html#abc.ABCMeta.__subclasshook__)).
```
class SizedIterable(Sized, Iterable[str], metaclass=ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return Sized.__subclasscheck__(subclass) and Iterable.__subclasscheck__(subclass)
```
Then the subclass check works:
```
>>> SizedIterable.__subclasscheck__(list)
True
```
But `mypy` still complains about my `list`.
```
error: Argument 1 to "foo" has incompatible type "List[str]"; expected "SizedIterable"
```
How can I use type hints when using both the `len` function and iterate over my parameter? I think casting `foo(cast(SizedIterable, ['a', 'b', 'c']))` is not a good solution.<issue_comment>username_1: In the future `Protocol`s will be introduced. They are already available through [`typing_extensions`](https://pypi.python.org/pypi/typing-extensions/3.6.2.1). See also [PEP 544](https://www.python.org/dev/peps/pep-0544/). Using `Protocol` the code above would be:
```
from typing_extensions import Protocol
class SizedIterable(Protocol):
def __len__(self):
pass
def __iter__(self):
pass
def foo(some_thing: SizedIterable):
print(len(some_thing))
for part in some_thing:
print(part)
foo(['a', 'b', 'c'])
```
`mypy` takes that code without complaining. But PyCharm is saying
>
> Expected type 'SizedIterable', got 'List[str]'
>
>
>
about the last line.
Upvotes: 4 <issue_comment>username_2: Starting from Python3.6 there's a new type called `Collection`. See [here](https://docs.python.org/3/library/collections.abc.html#collections.abc.Collection).
Upvotes: 6 <issue_comment>username_3: You should go with `Sequence` from [typing](https://docs.python.org/3/library/typing.html) if you plan to use only list or tuple and access its elements by index, like `x[0]`. `Sequence` is both `Sized` and `Iterable`, see [here](https://docs.python.org/3/library/collections.abc.html).
Upvotes: 4 <issue_comment>username_4: Maybe you need a class like this?
```py
class MyArray:
_array: list
def as_tuple(self):
return tuple(self._array)
def as_list(self):
return self._array
# More Feature to implement
```
Upvotes: 0 |
2018/03/22 | 889 | 2,752 | <issue_start>username_0: I have a string in following format
qString path = <https://user:[email protected]>
I want to ingore username and password from the the above path using QRegExp.
An worked with following case also
`1. qString path = http://user:pass@someurl.`
In the below case if it is does not contain any user name or passwod then return the string
```
2. qString path = https://someurl.com
```
My code is worked with http and https, Is there any best approach to do that is short and simple manner. please suggest
```
f(Path.startsWith("https://") == true)
{
QRegExp UserPwd("(.*)(https://)(.*)(.*)", Qt::CaseInsensitive, QRegExp::RegExp);
QRegExp UserPwd1("(.*)(https://)(.*)@(.*)", Qt::CaseInsensitive, QRegExp::RegExp);
if(UserPwd1.indexIn(ErrorString) != -1)
{
(void) UserPwd1.indexIn(Path);
return UserPwd1.cap(1) + UserPwd1.cap(2) + UserPwd1.cap(4);
}
else
{
(void) UserPwd.indexIn(Path);
return UserPwd.cap(1) + UserPwd.cap(2) + UserPwd.cap(3);
}
}
else
{
QRegExp UserPwd("(.*)(http://)(.*)@(.*)", Qt::CaseInsensitive, QRegExp::RegExp);
(void) UserPwd.indexIn(Path);
return UserPwd.cap(1) + UserPwd.cap(2) + UserPwd.cap(4);
}
```<issue_comment>username_1: It can be achieved using [QUrl](http://doc.qt.io/qt-5/qurl.html)
The following function manipulate the URL [authority](http://doc.qt.io/qt-5/qurl.html#setAuthority) format
```
QUrl GetFixedUrl(const QUrl & oUrl )
{
QUrl oNewUrl = oUrl;
// Reset the user name and password
oNewUrl.setUserName(QString());
oNewUrl.setPassword(QString());
// Save the host name
QString oHostName = oNewUrl.host();
// Clear authority
oNewUrl.setAuthority(QString());
// Set host name
oNewUrl.setHost(oHostName);
return oNewUrl;
}
```
Then call it
```
QUrl oUrl("https://user:[email protected]");
std::cout<< GetFixedUrl(oUrl).toString().toStdString()<< std::endl;
```
Output will be:
```
https://someurl.com
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I would suggest two approaches. You can choose one, which is more convenient and suitable to you:
**Using regular expression**
```
QString removeAuthority1(const QString &path)
{
QRegExp rx("((http|https|ftp):\\/\\/)(.*@)?(.*)");
if (rx.indexIn(path) != -1) {
return rx.cap(1) + rx.cap(4);
}
return QString();
}
```
**Using QUrl**
```
QString removeAuthority2(const QString &path)
{
QUrl url = QUrl::fromUserInput(path);
return url.scheme() + "://" + url.host();
}
```
**Usage**
```
QString path("http://user:[email protected]");
QString s1 = removeAuthority1(path); // http://someurl.com
QString s2 = removeAuthority2(path); // http://someurl.com
```
Upvotes: 1 |
2018/03/22 | 546 | 2,346 | <issue_start>username_0: I have created a `DbContext` using EF Core 2.0 and already applied a lot of migrations in the development environment using `Update-Database` in PM-Console.
The tables are created using the `dbo`schema on my localDb as expected and as I know from EF6.
However, when i apply the `Update-Database` command to my production database on a MSSQL Server, it creates a schema named `Domain\Username` (my user from my machine). When I then run the server application with its designated domain account, it can not access the database. As a workaround I talked the IT infrastructure guys into allowing this account to execute software on my computer and applied the migritions by executing VisualStudio with this account. Then a schema for this special account is created and thereafter it can access the database fro the webserver application. It works since this special account is currently the only one that needs direct access to the database (besides myself). But this should ne be a permanent solution.
Does anyone know a solution for this? The database has been created in the exactly same manner as for previous EF6 projects.
Why are the per user schemas only used when applying the migrations to the production system and not on my development machine and how can I control the schema manually?
I tried `modelBuilder.HasDefaultSchema("dbo");` but this does not work. Actually it seems to not having any effect at all.<issue_comment>username_1: I had the same problem and believe it was caused by having my `domain\user` listed under `MyDatabase -> Security -> Users`. I fixed the issue by deleting my account from the users (right click -> delete) and the next time I ran `update-database` it prefixed the tables correctly with 'dbo'.
[](https://i.stack.imgur.com/H9v0j.png)
Upvotes: 2 <issue_comment>username_2: Calling `modelBuilder.HasDefaultSchema("dbo")` in the db context solved this problem for me (EF 3.1.7), but it needs to be there when you *generate* the migration (not when it gets applied). This makes EF add `schema: "dbo"` to calls to `migrationBuilder.CreateTable(...)`, overriding the SQL default (which can vary based on the provider/implementation).
IMO it's always a good idea to specify a schema for your model.
Upvotes: 2 |
2018/03/22 | 447 | 1,570 | <issue_start>username_0: [](https://i.stack.imgur.com/JFQFw.png)
```
private void button1_Click(object sender, EventArgs e)
{
string[] AnalyteNames = new string[]{
"NA", "K", "CL", "TCO2", "BUN", "CREA", "EGFR", "GLU", "CA", "ANG", "HCT", "HGB" };
for (int i = 0; i < AnalyteNames.Length; i++)
{
CheckBox box = new CheckBox();
box.Text = AnalyteNames[i].ToString();
box.ForeColor = Color.Black;
box.Checked = false;
// AnalyteListCheckBoxes was a CheckedBoxList
this.AnalyteListCheckBoxes.Items.Add(box);
}
}
```<issue_comment>username_1: I had the same problem and believe it was caused by having my `domain\user` listed under `MyDatabase -> Security -> Users`. I fixed the issue by deleting my account from the users (right click -> delete) and the next time I ran `update-database` it prefixed the tables correctly with 'dbo'.
[](https://i.stack.imgur.com/H9v0j.png)
Upvotes: 2 <issue_comment>username_2: Calling `modelBuilder.HasDefaultSchema("dbo")` in the db context solved this problem for me (EF 3.1.7), but it needs to be there when you *generate* the migration (not when it gets applied). This makes EF add `schema: "dbo"` to calls to `migrationBuilder.CreateTable(...)`, overriding the SQL default (which can vary based on the provider/implementation).
IMO it's always a good idea to specify a schema for your model.
Upvotes: 2 |
2018/03/22 | 999 | 3,992 | <issue_start>username_0: There have been several similar questions asked, but I couldn't find anything that looked to be exactly the same as what I'm experiencing.
I've got a `ComboBox` inside a `DataTemplate` for a `ListView`. The `ComboBox` has the correct bindings to the `ItemsSource` as well as the `SelectedItem`. The pattern I'm using is the same pattern I use throughout the application without any problems.
For whatever reason though, the selected item is getting nulled out somewhere along the way. I've put breakpoints inside the selected item and I can see that it is being properly set during the lists construction. Then, the selected item is being set again to `null` while the control is being rendered (at least that's the way it appears). When I look at the call stack at the point it's being set to `null`, the stack only shows the line I'm on `[External Code]`.
For reference, here is what the current code looks like:
```
```
The `ComboBoxTypes` is an `ObservableCollection`.
`SelectedComboBoxType` is set by referencing a row from the `RaceTypes`.
Again, as I mentioned above, this pattern that seems to work everywhere else in the application, but not inside a `ListView`.
Here is a sample of what the code looks like that I'm using to populate the list items and the combo boxes. It's not actual code, because I can't provide the actual code. It is close enough though that it illustrate the steps being taken.
```
vm.ListVms.Clear();
foreach (var unit in source.ListItems)
{
var listVm = new ListVm();
listVm.ComboBoxTypes.Add();
listVm.ComboBoxTypes.Add();
listVm.ComboBoxTypes.Add();
listVm.ComboBoxTypes.Add();
listVm.SelectedComboBoxType = listVm.ComboBoxTypes.FirstOrDefault(r => r.Id == (int) unit.ComboBoxType);
vm.ListVms.Add(listVm);
}
```<issue_comment>username_1: This usually happens when you reverse the order in which you select an item in the code-behind. Consider the following two options:
**Option 1**
```
SelectedComboBoxType = items[0];
ComboBoxTypes = items;
```
**Option 2**
```
ComboBoxTypes = items;
SelectedComboBoxType = items[0];
```
In **Option 1** you first set the selected item which causes change notification which is immediately handled by the control. The control is however not yet bound to `items` and therefore will not set `SelectedItem` to your selection but will in contrast cause an update back to `SelectedComboBoxType` with the previously selected value.
Basically this means that you always can select only *after* the value you want to select is already bound to the control. **Option 2** should solve your problem.
Upvotes: 0 <issue_comment>username_2: I received a couple of workable answers from the Microsoft Developer Network, so I thought I would share them here for anybody who has run into this same problem.
**Option 1**
Put in a test on the setter to bypass updating the backing field if the value is null.
This is a hack to me, but it works perfectly.
```
public ComboboxItemVm SelectedComboBoxType
{
get { return selectedType; }
set
{
if (value == null)
{
Debug.WriteLine("null!");
return;
}
if (value != selectedType)
{
selectedType = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedComboBoxType"));
}
}
}
```
**Option 2**
Change the binding on the SelectedItem from x:Bind to Binding.
```
```
It's disappointing that the solution is to use an older coding style, but it also fixes the issue without having to add an extra null-test-bypass option in the code.
[Here is a link to the original answer provided to me](https://social.msdn.microsoft.com/Forums/en-US/9ea26230-ab89-4eb8-975c-f06373391a85/in-uwp-when-using-a-combobox-inside-a-listview-datatemplate-selecteditem-is-lost?forum=wpdevelop)
Upvotes: 2 [selected_answer] |
2018/03/22 | 590 | 2,069 | <issue_start>username_0: Is there a way to increment each result of a loop by 2 each time? So it should increase the values by 2, then 4, then 6...
So if the first result is 2, it should be `2*2=4`
But the second result should be increased by 4: `2*4=8`
This is the loop:
```
function setDatePosition(timelineComponents, min) {
for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
timelineComponents['timelineEvents'].eq(i).css('left', (distanceNorm*min)+'px');
}
}
```
At the moment, the first result is left:120px and the second result is left:180px.
I want to achieve:
First result + 20px: 140px
Second result + 40px: 220px
Third result + 60px... And so on<issue_comment>username_1: I believe your 20px coming from min?
If that is the case, you just need to increase min after each iteration.
`min += 20;`
```
function setDatePosition(timelineComponents, min) {
for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
timelineComponents['timelineEvents'].eq(i).css('left', (distanceNorm*min)+'px');
min += 20;
}
}
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: You could multiply `distanceNorm` by `i+1` at each iteration:
```
function setDatePosition(timelineComponents, min) {
for (i = 0; i < timelineComponents['timelineDates'].length; i++) {
var distance = daydiff(timelineComponents['timelineDates'][0], timelineComponents['timelineDates'][i]),
distanceNorm = Math.round(distance/timelineComponents['eventsMinLapse']) + 2;
timelineComponents['timelineEvents'].eq(i).css('left', (distanceNorm*min*i+1)+'px');
}
}
```
Upvotes: 1 |
2018/03/22 | 1,973 | 7,433 | <issue_start>username_0: Why does `std::any_cast` throw a `std::bad_any_cast` exception when an implicit conversion from the actual stored type to the requested type would be possible?
For example:
```
std::any a = 10; // holds an int now
auto b = std::any_cast(a); // throws bad\_any\_cast exception
```
Why is this not allowed and is there a workaround to allow an implicit conversion (in case the exact type that `std::any` holds is unknown)?<issue_comment>username_1: `std::any_cast` is specified in terms of `typeid`. To quote [cppreference](http://en.cppreference.com/w/cpp/utility/any/any_cast) on this:
>
> Throws `std::bad_any_cast` if the `typeid` of the requested `ValueType` does
> not match that of the contents of operand.
>
>
>
Since [`typeid`](http://en.cppreference.com/w/cpp/language/typeid) doesn't allow the implementation to "figure out" an implicit conversion is possible, there's no way (to my knowledge) that `any_cast` can know it's possible either.
To put it otherwise, the type erasure provided by `std::any` relies on information available only at run-time. And that information is not quite as rich as the information the compiler has for figuring out conversions. That's the cost of type erasure in C++17.
Upvotes: 7 [selected_answer]<issue_comment>username_2: To do what you want you'd need full code reflection and reification. That means every detail of every type would have to be saved to every binary (and every signature of every function on every type! And every template anywhere!), and when you ask to convert from an any to a type X you'd pass the data about X into the any, which would contain enough information about the type it contained to basically attempt to compile a conversion to X and fail or not.
There are languages that can do this; every binary ships with IR bytecode (or raw source) and an interpreter/compiler. These languages tend to be 2x or more slower than C++ at most tasks and have significantly larger memory footprints. It may be possible to have those features without that cost, but nobody has that language that I know of.
C++ doesn't have this ability. Instead, it forgets almost all facts about types during compilation. For any, it remembers a typeid which it can be used to get an exact match, and how to convert its storage to said exact match.
Upvotes: 4 <issue_comment>username_3: `std::any` *has* to be implemented with type-erasure. That's because it can store *any* type and can't be a template. There is just no other functionality in C++ to achieve this at the moment.
What that means is that `std::any` will store a type-erased pointer, `void*` and `std::any_cast` will convert that pointer to the specified type and that's it. It just does a sanity check using `typeid` before to check whether you the type you cast it to is the one stored into the any.
Allowing implicit conversions would be impossible using the current implementation. Think about it (ignore the `typeid` check for now).
```
std::any_cast(a);
```
`a` stores an `int` and not a `long`. How should `std::any` know that? It can just cast its `void*` to the type specified, dereference it and return it. Casting a pointer from one type to another is a strict aliasing violation and results in UB, so that's a bad idea.
`std::any` would have to store the actual type of the object stored in it, which is not possible. You can't store types in C++ right now. It could maintain a list of types along with their respective `typeid`s and switch over them to get the current type and perform the implicit conversion. But there is no way to do that for *every* single type that you are going to use. User defined types wouldn't work anyways, and you'd have to rely on things such as macros to "register" your type and generate the appropriate switch case for it1.
Maybe something like this:
```
template
T any\_cast(const any &Any) {
const auto Typeid = Any.typeid();
if (Typeid == typeid(int))
return \*static\_cast(Any.ptr());
else if (Typeid == typeid(long))
return \*static\_cast(Any.ptr());
// and so on. Add your macro magic here.
// What should happen if a type is not registered?
}
```
Is this a good solution? No, by far. The switch is costly, and C++'s mantra is "you don't pay for what you don't use" so no, there is no way of achieving this currently. The approach is also "hacky" and very brittle (what happens if you forget to register a type). In short, the possible benefits of doing something like this is not worth the trouble in the first place.
>
> is there a workaround to allow an implicit conversion (in case the exact type that std::any holds is unknown)?
>
>
>
Yes, implement `std::any` (or a comparable type) and `std::any_cast` yourself using the macro register approach mentioned above1. I won't recommend it though. If you don't and can't know what type `std::any` stores and need to access it, you have a possible design flaw.
---
1: Don't actually know if this is possible, I'm not that good in macro (ab)use. You can also hard-code your types in for your custom implementation or use a separate tool for it.
Upvotes: 3 <issue_comment>username_4: This could be implemented by trying a contingency implicit conversion, if the type id of the requested type was not the same as the type id of the stored type. But it would involve a cost and hence violate the ["not pay for what you don't use"](https://stackoverflow.com/questions/28304992/how-can-i-better-learn-to-not-pay-for-what-you-dont-use) principle. Another `any` shortcoming, for example, is the inability to store an array.
```
std::any("blabla");
```
will work, but it will store a `char const*`, not an array. You could add such a feature in your own customized `any`, but then you'd need to store a pointer to a string literal by doing:
```
any(&*"blabla");
```
which is kind of odd. The decisions of the Standard committee are a compromise and never satisfy everyone, but you fortunately have the option of implementing your own `any`.
You could also extend `any` to store and then invoke type-erased [functors](https://github.com/username_4/generic/blob/master/callback.cpp), for example, but this is also not supported by the Standard.
Upvotes: 1 <issue_comment>username_5: This question is not well posed; implicit conversion to the right type are *in principle* possible, but disabled.
This restriction probably exists to maintain a certain level of safety or to mimic the explict cast necessary (through pointer) in the C-version of `any` (`void*`).
(The example implementation below shows that it is possible.)
Having said that, your target code still doesn't work because you need to know the exact type before conversion, but this can *in principle* work:
```
any a = 10; // holds an int now
long b = int(a); // possible but today's it needs to be: long b = any_cast(a);
```
To show that implicit conversions are *technically* possible (but can fail at runtime):
```
#include
struct myany : boost::any{
using boost::any::any;
template operator T() const{return boost::any\_cast(\*this);}
};
int main(){
boost::any ba = 10;
// int bai = ba; // error, no implicit conversion
myany ma = 10; // literal 10 is an int
int mai = ma; // implicit conversion is possible, other target types will fail (with an exception)
assert(mai == 10);
ma = std::string{"hello"};
std::string mas = ma;
assert( mas == "hello" );
}
```
Upvotes: 1 |
2018/03/22 | 1,986 | 7,549 | <issue_start>username_0: I have an java class like below. So I want to make a object of that class with lesser variables.
```
public class ABC{
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
}
```
So I want to make a object containing firstName only. Can I achieve this?? Or is there any way around as I need to create object with same or different number of variables.<issue_comment>username_1: `std::any_cast` is specified in terms of `typeid`. To quote [cppreference](http://en.cppreference.com/w/cpp/utility/any/any_cast) on this:
>
> Throws `std::bad_any_cast` if the `typeid` of the requested `ValueType` does
> not match that of the contents of operand.
>
>
>
Since [`typeid`](http://en.cppreference.com/w/cpp/language/typeid) doesn't allow the implementation to "figure out" an implicit conversion is possible, there's no way (to my knowledge) that `any_cast` can know it's possible either.
To put it otherwise, the type erasure provided by `std::any` relies on information available only at run-time. And that information is not quite as rich as the information the compiler has for figuring out conversions. That's the cost of type erasure in C++17.
Upvotes: 7 [selected_answer]<issue_comment>username_2: To do what you want you'd need full code reflection and reification. That means every detail of every type would have to be saved to every binary (and every signature of every function on every type! And every template anywhere!), and when you ask to convert from an any to a type X you'd pass the data about X into the any, which would contain enough information about the type it contained to basically attempt to compile a conversion to X and fail or not.
There are languages that can do this; every binary ships with IR bytecode (or raw source) and an interpreter/compiler. These languages tend to be 2x or more slower than C++ at most tasks and have significantly larger memory footprints. It may be possible to have those features without that cost, but nobody has that language that I know of.
C++ doesn't have this ability. Instead, it forgets almost all facts about types during compilation. For any, it remembers a typeid which it can be used to get an exact match, and how to convert its storage to said exact match.
Upvotes: 4 <issue_comment>username_3: `std::any` *has* to be implemented with type-erasure. That's because it can store *any* type and can't be a template. There is just no other functionality in C++ to achieve this at the moment.
What that means is that `std::any` will store a type-erased pointer, `void*` and `std::any_cast` will convert that pointer to the specified type and that's it. It just does a sanity check using `typeid` before to check whether you the type you cast it to is the one stored into the any.
Allowing implicit conversions would be impossible using the current implementation. Think about it (ignore the `typeid` check for now).
```
std::any_cast(a);
```
`a` stores an `int` and not a `long`. How should `std::any` know that? It can just cast its `void*` to the type specified, dereference it and return it. Casting a pointer from one type to another is a strict aliasing violation and results in UB, so that's a bad idea.
`std::any` would have to store the actual type of the object stored in it, which is not possible. You can't store types in C++ right now. It could maintain a list of types along with their respective `typeid`s and switch over them to get the current type and perform the implicit conversion. But there is no way to do that for *every* single type that you are going to use. User defined types wouldn't work anyways, and you'd have to rely on things such as macros to "register" your type and generate the appropriate switch case for it1.
Maybe something like this:
```
template
T any\_cast(const any &Any) {
const auto Typeid = Any.typeid();
if (Typeid == typeid(int))
return \*static\_cast(Any.ptr());
else if (Typeid == typeid(long))
return \*static\_cast(Any.ptr());
// and so on. Add your macro magic here.
// What should happen if a type is not registered?
}
```
Is this a good solution? No, by far. The switch is costly, and C++'s mantra is "you don't pay for what you don't use" so no, there is no way of achieving this currently. The approach is also "hacky" and very brittle (what happens if you forget to register a type). In short, the possible benefits of doing something like this is not worth the trouble in the first place.
>
> is there a workaround to allow an implicit conversion (in case the exact type that std::any holds is unknown)?
>
>
>
Yes, implement `std::any` (or a comparable type) and `std::any_cast` yourself using the macro register approach mentioned above1. I won't recommend it though. If you don't and can't know what type `std::any` stores and need to access it, you have a possible design flaw.
---
1: Don't actually know if this is possible, I'm not that good in macro (ab)use. You can also hard-code your types in for your custom implementation or use a separate tool for it.
Upvotes: 3 <issue_comment>username_4: This could be implemented by trying a contingency implicit conversion, if the type id of the requested type was not the same as the type id of the stored type. But it would involve a cost and hence violate the ["not pay for what you don't use"](https://stackoverflow.com/questions/28304992/how-can-i-better-learn-to-not-pay-for-what-you-dont-use) principle. Another `any` shortcoming, for example, is the inability to store an array.
```
std::any("blabla");
```
will work, but it will store a `char const*`, not an array. You could add such a feature in your own customized `any`, but then you'd need to store a pointer to a string literal by doing:
```
any(&*"blabla");
```
which is kind of odd. The decisions of the Standard committee are a compromise and never satisfy everyone, but you fortunately have the option of implementing your own `any`.
You could also extend `any` to store and then invoke type-erased [functors](https://github.com/username_4/generic/blob/master/callback.cpp), for example, but this is also not supported by the Standard.
Upvotes: 1 <issue_comment>username_5: This question is not well posed; implicit conversion to the right type are *in principle* possible, but disabled.
This restriction probably exists to maintain a certain level of safety or to mimic the explict cast necessary (through pointer) in the C-version of `any` (`void*`).
(The example implementation below shows that it is possible.)
Having said that, your target code still doesn't work because you need to know the exact type before conversion, but this can *in principle* work:
```
any a = 10; // holds an int now
long b = int(a); // possible but today's it needs to be: long b = any_cast(a);
```
To show that implicit conversions are *technically* possible (but can fail at runtime):
```
#include
struct myany : boost::any{
using boost::any::any;
template operator T() const{return boost::any\_cast(\*this);}
};
int main(){
boost::any ba = 10;
// int bai = ba; // error, no implicit conversion
myany ma = 10; // literal 10 is an int
int mai = ma; // implicit conversion is possible, other target types will fail (with an exception)
assert(mai == 10);
ma = std::string{"hello"};
std::string mas = ma;
assert( mas == "hello" );
}
```
Upvotes: 1 |
2018/03/22 | 1,928 | 7,298 | <issue_start>username_0: Looking at the XAML below (which is an extract from a carousel page), is there any way to use OnIdiom to set the image gl\_CarouselIndicator to different things for phone and tablet?
I have used OnIdiom many times but I'm unsure how I would structure it in this instance.
thanks
```
```<issue_comment>username_1: `std::any_cast` is specified in terms of `typeid`. To quote [cppreference](http://en.cppreference.com/w/cpp/utility/any/any_cast) on this:
>
> Throws `std::bad_any_cast` if the `typeid` of the requested `ValueType` does
> not match that of the contents of operand.
>
>
>
Since [`typeid`](http://en.cppreference.com/w/cpp/language/typeid) doesn't allow the implementation to "figure out" an implicit conversion is possible, there's no way (to my knowledge) that `any_cast` can know it's possible either.
To put it otherwise, the type erasure provided by `std::any` relies on information available only at run-time. And that information is not quite as rich as the information the compiler has for figuring out conversions. That's the cost of type erasure in C++17.
Upvotes: 7 [selected_answer]<issue_comment>username_2: To do what you want you'd need full code reflection and reification. That means every detail of every type would have to be saved to every binary (and every signature of every function on every type! And every template anywhere!), and when you ask to convert from an any to a type X you'd pass the data about X into the any, which would contain enough information about the type it contained to basically attempt to compile a conversion to X and fail or not.
There are languages that can do this; every binary ships with IR bytecode (or raw source) and an interpreter/compiler. These languages tend to be 2x or more slower than C++ at most tasks and have significantly larger memory footprints. It may be possible to have those features without that cost, but nobody has that language that I know of.
C++ doesn't have this ability. Instead, it forgets almost all facts about types during compilation. For any, it remembers a typeid which it can be used to get an exact match, and how to convert its storage to said exact match.
Upvotes: 4 <issue_comment>username_3: `std::any` *has* to be implemented with type-erasure. That's because it can store *any* type and can't be a template. There is just no other functionality in C++ to achieve this at the moment.
What that means is that `std::any` will store a type-erased pointer, `void*` and `std::any_cast` will convert that pointer to the specified type and that's it. It just does a sanity check using `typeid` before to check whether you the type you cast it to is the one stored into the any.
Allowing implicit conversions would be impossible using the current implementation. Think about it (ignore the `typeid` check for now).
```
std::any_cast(a);
```
`a` stores an `int` and not a `long`. How should `std::any` know that? It can just cast its `void*` to the type specified, dereference it and return it. Casting a pointer from one type to another is a strict aliasing violation and results in UB, so that's a bad idea.
`std::any` would have to store the actual type of the object stored in it, which is not possible. You can't store types in C++ right now. It could maintain a list of types along with their respective `typeid`s and switch over them to get the current type and perform the implicit conversion. But there is no way to do that for *every* single type that you are going to use. User defined types wouldn't work anyways, and you'd have to rely on things such as macros to "register" your type and generate the appropriate switch case for it1.
Maybe something like this:
```
template
T any\_cast(const any &Any) {
const auto Typeid = Any.typeid();
if (Typeid == typeid(int))
return \*static\_cast(Any.ptr());
else if (Typeid == typeid(long))
return \*static\_cast(Any.ptr());
// and so on. Add your macro magic here.
// What should happen if a type is not registered?
}
```
Is this a good solution? No, by far. The switch is costly, and C++'s mantra is "you don't pay for what you don't use" so no, there is no way of achieving this currently. The approach is also "hacky" and very brittle (what happens if you forget to register a type). In short, the possible benefits of doing something like this is not worth the trouble in the first place.
>
> is there a workaround to allow an implicit conversion (in case the exact type that std::any holds is unknown)?
>
>
>
Yes, implement `std::any` (or a comparable type) and `std::any_cast` yourself using the macro register approach mentioned above1. I won't recommend it though. If you don't and can't know what type `std::any` stores and need to access it, you have a possible design flaw.
---
1: Don't actually know if this is possible, I'm not that good in macro (ab)use. You can also hard-code your types in for your custom implementation or use a separate tool for it.
Upvotes: 3 <issue_comment>username_4: This could be implemented by trying a contingency implicit conversion, if the type id of the requested type was not the same as the type id of the stored type. But it would involve a cost and hence violate the ["not pay for what you don't use"](https://stackoverflow.com/questions/28304992/how-can-i-better-learn-to-not-pay-for-what-you-dont-use) principle. Another `any` shortcoming, for example, is the inability to store an array.
```
std::any("blabla");
```
will work, but it will store a `char const*`, not an array. You could add such a feature in your own customized `any`, but then you'd need to store a pointer to a string literal by doing:
```
any(&*"blabla");
```
which is kind of odd. The decisions of the Standard committee are a compromise and never satisfy everyone, but you fortunately have the option of implementing your own `any`.
You could also extend `any` to store and then invoke type-erased [functors](https://github.com/username_4/generic/blob/master/callback.cpp), for example, but this is also not supported by the Standard.
Upvotes: 1 <issue_comment>username_5: This question is not well posed; implicit conversion to the right type are *in principle* possible, but disabled.
This restriction probably exists to maintain a certain level of safety or to mimic the explict cast necessary (through pointer) in the C-version of `any` (`void*`).
(The example implementation below shows that it is possible.)
Having said that, your target code still doesn't work because you need to know the exact type before conversion, but this can *in principle* work:
```
any a = 10; // holds an int now
long b = int(a); // possible but today's it needs to be: long b = any_cast(a);
```
To show that implicit conversions are *technically* possible (but can fail at runtime):
```
#include
struct myany : boost::any{
using boost::any::any;
template operator T() const{return boost::any\_cast(\*this);}
};
int main(){
boost::any ba = 10;
// int bai = ba; // error, no implicit conversion
myany ma = 10; // literal 10 is an int
int mai = ma; // implicit conversion is possible, other target types will fail (with an exception)
assert(mai == 10);
ma = std::string{"hello"};
std::string mas = ma;
assert( mas == "hello" );
}
```
Upvotes: 1 |
2018/03/22 | 849 | 1,829 | <issue_start>username_0: I want to find files having date in their extension.
In a folder having following files:
```
jvm-app-0.log.20180124.0000
jvm-app-0.log.20180124.0341
jvm-app-0.log.20180124.0341.tz
jvm-app-0.log.20180124.0355
```
I only want to find
```
jvm-app-0.log.20180124.0000
jvm-app-0.log.20180124.0341
jvm-app-0.log.20180124.0355
```
**Edit:** Also if second block is optional. e.g.
```
access.log.20180124
access.log.20180125
```
I tried following:
```
find . * | grep "\*\.[0-9]{8}\.\*"
find . -regextype posix-egrep -regex '*\.[0-9+]\.[0-9+]'
find . -regextype posix-egrep -regex '*\.[0-9+]\.*'
find . -regextype posix-egrep -regex '\.[0-9+]\.*'
find . -regextype sed -regex "*.{[0-9]+\.[0-9]+}"
```<issue_comment>username_1: You are close, you may use this `find`:
```
find . -regextype posix-egrep -regex '.*\.[0-9]+\.[0-9]+$'
```
Above `find` will require `gnu find`. To make it work on other `find` versions such as `BSD` use:
```
find . -regex '.*\.[0-9]*\.[0-9]*$'
```
---
If you are using `bash` you may also use `extglob` with `globstar` and **avoid** `find`:
```
shopt -s globstar extglob nullglob
printf '%s\n' **/*.+([0-9])
```
Upvotes: 2 <issue_comment>username_2: ```
find . -regex '.*\.[0-9]+'
```
* Use `.*` rather than `*` at the front to match any prefix.
* `+` needs to be outside the square brackets.
* `-regextype` isn't necessary.
If you `extglob` is enabled then you can do this directly in the shell:
```
$ shopt -s extglob
$ ls *.+([0-9])
jvm-app-0.log.20180124.0000 jvm-app-0.log.20180124.0341 jvm-app-0.log.20180124.0355
```
If you want a recursive search, turn on `globstar` as well:
```
$ shopt -s extglob globstar
$ ls **/*.+([0-9])
jvm-app-0.log.20180124.0000 jvm-app-0.log.20180124.0341 jvm-app-0.log.20180124.0355
```
Upvotes: 3 [selected_answer] |
2018/03/22 | 2,076 | 7,000 | <issue_start>username_0: I've got a problem with a NullPointerException.
This is my Controller:
```
public class Controller implements Initializable{
public Label lbTitle;
public Label lbAuthor;
public Label lbChapters;
public TextField tfTitle;
public TextField tfAuthor;
public TextArea taChapters;
public ListView listView;
private void OpenNewWindow(Book book1) throws Exception {
String selected = listView.getSelectionModel().getSelectedItem().toString();
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("/zli/BooksFX/NewWindow.fxml"));
Scene scene = new Scene(fxmlLoader.load(), 400, 400);
Stage stage = new Stage();
tfTitle.setText(book1.getTitle());
tfAuthor.setText(book1.getAuthor());
taChapters.setText(book1.toStringChapters());
stage.setTitle(selected);
stage.setScene(scene);
stage.show();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
Chapter chapter1Book1 = new Chapter(1, 100, "First Chapter...");
Chapter chapter2Book1 = new Chapter(2, 400, "Second Chapter...");
ArrayList book1Chapters = new ArrayList<>();
book1Chapters.add(chapter1Book1);
book1Chapters.add(chapter2Book1);
Book book1 = new Book("IT: Not the one with the clown", "<NAME>", book1Chapters);
Chapter chapter1Book2 = new Chapter(1, 100, "First Chapter...");
Chapter chapter2Book2 = new Chapter(2, 400, "Second Chapter...");
ArrayList book2Chapters = new ArrayList<>();
book1Chapters.add(chapter1Book2);
book1Chapters.add(chapter2Book2);
Book book2 = new Book("Z Men", "<NAME>", book2Chapters);
Chapter chapter1Book3 = new Chapter(1, 100, "First Chapter...");
Chapter chapter2Book3 = new Chapter(2, 400, "Second Chapter...");
ArrayList book3Chapters = new ArrayList<>();
book1Chapters.add(chapter1Book3);
book1Chapters.add(chapter2Book3);
Book book3 = new Book("Captain AlivePool", "Undead Zombie", book3Chapters);
ObservableList items = FXCollections.observableArrayList (book1, book2, book3);
listView.setItems(items);
listView.setOnMouseClicked(e -> {
try {
OpenNewWindow(book1);
} catch (Exception e1) {
e1.printStackTrace();
}
});
}
}
```
And this is my .fxml:
```
```
And this is the Error message:
```
java.lang.NullPointerException
at zli.BooksFX.Controller.OpenNewWindow(Controller.java:37)
at zli.BooksFX.Controller.lambda$initialize$0(Controller.java:73)
at javafx.base/com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at javafx.base/com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at javafx.base/com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at javafx.base/com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at javafx.base/com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at javafx.base/com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.base/javafx.event.Event.fireEvent(Event.java:198)
at javafx.graphics/javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3589)
at javafx.graphics/javafx.scene.Scene$ClickGenerator.access$8300(Scene.java:3517)
at javafx.graphics/javafx.scene.Scene$MouseHandler.process(Scene.java:3885)
at javafx.graphics/javafx.scene.Scene$MouseHandler.access$1300(Scene.java:3604)
at javafx.graphics/javafx.scene.Scene.processMouseEvent(Scene.java:1874)
at javafx.graphics/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2613)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:397)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:434)
at javafx.graphics/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at javafx.graphics/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:433)
at javafx.graphics/com.sun.glass.ui.View.handleMouseEvent(View.java:556)
at javafx.graphics/com.sun.glass.ui.View.notifyMouse(View.java:942)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:175)
at java.base/java.lang.Thread.run(Thread.java:844)
```
Now, when I want to set the Text of my TextFields and TextAreas (tfTitle, tfAuthor, taChapters) to the assigned value, it gives me a "java.lang.NullPointerException" on the Line 37 in Controller, which is this:
```
tfTitle.setText(book1.getTitle());
```
And for your information: "Book" is a storage Class for Chapters.
Because it was asked for, my other .fxml:
```
```<issue_comment>username_1: May be you have not initialized your Texfield.
use `@FXML` Annotation over tfTitle declaration
```
@FXML
public TextField tfTitle;
```
Same goes for other fields too.
Upvotes: 1 <issue_comment>username_2: You use the class `Controller` as the controller of two different fxml-files.
The first only declares `listView` but not `tfTitle`, `tfAuthor` and `taChapters` therefore you get a NullPointerException at `tfTitle.setText(book1.getTitle());`
When you load the second fxml-file in `OpenNewWindow` you also creates a new `Controller` object.
Now you can reuse the first controller with `fxmlLoader.setController(this);` and remove `fx:controller="zli.BooksFX.Controller"` from `NewWindow.fxml` (**Don't do this since you will run into similar problems like this**).
Or create two independent controller for each fxml-file and pass the book between the controllers.
For the second controller you need something like:
```
public void setBook(Book book) {
tfTitle.setText(book.getTitle());
tfAuthor.setText(book.getAuthor());
taChapters.setText(book.toStringChapters());
}
```
And pass the book with `((BookDetailController)fxmlLoader.getController()).setBook(book1);` after `fxmlLoader.load()`
Upvotes: 1 [selected_answer] |
2018/03/22 | 643 | 2,411 | <issue_start>username_0: [](https://i.stack.imgur.com/jOmMb.png)
My scenario is as shown in the above image. Here customer and shop will be using a windows form application and there is local DB for both.
For example if customer checks for shops products and place order, it will store in local DB of customer and then push it to central server, from there particular shop should get the order details notification. similarly if order is approved, the data should be updated in central server as well as it should push to customer local DB as update.
we tried using SignalR For this, based on this article [Is it correct to use SignalR for desktop applications?](https://stackoverflow.com/questions/31261987/is-it-correct-to-use-signalr-for-desktop-applications?answertab=active#tab-top) there is no direct support of signalR for windows Forms.
what about using [Microsoft Sync Framework](https://msdn.microsoft.com/en-us/library/bb902854(v=sql.110).aspx) for this, will it be fine and do the job for me?
So is there any other technique to implement real time data sync in c# windows forms.<issue_comment>username_1: May be you have not initialized your Texfield.
use `@FXML` Annotation over tfTitle declaration
```
@FXML
public TextField tfTitle;
```
Same goes for other fields too.
Upvotes: 1 <issue_comment>username_2: You use the class `Controller` as the controller of two different fxml-files.
The first only declares `listView` but not `tfTitle`, `tfAuthor` and `taChapters` therefore you get a NullPointerException at `tfTitle.setText(book1.getTitle());`
When you load the second fxml-file in `OpenNewWindow` you also creates a new `Controller` object.
Now you can reuse the first controller with `fxmlLoader.setController(this);` and remove `fx:controller="zli.BooksFX.Controller"` from `NewWindow.fxml` (**Don't do this since you will run into similar problems like this**).
Or create two independent controller for each fxml-file and pass the book between the controllers.
For the second controller you need something like:
```
public void setBook(Book book) {
tfTitle.setText(book.getTitle());
tfAuthor.setText(book.getAuthor());
taChapters.setText(book.toStringChapters());
}
```
And pass the book with `((BookDetailController)fxmlLoader.getController()).setBook(book1);` after `fxmlLoader.load()`
Upvotes: 1 [selected_answer] |
2018/03/22 | 943 | 3,342 | <issue_start>username_0: I have 3 **tables** and I want to return
the **customers** name and **total** sum of each **deposit** and **credit** amount.
```
deposit customers credit
id id id
d_amount c_amount
customer_id name customer_id
type(credit,etc)
```
I'm doing it by this query =>
```
SELECT customers.name ,
sum(deposit.d_amount) as total_depot,
sum(credit.c_amount) as total_credit
from customers
inner join deposit on deposit.customer_id = customers.id
inner join credit on credit.customer_id = customers.id
and credit.type='credit'
group by customers.id order by customers.name asc
```
Unfortunately the result of **total\_depot** and **total\_credit** **is not correct**
but when I'm doing it separately like this =>
```
SELECT customers.name , sum(deposit.d_amount) as total_depot
from customers
inner join deposit on deposit.customer_id = customers.id
group by customers.id order by customers.name asc
SELECT customers.name , sum(credit.d_amount) as total_credit
from customers
inner join credit on credit.customer_id = customers.id
and credit.type='credit'
group by customers.id order by customers.name asc
```
The result of **total\_depot** and **total\_credit** is correct
I don't know where is the error.<issue_comment>username_1: Do the aggregation *before* joining the tables:
```
select c.name, d.total_deposit, cr.total_credit
from customers c join
(select d.customer_id, sum(d.d_amount) as total_deposit
from deposit d
group by d.customer_id
) d
on d.customer_id = c.id join
(select c.customer_id, sum(c.c_amount) as total_credit
from credit c
where c.type = 'credit'
group by c.customer_id
) cr
on cr.customer_id = c.id
order by c.name asc;
```
Upvotes: 0 <issue_comment>username_2: The first query is totally wrong, JOINS will multiply lines in result. Example for ONE customer, 3 his credits and 5 his deposits:
select from customers returns 1 line
customers INNER JOIN credits returns 3 lines
customers INNER JOIN credits INNER JOIN deposits returns 15 lines
That is not what you want. Execute your query without SUM and GROUP BY, you will see it.
This is what you want (simplified, not tested):
```
select customers.id, cr.amount, dep.amount
from customers
left join (select customer_id, sum(credit.d_amount) as amount from credits group by customer_id) cr on cr.customer_id=customers.id
left join (select customer_id, sum(deposits.d_amount) as amount from deposits group by customer_id) dep on dep.customer_id=customers.id
```
btw. LEFT join is needed for cases when customer does not have BOTH deposit and credit
Upvotes: 2 <issue_comment>username_3: **Thanks so lot every body**'
i try with all of this exam but it's does not work
i finally make this. **its work.**
```
select customers.name, total_depot , total_credit
from customers
left join (select customer_id , d_amount , sum(deposit.d_amount) as total_deposit from deposit group by customer_id) d on d.customers_id = customers.id
left join (select customer_id , c_amount , sum(credit.c_amount) as total_fact from credit where credit.type='credit' group by customer_id) c on c.id = customers.id
group by customers.name
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 835 | 2,834 | <issue_start>username_0: I am able to get meta field in cart and checkout pages, But in email I tried to get using `$order` array but don't find any custom field in email.
How can I get custom meta fields in email notificatios (Admin, Customer)?
My code is following:
```
function wdm_add_custom_order_line_item_meta($item, $cart_item_key, $values, $order)
{
if(array_key_exists('wdm_name', $values))
{
$item->add_meta_data('_wdm_name',$values['wdm_name']);
}
}
add_action( 'woocommerce_email_order_details', 'action_email_order_details', 10, 4 );
function action_email_order_details( $order, $sent_to_admin, $plain_text, $email ) {
if( $sent_to_admin ): // For admin emails notification
echo get_post_meta( $order->id, '_wdm_name', true );
endif;
}
```
Any help is appreciated.<issue_comment>username_1: Do the aggregation *before* joining the tables:
```
select c.name, d.total_deposit, cr.total_credit
from customers c join
(select d.customer_id, sum(d.d_amount) as total_deposit
from deposit d
group by d.customer_id
) d
on d.customer_id = c.id join
(select c.customer_id, sum(c.c_amount) as total_credit
from credit c
where c.type = 'credit'
group by c.customer_id
) cr
on cr.customer_id = c.id
order by c.name asc;
```
Upvotes: 0 <issue_comment>username_2: The first query is totally wrong, JOINS will multiply lines in result. Example for ONE customer, 3 his credits and 5 his deposits:
select from customers returns 1 line
customers INNER JOIN credits returns 3 lines
customers INNER JOIN credits INNER JOIN deposits returns 15 lines
That is not what you want. Execute your query without SUM and GROUP BY, you will see it.
This is what you want (simplified, not tested):
```
select customers.id, cr.amount, dep.amount
from customers
left join (select customer_id, sum(credit.d_amount) as amount from credits group by customer_id) cr on cr.customer_id=customers.id
left join (select customer_id, sum(deposits.d_amount) as amount from deposits group by customer_id) dep on dep.customer_id=customers.id
```
btw. LEFT join is needed for cases when customer does not have BOTH deposit and credit
Upvotes: 2 <issue_comment>username_3: **Thanks so lot every body**'
i try with all of this exam but it's does not work
i finally make this. **its work.**
```
select customers.name, total_depot , total_credit
from customers
left join (select customer_id , d_amount , sum(deposit.d_amount) as total_deposit from deposit group by customer_id) d on d.customers_id = customers.id
left join (select customer_id , c_amount , sum(credit.c_amount) as total_fact from credit where credit.type='credit' group by customer_id) c on c.id = customers.id
group by customers.name
```
Upvotes: 1 [selected_answer] |
2018/03/22 | 793 | 3,144 | <issue_start>username_0: I'm trying to resolve data before navigating to children routes as i have to use that data in children guard. The issue is parent resolver, resolves data after the child guard is fired. Resolver takes long time to resolve data
```
// app.module.ts
const appRoutes: Routes = [
{ path: 'login', component: LoginComponent },
{
path: '',
component: SiteLayoutComponent,
children: [
{ path: '', redirectTo: 'warehouse', pathMatch: 'full' },
{
path: 'warehouse',
loadChildren: './warehouse/warehouse.module#WarehouseModule'
// loadChildren: () => WarehouseModule
}
],
canActivate: [AuthGuard],
resolve: {
Site: SiteResolver // should be resolved before the guard is invoked.
}
},
{ path: '**', component: PageNotFoundComponent }
];
// warehouse.module.ts
const appRoutes: Routes = [
{ path: '', redirectTo: 'cash', pathMatch: 'full' },
{ path: 'cash', component: CashComponent, canActivate: [RouteGuard] // should be invoked after the parent resolver resloves th data }
];
```
Here, the parent resolver i.e. SiteResolver resolves after the child guard i.e. RouteGuard is invoked. What i want is SiteResolver to resolve data first and then RouteGuard should fire, how can i achieve that ?<issue_comment>username_1: I am not sure if this is the correct method. But after going through a lot of angular issues , i found a workaround.
Instead of resolve , use canActivate to fetch data and store the data in the service. Below is the code snippet for the same
```
@Injectable()
export class FetchUserData implements CanActivate {
constructor(
private userService: UserService,
private httpClient: HttpClient
) {}
public modalRef: BsModalRef;
canActivate() {
return this.httpClient
.get("some/api/route")
.map(e => {
if (e) {
this.userService.setUserDetails(e);
return true;
}
return true;
})
.catch(() => {
return Observable.of(false);
});
}
}
```
It worked for me well. You will have no problem in refreshing the child route.
Upvotes: 3 <issue_comment>username_2: My solution to this situation was to **wrap** the entire application in a **lazy module** and hang **canLoad** on it
```
{
path: '',
children: [
{
path: '',
canLoad: [PortalResolver],
loadChildren: () => import('./portal/portal.module').then(m => m.PortalModule),
}
],
},
```
Upvotes: 0 <issue_comment>username_3: Usage notes
When both guard and resolvers are specified, the resolvers are not executed until all guards have run and succeeded. For example, consider the following route configuration:
```html
{
path: 'base'
canActivate: [BaseGuard],
resolve: {data: BaseDataResolver}
children: [
{
path: 'child',
guards: [ChildGuard],
component: ChildComponent,
resolve: {childData: ChildDataResolver}
}
]
}
```
The order of execution is: **BaseGuard**, **ChildGuard**, **BaseDataResolver**, **ChildDataResolver**.
<https://angular.io/api/router/Resolve#usage-notes>
Upvotes: 0 |
2018/03/22 | 790 | 2,120 | <issue_start>username_0: I have a database which looks like
Table1
```
ID Date
1 2018-01-01 15:04:03
2 2018-01-02 18:06:05
3 2018-01-03 23:21:12
4 2018-02-01 15:04:03
5 2018-02-02 18:06:05
6 2018-02-03 23:21:12
```
I want the count based on Month either in `JAN-18` format or in `2018-01` format.
Required output:
```
Month Count
JAN-18 3
FEB-18 3
```<issue_comment>username_1: `GROUP BY` the year and the month:
```
select year(Date), month(Date), count(*)
from table1
group by year(Date), month(Date)
```
Formatting the output shouldn't be that tricky, but I don't know MySQL...
Try `concat(cast(year(Date) as char(4)),'-',cast(month(Date) as char(2)))`.
Upvotes: 1 <issue_comment>username_2: This is what you want:
```
SELECT CONCAT(UPPER(DATE_FORMAT(Date, '%b')),'-',year(Date)), count(*)
FROM table1
GROUP BY CONCAT(UPPER(DATE_FORMAT(Date, '%b')),'-',year(Date))
```
Upvotes: 0 <issue_comment>username_3: You might use the `DATE_FORMAT()` function:
```
SELECT DATE_FORMAT(Date, '%Y-%m'), COUNT(*)
FROM Table1
GROUP BY DATE_FORMAT(Date, '%Y-%m')
```
`%m` in the mask will give the month's number (01-12) and `%Y` is the 4-digit year; use the following to get the other format you mentioned:
```
SELECT UPPER(DATE_FORMAT(Date, '%b-%y')), COUNT(*)
FROM Table1
GROUP BY UPPER(DATE_FORMAT(Date, '%b-%y'))
```
`%b` is the month's name abbreviated, but capitalized rather than all-uppercase; `%y` is the 2-digit year.
Upvotes: 0 <issue_comment>username_4: ```
select DATE_FORMAT(Date, '%b-%y'), count(*) from table1 group by YEAR(Date), MONTH(Date)
```
* %b: Abbreviated month name (Jan..Dec)
* %y: Year, numeric (two digits)
see: <https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format>
Upvotes: 0 <issue_comment>username_5: The format yyyy-mm is sortable, so use this to group by:
```
select date_format(date, 'Y-m') as month, count(*)
from table1
group by month
order by month;
```
(Grouping by the alias name is not valid in standard SQL, but in MySQL it is and it gets the query very readable.)
Upvotes: 0 |
2018/03/22 | 892 | 2,467 | <issue_start>username_0: I'm displaying set of range values in two list boxes using VBA form. In `listbox1` headers, then per input displaying relevant data in `listbox2` by using the below code:
```
'header
Set rng = sht.Range("A1:I1")
With ListBox1
.ColumnCount = 9
.ColumnWidths = "50;40;30;120;160;120;50;30;30"
.RowSource = rng.Address
End With
'dynamic data
Set rng1 = sht.Range(Cells(st, ukey), Cells(st + en - 1, utim))
With ListBox2
.ColumnCount = 9
.ColumnWidths = "50;40;30;120;160;120;50;30;30"
.RowSource = rng1.Address
End With
```
How can I add the header and data in one listbox after the heading?
Also how can I add column 10 to 15 in the listbox from another set of ranges?<issue_comment>username_1: How to add the header and data in one listbox after the heading?
Unite the two ranges, representing the header and the values like this
```
Set rng = Union(rng, rng1)
.RowSource = rng.Address
```
This is some small sample that works, combining both ranges into one listbox:
```
Private Sub UserForm_Activate()
Dim rng As Range
Dim rngTitle As Range
Set rng = Range("D2:L3")
Set rngTitle = Range("D1:L1")
Set rng = Union(rng, rngTitle)
With ListBox1
.ColumnCount = 9
.ColumnWidths = "50;40;30;120;160;120;50;30;30"
.RowSource = rng.Address
End With
End Sub
```
This is what I get:
[](https://i.stack.imgur.com/EGOe6.png)
Upvotes: 2 <issue_comment>username_2: I merged the ranges by using UNION as mentioned above by username_1 and moved them to a temp workbook and displayed by using the below code :)
```css
Set rngt1 = sht.Range("A1:I1")
Set rngt2 = sht.Range("X1:AE1")
Set rngt3 = sht.Range("AI1")
Set rngd1 = sht.Range(Cells(st, ukey), Cells(st + en - 1, utim))
Set rngd2 = sht.Range(Cells(st, ccat), Cells(st + en - 1, etag))
Set rngd3 = sht.Range(Cells(st, comt), Cells(st + en - 1, comt))
Set rngt = Union(rngt2, rngt1)
Set rngt = Union(rngt3, rngt)
Set rngd = Union(rngd2, rngd1)
Set rngd = Union(rngd3, rngd)
Workbooks.Add
rngt.Copy ActiveSheet.Range("A1")
rngd.Copy ActiveSheet.Range("A2")
Set rng = ActiveSheet.Range(Cells(2, 1), Cells(en + 1, 18))
With ListBox2
.ColumnCount = 18
.RowSource = rng.Address
.ColumnHeads = True
End With
```
Thank you username_1 for the help :)
Upvotes: 0 |
2018/03/22 | 885 | 3,165 | <issue_start>username_0: I have a problem with resource starvation on my java application running in wildfly.
It is making a lot of API calls to other REST resources, and if one of these API:s is slowed down, our system goes down as well.
It has happened that the backend systems are not responding within 14 seconds. So I would like my application to break the connection after maybe 4 seconds.
The "problem" is that we are using `Client` and `ClientBuilder` from `javax.ws.rs.client` and we are using wildfly as an implementation.
So I have no idea how to set this timeout parameter. It doesn't appear to be possible from code, and I'm quite lost as to which wildfly subsystem is affected and what properties to set.
Has anyone done this before and know how to set the timeout?<issue_comment>username_1: You could use the CONNECT\_TIMEOUT Jersey client property as show those posts:
* <http://www.adam-bien.com/roller/abien/entry/implementing_connect_and_read_timeouts>
* <http://www.adam-bien.com/roller/abien/entry/setting_timeout_for_the_jax>
* <http://www.adam-bien.com/roller/abien/entry/setting_timeout_for_jax_rs>
Upvotes: 1 <issue_comment>username_2: So since wildfly comes bundled with resteasy you have to implement a timeout for that specific implementation. That or force wildfly to use something else. Since forceing jersey upon wildfly didn't seem like the best of ideas(or the easiest) I went with configuring it.
<http://blog.eisele.net/2014/12/setting-timeout-for-jax-rs-20-resteasy-client.html>
```
import javax.ws.rs.client.Client;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(100, TimeUnit.SECONDS)
.socketTimeout(2, TimeUnit.SECONDS)
.build();
```
and I've added the following in the pom.xml:
```
org.jboss.resteasy
resteasy-client
3.0.19.Final
```
Upvotes: 0 <issue_comment>username_3: Given that both **establishConnectionTimeout** and **socketTimeout** are deprecated.
With this explanation on jboss v7.3 by [redhat website](https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.3/html-single/developing_web_services_applications/index) :
>
> The following ClientBuilder specification-compliant methods replace certain deprecated RESTEasy methods:
>
>
> * The **connectTimeout** method replaces the **establishConnectionTimeout** method.
>
>
> + The **connectTimeout** method determines how long the client must wait when making a new server connection.
> * The **readTimeout** method replaces the **socketTimeout** method.
>
>
> + The **readTimeout** method determines how long the client must wait for a response from the server.
>
>
>
This worked for me with **RestEASY 3.12.1.Final**:
```
private Client clientBuilder() {
return new ResteasyClientBuilder()
.connectTimeout(2, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
}
```
```
org.jboss.resteasy
resteasy-client
3.12.1.Final
```
Upvotes: 0 |
2018/03/22 | 1,007 | 3,629 | <issue_start>username_0: I don't mind rooting a device as the application will only be used privately, i'm working on a project that requires to monitor the call state of a device, have read the documentation on it
<https://developer.android.com/reference/android/telecom/Call.html>
and i have been using it but i'm having issue knowing when a call is picked, have checked the documentation and stackoverflow, have realized is a known issue from google itself.
[Detecting outgoing call answered on Android](https://stackoverflow.com/questions/16683781/detecting-outgoing-call-answered-on-android)
[In rooted device detect if an outgoing call has been answered](https://stackoverflow.com/questions/34586207/in-rooted-device-detect-if-an-outgoing-call-has-been-answered)
and many others that i have tried.
i understand there is no documented method to achieve this, i'm sure this will be possible because android itself calculate the time spent on a call and also some applications too like TRUE CALLER and some other private app monitor the time spent which is based on when a call is picked and when they hang-up from the call.
Have tried a lot myself before deciding to post this,
any suggestion on how to achieve this on a ROOTED device.<issue_comment>username_1: You could use the CONNECT\_TIMEOUT Jersey client property as show those posts:
* <http://www.adam-bien.com/roller/abien/entry/implementing_connect_and_read_timeouts>
* <http://www.adam-bien.com/roller/abien/entry/setting_timeout_for_the_jax>
* <http://www.adam-bien.com/roller/abien/entry/setting_timeout_for_jax_rs>
Upvotes: 1 <issue_comment>username_2: So since wildfly comes bundled with resteasy you have to implement a timeout for that specific implementation. That or force wildfly to use something else. Since forceing jersey upon wildfly didn't seem like the best of ideas(or the easiest) I went with configuring it.
<http://blog.eisele.net/2014/12/setting-timeout-for-jax-rs-20-resteasy-client.html>
```
import javax.ws.rs.client.Client;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
Client client = new ResteasyClientBuilder()
.establishConnectionTimeout(100, TimeUnit.SECONDS)
.socketTimeout(2, TimeUnit.SECONDS)
.build();
```
and I've added the following in the pom.xml:
```
org.jboss.resteasy
resteasy-client
3.0.19.Final
```
Upvotes: 0 <issue_comment>username_3: Given that both **establishConnectionTimeout** and **socketTimeout** are deprecated.
With this explanation on jboss v7.3 by [redhat website](https://access.redhat.com/documentation/en-us/red_hat_jboss_enterprise_application_platform/7.3/html-single/developing_web_services_applications/index) :
>
> The following ClientBuilder specification-compliant methods replace certain deprecated RESTEasy methods:
>
>
> * The **connectTimeout** method replaces the **establishConnectionTimeout** method.
>
>
> + The **connectTimeout** method determines how long the client must wait when making a new server connection.
> * The **readTimeout** method replaces the **socketTimeout** method.
>
>
> + The **readTimeout** method determines how long the client must wait for a response from the server.
>
>
>
This worked for me with **RestEASY 3.12.1.Final**:
```
private Client clientBuilder() {
return new ResteasyClientBuilder()
.connectTimeout(2, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
}
```
```
org.jboss.resteasy
resteasy-client
3.12.1.Final
```
Upvotes: 0 |
2018/03/22 | 948 | 2,947 | <issue_start>username_0: I've setup a private Docker registry on my PC and I'm able to pull and push the image to it and pull it back again if I use the following command :
`docker pull localhost:5000/new_buntu`
But, if I replace `localhost` with my IP address, it doesn't work.
```
$ docker pull 10.118.56.140:5000/new_buntu
Using default tag: latest
Error response from daemon: Get https://10.118.56.140:5000/v2/: Tunnel or SSL Forbidden
```
Now an interesting observation is, if I want see the list of images inside my docker registry, I visit:
`http://localhost:5000/v2/_catalog`
which is an HTTP URL. But, as seen in the output, when I try to pull an image using my IP address, it tries to connect over HTTPS. I wonder if docker has some sort of setting that if the images is not being pulled from localhost, it'll force the SSL. If so, how do I stop it?
I've tried putting "http" in the pull command but it didn't work:
```
$ docker pull http://10.118.56.140:5000/new_buntu
invalid reference format
```
I want all the people on my network to be able to fetch image from my registry. How do I do it?<issue_comment>username_1: Took me a little effort exploring this issue but finally I figured it out. Docker, as it seems, does force SSL if the image is being pulled from a remote machine. To prevent this behavior, we need to specifically tell docker that the registry we're trying to connect to isn't SSLized. Follow these steps to configure the docker image for it:
1. Right Click on the docker’s icon in the icon bar.
[](https://i.stack.imgur.com/24QSx.png)
2. Click on “Settings”.
[](https://i.stack.imgur.com/ouYP4.png)
3. Go to the “Daemon” Tab in the Settings Panel.
[](https://i.stack.imgur.com/HTPmq.png)
4. Add the registry’s IP address and port number in “Insecure registries” section. (10.118.56.140:5000 in my case)
[](https://i.stack.imgur.com/fTTW0.png)
5. Open a browser and visit http://:/v2/\_catalog to see the list of all the available images. (<http://10.118.56.140:5000/v2/_catalog> in my case)
[](https://i.stack.imgur.com/2OTsc.png)
6. Issue the following command to pull the image.
docker pull IP\_Address:Port\_Number/Image\_Name
For eg:
```
docker pull 10.118.56.140:5000/new_buntu
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I had the same issue, but I needed to configure the "bypass proxy settings" with the URL of my Registry. Later, I did what 7\_R3X wrote here with this on "Docker Engine" configuration:
```
{
...
,
"insecure-registries": [
"http://registry-url:8444"
],
"registry-mirrors": []
}
```
Upvotes: 0 |
Subsets and Splits