date
stringlengths 10
10
| nb_tokens
int64 60
629k
| text_size
int64 234
1.02M
| content
stringlengths 234
1.02M
|
---|---|---|---|
2018/03/21 | 654 | 2,407 | <issue_start>username_0: I'm trying to write my own setup.py to be able to import the module but I get errors
```
import mylib
>>> ModuleNotFoundError: No module named 'mylib'
```
My problem is that I do not understand why this is happening.
Currently I'm using windows and conda and have created an evnironment named "rig" where i try to install the packaged by:
```
(rig) C:\> pip install -e "path to lib"
```
After installation I can see that the lib has been installed
```
pip list
>> ...
>> mylib (1.2.3)
>> ...
```
It seems like the correct python executable are used:
```
import sys"
print(sys.executable)
>>>C:\ProgramData\Anaconda3\envs\rig\python.exe
```
how can it be that pip lists the module but it's not possible to import it?
How do I debug this problem, suggestions?
my setup.py file:
```
from setuptools import setup, find_packages
setup(name='mylib',
description="experimental platform for ejector-program",
author="<NAME>",
version='1.2.3',
license='GPLv3',
packages = ['JetFiles'], #packages=find_packages(exclude=['examples','tests']),
install_requires=['mongoengine',
'pandas',
'numpy',
'pyvalid'],
)
```<issue_comment>username_1: I think you have wrong import. Because setup name != real package name
Try:
```
import JetFiles
```
Also check you run python in venv or not.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Check that the path to python.exe which usually in a desktop env is at `C:\PythonXX\' is the same as the python\scripts folder where`pip` is located and therefore the modules that are being retrieved later.
I've encountered something similar sometimes when having installed python 2.7 and 3.x at the same time and having as env. variable `C:\Program Files\Python36` but `pip` pointing to `C:\Python27`.
Upvotes: 0 <issue_comment>username_3: You need create your program by a structure for use setuptools.
Try to read this <https://pythonhosted.org/an_example_pypi_project/setuptools.html>
Now you can import setup from setuptools and tell setup function.
for example:
```
from setuptools import setu
setup(
name = "yourProgram",
version = "1",
author = "you",
author_email = "<EMAIL>",
description = (""),
keywords = "",
url = "",
packages=['', ''],
long_description=read('README'),)
```
Upvotes: 0 |
2018/03/21 | 290 | 1,084 | <issue_start>username_0: I have already found the "Request Preview" [page](https://pages.awscloud.com/NeptunePreview.html), apart from that is there any way to deploy and test Neptune locally?<issue_comment>username_1: AWS Neptune can be tested only from within the VPC. What you can probably do is
1. Create an ec2 instance in the same VPC
2. Install Gremlin/ SPARQL console in ec2 (if you need to execute queries)
3. connect to Neptune via ec2
4. Execute queries
Neptune DB can be either SPARQL/ Gremlin. It is based on the first query you hit.
If SPARQL, metaphacts can be used for the visual representation of the database.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Update: Neptune is Generally Available in 4 regions as of June 2018 and you should be able to create instances on your own without requiring any white-listing. You can use some of the [cloud formation examples](https://docs.aws.amazon.com/neptune/latest/userguide/quickstart.html) to get a test setup created in minutes. There is no other way to test Neptune unfortunately.
Upvotes: 1 |
2018/03/21 | 1,295 | 4,464 | <issue_start>username_0: My application developed in NativeScript. For FCM I use `nativescript-plugin-firebase`.
I have received a push notification whenever I tried from the FCM console. But, I never received a push notification when I try from post man as below.
```
URL : POST : https://fcm.googleapis.com/fcm/send
Headers : Authorization = key="******", Content-Type=application/json
```
Data :
```
{
"data": {
"title": "RAJA RAJA",
"message": "another test",
"name": "<NAME>"
},
"to" : "**************************************"
}
```
Response :
```
{
"multicast_id": 5806593945960213086,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1521623661699559%161a06bff9fd7ecd"
}
]
}
```
Anyone knows what have I missed that push notification is not coming when I try in postman even though I get a success response.<issue_comment>username_1: ```
{
"to" : "********",
"priority": "high",
"notification": {
"title": "Title",
"body" : "First Notification",
"text": "Text"
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_2: Send Data Message using HTTP protocol with POSTMAN
You have to copy Legecy Server Key from Firebase Console > Project Settings > Cloud Messaging
Note: Firebase has upgraded our server keys to a new version. You may continue to use your Legacy server key, but it is recommended that you upgrade to the newest version.
Select POST. Enter request URL as <https://fcm.googleapis.com/fcm/send>
Add Headers Authorization: key= OR Authorization: key=and Content-Type: application/json.
Setting-up with POSTMAN
Now Select Body > raw > JSON (application/json) and add following code:
```
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
}
```
You can push a Generic notification (with notification payload) or a Custom notifications (with notification and data payload) and hit Send.
```
{
"to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
"collapse_key" : "type_a",
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"key_2" : "Hellowww"
}
}
```
Note that Custom notification will only trigger if there is only data (without notification) node in the payload. Hence, you’d need to move the body and title to data node.
Keep in Mind : Use registration\_ids instead of to node if you want to send notification to multiple devices with corresponding firebase\_instance\_id's.
Upvotes: 0 <issue_comment>username_3: I am sending notification thru "topics" like:-
```
{
"to" : "/topics/XXXX",
"notification" : {
"body" : "First Notification",
"title": "Collapsing A",
"click_action":"DisplayTestActivity"
},
"data" : {
"body" : "First Notification",
"title": "Collapsing A",
"key_1" : "Data for key one",
"click_action":"DisplayTestActivity"
}
}
```
if you sending notification like this and you are unable to get the notification thru postman then
"Make sure that following line should be their in your splash activity or first page means executed before you are going to get notification "
```
FirebaseMessaging.Instance.SubscribeToTopic("XXXX");
if(!GetString(Resource.String.google_app_id).Equals("XXXXXXXXXXXXXXXXXXXXX")) throw new System.Exception("Invalid Json file");
Task.Run(() =>
{
var instanceId = FirebaseInstanceId.Instance;
instanceId.DeleteInstanceId();
Android.Util.Log.Debug("TAG", "{0} {1}", instanceId.Token, instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope));
});
```
\*above code is in c# so use your programming language..
thanks
Upvotes: 2 <issue_comment>username_4: 1. Open your application in mobile and connect it to PC
2. Then after opening chrome and paste this `chrome://inspect/#devices` in Remote Target Hit Inspect: [Demo1](https://i.stack.imgur.com/fppjT.png)
3. Then after you will see the `registrationId` under Device registered
4. Copy this Id and paste it after "to":"`registrationId`" in `POSTMAN`: [Demo2](https://i.stack.imgur.com/zHtv7.png)
Hope it helps!
Upvotes: 0 |
2018/03/21 | 414 | 1,455 | <issue_start>username_0: i have menu and highlighting works there fine, but when I in some subpage main menu item is not highlighted.
My code:
```
* [bla bla](/)
* [bla bla](Shipments)
```
My script:
```
$(function() {
var url = window.location.href;
$(".sidebar-nav-icons a").each(function() {
if (url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});
```
In Shipments page a have a link to next page with link "Shipments/Shipment".
When I'm in Shipments page menu item is highlighted, but when I'm in Shipment it's not. How to create it? Thanks<issue_comment>username_1: As you make an equals comparison between the URL and the anchor's href, the `active` class will only be applied if the page is the same.
A possible approach would be to check if the URL **starts with** the anchor's href.
```js
var url = window.location.href;
$(".sidebar-nav-icons a").each(function () {
if (url.startsWith(this.href)) {
$(this).closest("li").addClass("active");
}
});
```
Edit: if you're using relative paths, you can use `windows.location.pathname` instead of `window.location.href`.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to use [startsWith](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) function instead of equality check:
```js
if (url.startsWith(this.href)) {
// your highlight logic goes here
}
```
Upvotes: 0 |
2018/03/21 | 402 | 1,386 | <issue_start>username_0: I created a function that will add an item to an empty array up to a const max value. However, I can't figure out how to return true each time an item is successfully added to the array (and false each time an item couldn't be added).
Here is what I've got:
```
let adoptedDogs = [];
const maxDogs = 2;
function getDog( name ){
console.log( 'dog's name:', name );
if( adoptedDogs.length < maxDogs ){
adoptedDogs.push( name );
}
}
getDog( 'Spot' );
getDog( 'Daisy' );
getDog( 'Chester' );
```<issue_comment>username_1: As you make an equals comparison between the URL and the anchor's href, the `active` class will only be applied if the page is the same.
A possible approach would be to check if the URL **starts with** the anchor's href.
```js
var url = window.location.href;
$(".sidebar-nav-icons a").each(function () {
if (url.startsWith(this.href)) {
$(this).closest("li").addClass("active");
}
});
```
Edit: if you're using relative paths, you can use `windows.location.pathname` instead of `window.location.href`.
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have to use [startsWith](https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith) function instead of equality check:
```js
if (url.startsWith(this.href)) {
// your highlight logic goes here
}
```
Upvotes: 0 |
2018/03/21 | 643 | 2,531 | <issue_start>username_0: **I am fetching data from table in foreach loop. Now i am trying to use variable outside for each loop but its not working.**
```
public function get_all_folders()
{
$con = $this->__construct();
$sql="select * from documents";
$execute = mysqli_query($con, $sql);
$rows = mysqli_num_rows($execute);
$data = [];
while ($result = $execute->fetch_assoc()) {
$data[] = $result;
}
return $data;
}
```
above is my function to fetch data on another page.
```
$folder = $obj->get_all_folders();
foreach ($folder as $folder_data)
{
$existing_directory = $folder_data['root_dir'];
}
```
**On another page i am calling my function on the top of my page.Inside foreach loop my variable `$existing_directory` is working.
But if i used this variable outside loop its not showing data.**<issue_comment>username_1: In second page, first of all, include first page as below:
```
include_once 'file1.php'; // whatever your filename
```
Secondly, create object of class (class in first file) in second file as shown below:
```
$obj = new className(); // whatever classname you have provided in file1
```
If still not work, then write below statement before your foreach statement in second page:
```
print_r($folder);exit;
```
If nothing displayed, means there is no data, and therefore foreach will not show anything.
Upvotes: 0 <issue_comment>username_2: You need to define the variable outside loop if you want to access it outside as well.
```
$folder = $obj->get_all_folders();
$existing_directory = null;
foreach ($folder as $folder_data)
{
$existing_directory = $folder_data['root_dir'];
}
```
as per your code you will get last record from array
so you can try below code as well
```
$folder = $obj->get_all_folders();
$last_record = end($folder);
$existing_directory = $last_record['root_dir'];
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Make it like this. In foreach loop you are assigning value to $existing\_directory make it $existing\_directory[] otherwise it will override previous variable.
```
$existing_directory = array();
$folder = $obj->get_all_folders();
foreach ($folder as $folder_data)
{
$existing_directory[] = $folder_data['root_dir'];
}
```
Upvotes: 0 |
2018/03/21 | 523 | 1,907 | <issue_start>username_0: If I run this query:
```
data = table.query(KeyConditionExpression = Key('id').eq('fasfas'),
FilterExpression=Attr(u'Absolute humidity[g/kg].3').eq(1))
```
I get the error:
```
ClientError: An error occurred (ValidationException) when calling the Query operation: Invalid FilterExpression: Syntax error; token: "humidity", near: "Absolute humidity ["
```
However If I run the query using their website it works. How can I make it work using boto3?
P.S. it also doens't work with underscores.<issue_comment>username_1: One of your parameter is not matching the datatype or a required parameter is missing such as range and hash key.
If you are looking for any records to match to your query then you need to scan instead of query.
<https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Programming.Errors.html>
>
> ValidationException Message: Varies, depending upon the specific
> error(s) encountered
>
>
> This error can occur for several reasons, such as a required parameter
> that is missing, a value that is out range, or mismatched data types.
> The error message contains details about the specific part of the
> request that caused the error.
>
>
> OK to retry? No
>
>
>
Hope it helps.
Upvotes: 0 <issue_comment>username_2: >
> An expression attribute name is a placeholder that you use in an expression, as an alternative to an actual attribute name.
>
>
> [...]
>
>
> If an attribute name begins with a number or contains a space, a special character, or a reserved word, then you must use an expression attribute name to replace that attribute's name in the expression.
>
>
> <https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ExpressionAttributeNames.html>
>
>
>
See also <http://boto3.readthedocs.io/en/latest/reference/services/dynamodb.html#DynamoDB.Client.query>
Upvotes: 2 |
2018/03/21 | 801 | 3,465 | <issue_start>username_0: I've been trying to share information between fragments using viewmodel's and livedata's.
But when I change from first fragment to another it seems that my viewmodel is reinitialized, making me lose all my previously stored data.
I get both times my viewmodel the same way in my fragments :
```
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interventionViewModel = ViewModelProviders.of(this).get(InterventionsViewModel.class);
}
```
And this is how I replace my framgents in my activity (I guess the problem must come from the fragments lifecycles but I can't figure out where is the error :/)
```
public void showFragment(Fragment fragment) {
String TAG = fragment.getClass().getSimpleName();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment, TAG);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commitAllowingStateLoss();
}
public void backstackFragment() {
Log.d("Stack count", getSupportFragmentManager().getBackStackEntryCount() + "");
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
finish();
}
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
}
private void removeCurrentFragment() {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getSupportFragmentManager()
.findFragmentById(R.id.fragment_container);
if (currentFrag != null) {
transaction.remove(currentFrag);
}
transaction.commitAllowingStateLoss();
}
```
When I need a fragment I call `backStackFragment()` to remove current fragment then I call `showFragment(MyFragment.newInstance());`
The fragment are the ones generated by AndroidStudio
Thanks for your help,
Cordially,
Matthieu<issue_comment>username_1: Try binding to the activity instead of the current fragment.
```
interventionViewModel = ViewModelProviders.of(activity).get(InterventionsViewModel.class);
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: `call getActivity()` method in fragment which return activity
```
viewModel = ViewModelProviders.of(getActivity()).get(MyViewModel.class);
```
Upvotes: 0 <issue_comment>username_3: I think you should initialize your view model in `onActivityCreated` method instead of `onCreate` like this
```
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
interventionViewModel = ViewModelProviders.of(this).get(InterventionsViewModel.class);
}
```
Its still weird, it keeps reload when fragment change too far (2 or more steps) but it works though, I prefer using `androidx.loader.content.AsyncTaskLoader`, that loader keeps your data very well.
Upvotes: -1 <issue_comment>username_4: Since the [`ViewModelProviders` class is deprecated](https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders) the correct way is to use `ViewModelProvider` and let the ViewModel survive the fragments life-cycle by binding it to the activities life-cycle by using
```
requireActivity()
```
as documented by Google [here](https://developer.android.com/topic/libraries/architecture/viewmodel#sharing):
```
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
```
Upvotes: 2 |
2018/03/21 | 1,176 | 3,425 | <issue_start>username_0: I am using react-twitter-widgets to embed a twitter timeline on my application. Currently, everything renders correctly, however, the timelines height stretches down the entire page. How do I get the widget height so that it only takes up the available view height? [](https://i.stack.imgur.com/KXZJ2.png)
The underlying DOM structure for the main dashboard is:
```
```
With the TwitterCard being in the following format:
```
import React from "react";
import { Timeline } from 'react-twitter-widgets';
export class TwitterCard extends React.Component{
constructor(props){
super();
this.state = {
ticker: props.ticker,
href: props.href
}
}
render() {
return (
)
}
}
```
The main/only css file is as follows:
```
body {
font-size: .875rem;
background-color: #f7f7f7;
}
/*
* Title bar
*/
.title-bar {
padding-right: 15px;
}
/*
* Connection status
*/
#connection-status {
height: 20px;
width: 20px;
border-radius: 50%;
-webkit-border-radius: 50%;
display: block;
}
#connection-status.connected {
background-color: green;
}
#connection-status.disconnected {
background-color: red;
}
/*
* Sidebar
*/
.sidebar {
position: fixed;
top: 0;
bottom: 0;
left: 0;
z-index: 100; /* Behind the navbar */
padding: 0;
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}
.sidebar-sticky {
position: sticky;
top: 48px; /* Height of navbar */
height: calc(100vh - 48px);
padding-top: .5rem;
overflow-x: hidden;
}
.sidebar .nav-link {
font-weight: 500;
color: #333;
}
.sidebar .nav-link{
margin-right: 4px;
color: #999;
}
.sidebar .nav-link.active {
color: #007bff;
}
.sidebar .nav-link:hover,
.sidebar .nav-link.active{
color: inherit;
}
.sidebar-heading {
font-size: .75rem;
text-transform: uppercase;
}
/*
* Navbar
*/
.navbar-brand {
padding-top: .75rem;
padding-bottom: .75rem;
font-size: 1rem;
background-color: rgba(0, 0, 0, .25);
box-shadow: inset -1px 0 0 rgba(0, 0, 0, .25);
}
.navbar .form-control {
padding: .75rem 1rem;
border-width: 0;
border-radius: 0;
}
.form-control-dark {
color: #fff;
background-color: rgba(255, 255, 255, .1);
border-color: rgba(255, 255, 255, .1);
}
.form-control-dark:focus {
border-color: transparent;
box-shadow: 0 0 0 3px rgba(255, 255, 255, .25);
}
.full-screen{
height: 100vh !important;
}
/*
* Utilities
*/
.border-top { border-top: 1px solid #e5e5e5; }
.border-bottom { border-bottom: 1px solid #e5e5e5; }
```<issue_comment>username_1: Please specify the JavaScript for rendering the widget. If it is same as below, you can adjust the height within the attribute.
```
ReactDOM.render((
console.log('Timeline is loaded!')}
/>
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: How I solve this problem:
```
HTMl:
CSS:
media: {
display: "flex",
objectFit: "cover",
width: "auto",
height: "450px",
overflowY: "scroll",
borderRadius: "15px",
},
```
I'm using material UI, so your code will be a little different. I put the component inside a Div with a class named "media". In the css I used The **overflowY** with a **height in px** to solve the problem.
Upvotes: 2 |
2018/03/21 | 238 | 901 | <issue_start>username_0: For upload my application on google playstore. I have generated signedapk so my question is after made few changes in code of the app Shall i generate signed apk again ?<issue_comment>username_1: Please specify the JavaScript for rendering the widget. If it is same as below, you can adjust the height within the attribute.
```
ReactDOM.render((
console.log('Timeline is loaded!')}
/>
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: How I solve this problem:
```
HTMl:
CSS:
media: {
display: "flex",
objectFit: "cover",
width: "auto",
height: "450px",
overflowY: "scroll",
borderRadius: "15px",
},
```
I'm using material UI, so your code will be a little different. I put the component inside a Div with a class named "media". In the css I used The **overflowY** with a **height in px** to solve the problem.
Upvotes: 2 |
2018/03/21 | 743 | 2,108 | <issue_start>username_0: I have tried to change the column order in desktop view and mobile view. In mobile view, `Last Name` should be in 2nd place where in desktop, it should be in last.
```html
First Name
Last Name
Address
Company
```<issue_comment>username_1: >
> Using **Flex** and adding **Media-Query** will solve your problem very easily.
>
>
>
There will be a way to get it done using Bootstrap Grid, i.e using `col-md-push-4` and etc.
But it's very much convenient using flex and adding `order` to inner elements.
Very useful **[Flexbox documentation](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)**.
```css
.outer {
margin: 20px 20px;
display: flex;
flex-wrap: wrap;
}
/*For Mobile*/
@media (min-width: 400px) {
.inner {
width: 100%;
padding: 0px 20px;
}
.fn {
order: 1;
}
.ln {
order: 2;
}
.add {
order: 3;
}
.co {
order: 4;
}
}
/*For Desktop which we are working for*/
@media (min-width: 992px) {
.inner {
width: 50%;
padding: 0px 20px;
}
.fn {
order: 1;
}
.ln {
order: 3;
}
.add {
order: 2;
}
.co {
order: 4;
}
}
/*For Large Screen*/
@media (min-width: 1200px) {
.inner {
width: 25%;
padding: 0px 20px;
}
.fn {
order: 1;
}
.ln {
order: 4;
}
.add {
order: 2;
}
.co {
order: 3;
}
}
```
```html
First Name
Last Name
Address
Company
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: I see that you are using push & pull which will only work for the desktop/tablet viewports.
Best is to develop for the mobile as per your need and then use push & pull for the desktop/tablet to make the re-arrangement.
I have achieved similar ordering using the same approach. It works very well.
**Update:**
Adding the plunker for the same : <http://plnkr.co/edit/b2PNXyyXOsXUx51LweJI?p=preview>
**HTML**
```
1
2
3
4
```
**CSS**
```
.cell {
background: #eee;
margin: 1px;
padding: 20px 0;
text-align: center;
}
```
Upvotes: 1 |
2018/03/21 | 503 | 1,838 | <issue_start>username_0: This question is somewhat hard to summarize. Following code block shows what I want to do.
I have a base class like this:
```
`class Base {
def methA:String="ook"
def methB:Int=1
}
```
Also I have a derived class, where I want each subclass method to call the super class method twice, compare the results and throw an exception on mismatch (this is for a test scenario).
But if I write
```
class Derived extends Base {
private def callDoublyAndCompare[T](fun:()=>T) : T = {
val fst=fun()
val snd=fun()
if(fst!=snd) throw new RuntimeException(s"Mismatch fst=$fst != snd=$snd")
snd
}
override def methB:Int={
callDoublyAndCompare(() => super[Derived].methB)
}
}
```
Then this will not compile. The only way out of this problem sofar has been to extract a method in class *Derived* which only calls the superclass' *methB* and to call this from the lambda call.
Is there a better way?<issue_comment>username_1: I understood you want to call super call method. Hope below is what you want.
You can call that as below with the key word `super` only
`(new Derived).methB` . This will call super call method in `callDoublyAndCompare` twice as per your code .
```
class Derived extends Base {
private def callDoublyAndCompare[T](fun:()=>T) : T = {
val fst=fun()
val snd=fun()
if(fst!=snd) throw new RuntimeException(s"Mismatch fst=$fst != snd=$snd")
snd
}
override def methB:Int={
callDoublyAndCompare(() => super.methB) //kept only super
}
}
```
Upvotes: 1 <issue_comment>username_2: The original example was not fully complete insofar as the Derived class was defined as inner class of another scala class.
After I moved out this inner class to the top level, the example from Praveen above suddenly worked.
Upvotes: 0 |
2018/03/21 | 1,119 | 3,906 | <issue_start>username_0: My function first calculates all possible anagrams of the given word. Then, for each of these anagrams, it checks if they are valid words, but checking if they equal to any of the words in the wordlist.txt file. The file is a giant file with a bunch of words line by line. So I decided to just read each line and check if each anagram is there. However, it comes up blank. Here is my code:
```
def perm1(lst):
if len(lst) == 0:
return []
elif len(lst) == 1:
return [lst]
else:
l = []
for i in range(len(lst)):
x = lst[i]
xs = lst[:i] + lst[i+1:]
for p in perm1(xs):
l.append([x] + p)
return l
def jumbo_solve(string):
'''jumbo_solve(string) -> list
returns list of valid words that are anagrams of string'''
passer = list(string)
allAnagrams = []
validWords = []
for x in perm1(passer):
allAnagrams.append((''.join(x)))
for x in allAnagrams:
if x in open("C:\\Users\\Chris\\Python\\wordlist.txt"):
validWords.append(x)
return(validWords)
print(jumbo_solve("rarom"))
```
If have put in many print statements to debug, and the passed in list, "allAnagrams", is fully functional. For example, with the input "rarom, one valid anagram is the word "armor", which is contained in the wordlist.txt file. However, when I run it, it does not detect if for some reason. Thanks again, I'm still a little new to Python so all the help is appreciated, thanks!<issue_comment>username_1: You missed a tiny but important aspect of:
```
word in open("C:\\Users\\username_2\\Python\\wordlist.txt")
```
This will search the file line by line, as if `open(...).readlines()` was used, and attempt to match the entire line, **with** `'\n'` **in the end**. Really, anything that demands iterating over `open(...)` works like `readlines()`.
You would need
`x+'\n' in open("C:\\Users\\username_2\\Python\\wordlist.txt")`
if the file is a list of words on separate lines to make this work to fix what you have, but it's inefficient to do this on every function call. Better to do once:
```
wordlist = open("C:\\Users\\username_2\\Python\\wordlist.txt").read().split('\n')
```
this will create a list of words if the file is a `'\n'` separated word list. Note you can use
```
`readlines()`
```
instead of `read().split('\n')`, but this will keep the `\n` on every word, like you have, and you would need to include that in your search as I show above. Now you can use the list as a global variable or as a function argument.
```
if x in wordlist: stuff
```
Note Graphier raised an important suggestion in the comments. A set:
```
wordlist = set(open("C:\\Users\\username_2\\Python\\wordlist.txt").read().split('\n'))
```
Is better suited for a word lookup than a list, since it's O(word length).
Upvotes: 3 [selected_answer]<issue_comment>username_2: You have used the following code in the wrong way:
```
if x in open("C:\\Users\\username_2\\Python\\wordlist.txt"):
```
Instead, try the following code, it should solve your problem:
```
with open("words.txt", "r") as file:
lines = file.read().splitlines()
for line in lines:
# do something here
```
Upvotes: 0 <issue_comment>username_3: So, putting all advice together, your code could be as simple as:
```
from itertools import permutations
def get_valid_words(file_name):
with open(file_name) as f:
return set(line.strip() for line in f)
def jumbo_solve(s, valid_words=None):
"""jumbo_solve(s: str) -> list
returns list of valid words that are anagrams of `s`"""
if valid_words is None:
valid_words = get_valid_words("C:\\Users\\username_2\\Python\\wordlist.txt")
return [word for word in permutations(s) if word in valid_words]
if __name__ == "__main__":
print(jumbo_solve("rarom"))
```
Upvotes: 0 |
2018/03/21 | 530 | 1,731 | <issue_start>username_0: My requirement is something like this.
I have two radio buttons namely **Live Paper** and **Normal Paper**
If user select Live Paper another two html `input elements`(`datatime-local`,`time`) must be shown.
If the user selected the Normal Paper these two additional input elements should be hide.
How do I achieve this through vueJS.
This is my code.
```js
Live Papaer
Live on Time
Normal Paper
```<issue_comment>username_1: Have a look to these documentations :
* [VueJS Forms : Basics](https://v2.vuejs.org/v2/guide/forms.html#Basic-Usage)
* [Vue JS Forms : Radio buttons](https://v2.vuejs.org/v2/guide/forms.html#Radio)
* [Vue JS Conditional Rendering](https://v2.vuejs.org/v2/guide/conditional.html)
Also, from the community, you can find a lot of resources to understand View Binding and Forms in VueJS :
* [Understand what's behind v-model](https://alligator.io/vuejs/add-v-model-support/)
* [2-Way Binding in Vue with V-Model - Vue.js 2.0 Fundamentals](https://www.youtube.com/watch?v=nEdsu6heW9o)
Upvotes: 2 <issue_comment>username_2: Just initialize a property named `selected` in your data option
```
new Vue({
el:"#app",
data(){
return{
selected: 'live'
}
}
})
```
Bind this `selected` property to both the radio inputs. See that the `value` attribute of radio inputs is set to `live` and `normal` respectively
Set up `v-if` on the div you conditionally want to render. The `v-if` is only true when `selected === 'live'`
```
Live Papaer
Live on Time
Normal Paper
```
Here is the [fiddle](https://jsfiddle.net/g4tafyhk/3/)
Reference: [radio inputs](https://v2.vuejs.org/v2/guide/forms.html#Radio)
Upvotes: 4 [selected_answer] |
2018/03/21 | 777 | 3,244 | <issue_start>username_0: i using a specific date library(<https://github.com/mohamad-amin/PersianMaterialDateTimePicker>)
now i want using it in a button in Recycler View.
now my problem is I have to define two options in library codes :
1 - I should refer to the activity.
2 - i need to use getSupport FragmentManager().
but this page has been extends with Recycler View.Adapter and I do not know how to call these two options on this page.
RecyclerViewAdapter page :
```
PersianCalendar persianCalendar = new PersianCalendar();
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance( StudentList.this ,
persianCalendar.getPersianYear() ,
persianCalendar.getPersianMonth() ,
persianCalendar.getPersianDay());
datePickerDialog.show( getSupportFragmentManager() , "datePickerDialog" );
```
In these pictures you can easily understand me :
[enter image description here](https://i.stack.imgur.com/JbQGX.jpg)
[enter image description here](https://i.stack.imgur.com/RJkFQ.jpg)
[enter image description here](https://i.stack.imgur.com/g4I7V.jpg)<issue_comment>username_1: You activity must implements `TimePickerDialog.OnTimeSetListener` and implement the abstact methode `onTimeSet`:
```
public class StudentList extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {
@Override
public void onTimeSet(TimePickerDialog view, int hourOfDay, int minute, int second) {
}
}
```
and inside `onClick`
```
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance((((StudentList)view.getContext()), persianCalendar.getPersianYear(),
persianCalendar.getPersianMonth(),
persianCalendar.getPersianDay());
```
OR :
```
DatePickerDialog datePickerDialog =DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
}
}, persianCalendar.getPersianYear(),
persianCalendar.getPersianMonth(),
persianCalendar.getPersianDay());
```
Upvotes: 2 [selected_answer]<issue_comment>username_2: You could try passing the Activity's context when creating an instance of the adapter:
```
//Code in your Activity
MyAdapter myAdapter = new MyAdapter(this, ...);
```
Your adapter:
```
private Context context;
public MyAdapter(Context context, ...){
this.context = context;
//Rest of the constructor...
}
```
By doing that, you could just add do this:
```
datePickerDialog.show(context.getSupportFragmentManager(), "datePickerDialog");
```
Upvotes: 0 <issue_comment>username_3: You just need an activity context passed in your constructor. Be sure to call new Adapter(this,...) from activities and new Adapter(getActivity(),...) from fragments.
```
private Context context;
@Override
public void onClick(View v) {
FragmentManager manager = ((Activity) context).getFragmentManager();
FragmentManager manager = ((AppCompatActivity)context).getSupportFragmentManager();
}
```
try this
Upvotes: 0 |
2018/03/21 | 455 | 1,435 | <issue_start>username_0: Here is the code of Flutter Map
```
void showFlutterMap(){
return new FlutterMap(
options: new MapOptions(
center: new LatLng(51.5, -0.09),
zoom: 13.0,
),
layers: [
new TileLayerOptions(
urlTemplate: "https://api.tiles.mapbox.com/v4/"
"{id}/{z}/{x}/{y}@2x.png?access_token={accessToken}",
additionalOptions: {
'accessToken': '',
'id': 'mapbox.streets',
},
),
new MarkerLayerOptions(
markers: [
new Marker(
width: 80.0,
height: 80.0,
point: new LatLng(51.5, -0.09),
builder: (ctx) =>
new Container(
child: new FlutterLogo(),
),
),
],
),
],
);
}
```<issue_comment>username_1: I know it's been a while, but in order to change the center of map in flutter\_map you just need to change the values of center property of MapOptions. It's a **LatLng** object which accepts Latitude and Longitude.
```
options: new MapOptions(
center: new LatLng(51.5, -0.09),
zoom: 13.0,
),
```
Upvotes: 1 <issue_comment>username_2: You can add a MapController (defined in your app) in your FlutterMap widget
```
MapController _mapctl = MapController();
...
void showFlutterMap(){
return new FlutterMap(
mapController: _mapctl,
...
);
}
```
Then you have to move into the new location
```
latlng = LatLng(coordinates_you_want);
double zoom = 4.0; //the zoom you want
_mapctl.move(latlng,zoom);
```
Upvotes: 2 |
2018/03/21 | 590 | 1,834 | <issue_start>username_0: I got this Ajax code on Js/Jq block (/buscador/menuLateral/menu-libros.php):
```
$.ajax({
url: '= get_stylesheet_directory_uri(); ?' +
'/buscador/buscador-functions.php',
type: 'POST',
data: {
sendCheckedVal: 'yes',
tipo: 'editorial',
valor: valor_recogido,
archivo: this_file_id.toString()
},
success: function(data) {
alert('Checked value !');
}
});
```
Values on this file exists and got some value, I tried seeing it with a GET on a Stringify.
And this, must be getted in a file like this (*/buscador/buscador-functions.php)* :
```
php
if (ISSET($_POST['sendCheckedVal'])){
echo 'hi, u reached here' ;
}
?
```
The values doesn't passes from js code file to next.
I get this error on console:
>
> POST
> [WP-URL-HIDDEN-ON-PURPOSE]/themes/ChildrenNewspaper/buscador/buscador-functions.php
> 500 (Internal Server Error)
>
>
>
On right side of the line-error :
>
> jquery.min.js:2
>
>
>
Someone knows how to repair this on ajax working on a wordpress theme.Thanks<issue_comment>username_1: I know it's been a while, but in order to change the center of map in flutter\_map you just need to change the values of center property of MapOptions. It's a **LatLng** object which accepts Latitude and Longitude.
```
options: new MapOptions(
center: new LatLng(51.5, -0.09),
zoom: 13.0,
),
```
Upvotes: 1 <issue_comment>username_2: You can add a MapController (defined in your app) in your FlutterMap widget
```
MapController _mapctl = MapController();
...
void showFlutterMap(){
return new FlutterMap(
mapController: _mapctl,
...
);
}
```
Then you have to move into the new location
```
latlng = LatLng(coordinates_you_want);
double zoom = 4.0; //the zoom you want
_mapctl.move(latlng,zoom);
```
Upvotes: 2 |
2018/03/21 | 343 | 1,205 | <issue_start>username_0: As you know Apple uses Radeon on iMac's. I have been trying to find out a solution to speed up the training process and no luck so far!
So can you pros direct me to the right route on this? I mean can i already use GPU on my iMac without adding any equipments or shall i go and buy some external NVIDIA and Thunderbolt box?
I am planning to use Tensorflowi keras aand sklearn on my iMac macOS High Sierra.<issue_comment>username_1: I know it's been a while, but in order to change the center of map in flutter\_map you just need to change the values of center property of MapOptions. It's a **LatLng** object which accepts Latitude and Longitude.
```
options: new MapOptions(
center: new LatLng(51.5, -0.09),
zoom: 13.0,
),
```
Upvotes: 1 <issue_comment>username_2: You can add a MapController (defined in your app) in your FlutterMap widget
```
MapController _mapctl = MapController();
...
void showFlutterMap(){
return new FlutterMap(
mapController: _mapctl,
...
);
}
```
Then you have to move into the new location
```
latlng = LatLng(coordinates_you_want);
double zoom = 4.0; //the zoom you want
_mapctl.move(latlng,zoom);
```
Upvotes: 2 |
2018/03/21 | 313 | 1,063 | <issue_start>username_0: I would like to know if there is a difference in performance between :
```
while(true)
{
.....
}
```
And :
```
bool x;
x = true;
while(x)
{
.....
}
```
I need the best performance and a small difference between the two is important to my application.
Info from comment by OP:
The `while(true)` will at some point also be left, that is however rare.<issue_comment>username_1: First of all...
If you want to make an infinite loop you (always) use:
```
while(true)
{
...
}
```
There would be absolutely no reason why defining a variable before that loop should speed up your "application". So there is no reason to use:
```
bool x = true;
while(x)
{
...
}
```
Upvotes: 1 <issue_comment>username_2: If you need a truly endless loop, then why use a condition?
If you need a loop which can be left, then your `while(true){...}` will contain an `if(!x)` which your `while(x)` does not contain.
Any potential optimisation benefit of `while(true)` over `while(x)` will be lost at that point.
Upvotes: 3 [selected_answer] |
2018/03/21 | 289 | 919 | <issue_start>username_0: I have below code in bash:
```
#/!bin/bash
USERS=tom1,tom2,tom3
```
and I want to drop all users from my variable "USERS" via sqlplus
```
#/!bin/bash
USERS=tom1,tom2,tom3
sqlplus -s system/*** <
```
pls help<issue_comment>username_1: First of all...
If you want to make an infinite loop you (always) use:
```
while(true)
{
...
}
```
There would be absolutely no reason why defining a variable before that loop should speed up your "application". So there is no reason to use:
```
bool x = true;
while(x)
{
...
}
```
Upvotes: 1 <issue_comment>username_2: If you need a truly endless loop, then why use a condition?
If you need a loop which can be left, then your `while(true){...}` will contain an `if(!x)` which your `while(x)` does not contain.
Any potential optimisation benefit of `while(true)` over `while(x)` will be lost at that point.
Upvotes: 3 [selected_answer] |
2018/03/21 | 421 | 1,287 | <issue_start>username_0: Based on the answer by Matt for the question asked [here](https://stackoverflow.com/questions/4837673/how-to-execute-mongo-commands-through-shell-scripts):
I tried the below script
```
use sample
db.testCollection.insert({"result":1})
```
However when I run as suggested, get an error as below and the record gets inserted in a collection of the default db and not in the 'sample' db as expected.
```
[tmp]# mongo < output.js
connecting to: mongodb://127.0.0.1:27017
2018-03-21T14:54:52.713+0530 E QUERY [thread1] SyntaxError: unterminated string literal @(shellhelp2):1:21
WriteResult({ "nInserted" : 1 })
bye
```
Kindly request for help.<issue_comment>username_1: You need to specify the db name as shown below.
```
mongo your-db-name < output.js
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: Your script and command are correct.
On Unix, you will get this error if your script has Dos/Windows end of lines (CRLF) instead of Unix end of lines (LF).
To convert your end of lines :
```
dos2unix output.js
```
or: [How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?](https://stackoverflow.com/questions/2613800/how-to-convert-dos-windows-newline-crlf-to-unix-newline-lf-in-a-bash-script)
Upvotes: 3 |
2018/03/21 | 1,246 | 4,815 | <issue_start>username_0: Goal:
Use Google Sheet API by using the syntax code "spreadsheets.values.update" in order to update the current cell.
Problem:
I have used the code that is provded by Google Sheet's tutorial (<https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update>) and it doesn't work.
I retrieve a error message saying:
```
"An unhandled exception of type 'Google.GoogleApiException' occurred in mscorlib.dll
Additional information: Google.Apis.Requests.RequestError
Request had insufficient authentication scopes. [403]
Errors [
Message[Request had insufficient authentication scopes.] Location[ - ] Reason[forbidden] Domain[global]
]"
```
Info:
\*I was enable to use Oath 2.0 authenfication in relation to syntax code "spreadsheets.values.get" (<https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get>) and it works perfectly.
\*The same code of Oath 2.0 that is used in "spreadsheets.values.get" works well.
\*It is the same authenfication when I use for "get" and "update". It works for "get" but not for "update".
Thank you!
[](https://i.stack.imgur.com/ZW5EX.png)
```
private void btn_test6_Click(object sender, RoutedEventArgs e)
{
string[] Scopes = { SheetsService.Scope.Spreadsheets};
string ApplicationName = "SheetUpdate"; //update this!
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
SheetsService sheetsService = new SheetsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Google-SheetsSample/0.1",
});
// The ID of the spreadsheet to update.
string spreadsheetId = ""; // TODO: Update placeholder value.
// The A1 notation of the values to update.
string range = "datadata!A1:A6"; // TODO: Update placeholder value.
// How the input data should be interpreted.
SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum valueInputOption = (SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum)0; // TODO: Update placeholder value.
IList my = new List();
my.Add("a");
my.Add("a");
my.Add("a");
my.Add("a");
my.Add("a");
my.Add("a");
IList> my2 = new List>();
my2.Add(my);
// TODO: Assign values to desired properties of `requestBody`. All existing
// properties will be replaced:
Google.Apis.Sheets.v4.Data.ValueRange requestBody = new Google.Apis.Sheets.v4.Data.ValueRange();
requestBody.Values = my2;
SpreadsheetsResource.ValuesResource.UpdateRequest request = sheetsService.Spreadsheets.Values.Update(requestBody, spreadsheetId, range);
request.ValueInputOption = valueInputOption;
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
Google.Apis.Sheets.v4.Data.UpdateValuesResponse response = request.Execute();
// Data.UpdateValuesResponse response = await request.ExecuteAsync();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
```<issue_comment>username_1: Remove new FileDataStore
```
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None //,
//new FileDataStore(credPath, true)
).Result;
```
Upvotes: 0 <issue_comment>username_2: Update requires following Authorization scopes
`https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets`
see [here](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update)
Try modifying scopes in array and update application/project's rights in google consoles' [OAuth consent screen](https://console.developers.google.com/apis/credentials/consent) and adding these scopes there too.
Upvotes: 0 <issue_comment>username_3: replace this line:
```
static string[] Scopes = { SheetsService.Scope.Spreadsheets.ReadOnly };
```
with this:
```
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
```
and if you did not pass, delete (token.json) folder and try again
Upvotes: 1 |
2018/03/21 | 775 | 3,003 | <issue_start>username_0: i try to call modal instance from main page controller but i get this error
TypeError: Cannot read property 'open' of undefined
are anyone help me to solve the problem
my main page controller is
```
app.controller('unitMasterCntlr', ['$scope', 'toaster', '$state',
'$http', 'emodal', '$timeout', '$compile','$filter','$modal','$rootScope',
function ($scope, toaster, $state, $http, emodal, $timeout, $compile,
DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $interval,$filter,$modal,$rootScope) {
```
and module is
```
angular.module('app', ['datatables','ui.select2','easyModalService',
'ngAnimate',
'ngCookies',
'ngResource',
'ngSanitize',
'ngTouch',
'ngStorage',
'ui.router',
'ui.bootstrap',
'ui.utils',
'ui.load',
'ui.jq',
'oc.lazyLoad',
'pascalprecht.translate',
'ui.mask']);
```
and modal calling code as
```
var modalInstance = $modal.open({
templateUrl: 'tpl/UnitMasterModal.jsp',
controller: 'modalcntrl',
size: 'lg',
resolve: {
items: function () {
return $scope.items;
}
}
});
```
modal controller is
```
app.controller('modalcntrl', ['$scope', '$modalInstance', 'items', function ($scope, $modalInstance, items) {
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}]);
```
where item is an array having some response value that i want to display on modal
iam new to angularjs... plz help me to solve this<issue_comment>username_1: Remove new FileDataStore
```
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None //,
//new FileDataStore(credPath, true)
).Result;
```
Upvotes: 0 <issue_comment>username_2: Update requires following Authorization scopes
`https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.file
https://www.googleapis.com/auth/spreadsheets`
see [here](https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update)
Try modifying scopes in array and update application/project's rights in google consoles' [OAuth consent screen](https://console.developers.google.com/apis/credentials/consent) and adding these scopes there too.
Upvotes: 0 <issue_comment>username_3: replace this line:
```
static string[] Scopes = { SheetsService.Scope.Spreadsheets.ReadOnly };
```
with this:
```
static string[] Scopes = { SheetsService.Scope.Spreadsheets };
```
and if you did not pass, delete (token.json) folder and try again
Upvotes: 1 |
2018/03/21 | 1,143 | 3,858 | <issue_start>username_0: I need events calendar component to my angular 5 application,
Look like 'Google Calendar' with an option to Hebrew dates and Jewish events.
Does anyone know about such a Calendar?<issue_comment>username_1: I am in a similar search...
The only suitable component that I have found so far is [DatePicker from NG Bootstrap](https://ng-bootstrap.github.io/#/components/datepicker/calendars#hebrew)
[Hebcal JS](https://github.com/hebcal/hebcal-js) package may be useful as well
Upvotes: 1 <issue_comment>username_2: I implemented [angular calendar](https://angular-calendar.com/#/kitchen-sink).
1. added "he" to my locale, [like that](https://github.com/mattlewis92/angular-calendar/issues/431#issuecomment-487901271).
2. set my local to `"he"` for getting the right RTL support. and Hebrew texts for the whole calendar.
3. used [hebcal api](https://www.hebcal.com/home/40/displaying-todays-hebrew-date-on-your-website) to get the dates in Hebrew format for each day.
4. used [this guide](https://angular-calendar.com/#/custom-templates) to edit my components and add the Hebrew date to each day
Upvotes: 0 <issue_comment>username_3: For anyone who struggling with this issue...I looked for something similar-
I had a calendar from [fullCalendar.io](https://fullcalendar.io/), and I couldn't choose another library, wasn't important to me the jewish events, more looked for the hebrew dates next to the gregorian in the day's header.
Eventually what I did is the following:
I created two functions: `getHebrewDates` and `setHebrewDates` (they are not getter/setters...)
```js
getHebrewDates(month: number, year:number){
const currMonth = month.toString().padStart(2,"0");
//'padStart' is for getting "02" instead of "2"
const nextMonth = (month + 1).toString().padStart(2,"0");
const start = `${year}-${currMonth}-01`;
const end = `${year}-${nextMonth}-01`;
const url = `https://www.hebcal.com/converter?cfg=json&start=${start}&end=${end}&g2h=1`;
fetch(url, {method: 'GET'})
.then(response => response.json())
.then(data => {
this.setHebewDates(data);
}).catch(err => {
console.log(err);
});
}
```
as you can see - I use an api url that provided by `Hebcal`, this api gives me the hebrew dates for each day in the range I supplied via the `start` and `end` parameters. see
[Hebcal Api for converting dates h2g and g2h](https://www.hebcal.com/home/219/hebrew-date-converter-rest-api)
next-
```js
setHebewDates(dates:any[]){
const dayDivs = document.getElementsByClassName("fc-daygrid-day");
for(let i = 0; i < dayDivs.length; i++){
const dayDiv = dayDivs.item(i);
const dayHeader = dayDiv.firstElementChild.firstElementChild;
const newElement = document.createElement("a");//or whatevet elemtn you want
newElement.classList.add("hebrewDate");
//'dayDiv' element has an attribute called 'dataset' that contains
//an object with the current date
let date = dates["hdates"][dayDiv["dataset"]["date"]]?.heDateParts.d;
if(date != undefined){
newElement.innerText = date;
dayHeader.append(newElement);
}
}
}
```
Because I don't know any method of fullCalendar that pushes elements into the date-header - I had to use plain js to change the DOM.
Now add the following css styles:
```css
::ng-deep .hebrewDate{
font-size: 16px;
padding:4px;
}
::ng-deep .fc-daygrid-day-top{
justify-content: space-between;
/*so the hebrew date will stand to the right and gregorian to the left*/
}
```
and last step - call the `getHebrewDates` from the prev and next callbacks.
retreive the current viewed monthe via `calendar.getDate().getMonth()/getFullYear()
**Note:** You'll get the previous month and not the current (if you're looking at April - you'll get "3") so just add the month `+1`
Upvotes: 0 |
2018/03/21 | 931 | 3,630 | <issue_start>username_0: I am trying to write EXIF data to the image but **CGImageDestinationFinalize** crashes:
```
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
let jpeg = UIImageJPEGRepresentation(image, 1.0)
var source: CGImageSource? = nil
source = CGImageSourceCreateWithData((jpeg as CFData?)!, nil)
let metadata = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil) as? [AnyHashable: Any]
var metadataAsMutable = metadata
var EXIFDictionary = (metadataAsMutable?[(kCGImagePropertyExifDictionary as String)]) as? [AnyHashable: Any]
var GPSDictionary = (metadataAsMutable?[(kCGImagePropertyGPSDictionary as String)]) as? [AnyHashable: Any]
GPSDictionary![(kCGImagePropertyGPSLatitude as String)] = 30.21313
GPSDictionary![(kCGImagePropertyGPSLongitude as String)] = 76.22346
EXIFDictionary![(kCGImagePropertyExifUserComment as String)] = "Hello Image"
let UTI: CFString = CGImageSourceGetType(source!)!
let dest_data = NSMutableData()
let destination: CGImageDestination = CGImageDestinationCreateWithData(dest_data as CFMutableData, UTI, 1, nil)!
CGImageDestinationAddImageFromSource(destination, source!, 0, (metadataAsMutable as CFDictionary?))
CGImageDestinationFinalize(destination)
```<issue_comment>username_1: This could be from your destination definition.
This worked for me
```
(...)
let source = CGImageSourceCreateWithData(jpgData as CFData, nil)
let finalData = NSMutableData()
let destination = getDestination(finalData:finalData, source:source!)
(...)
// Note that :
// NSMutableData type variable will be cast to CFMutableData
//
fileprivate func getDestination(finalData:CFMutableData, source:CGImageSource)->CGImageDestination?{
guard let destination = CGImageDestinationCreateWithData(finalData,
CGImageSourceGetType(source)!,
1,
nil)else{return nil}
return destination
}
```
Upvotes: 1 <issue_comment>username_2: Please check this below answer.
you got error due to nil value on **EXIFDictionary** and **GPSDictionary**
```
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
let jpeg = UIImageJPEGRepresentation(image, 1.0)
var source: CGImageSource? = nil
source = CGImageSourceCreateWithData((jpeg as CFData?)!, nil)
let metadata = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil) as? [AnyHashable: Any]
var metadataAsMutable = metadata
var EXIFDictionary = (metadataAsMutable?[(kCGImagePropertyExifDictionary as String)]) as? [AnyHashable: Any]
var GPSDictionary = (metadataAsMutable?[(kCGImagePropertyGPSDictionary as String)]) as? [AnyHashable: Any]
if !(EXIFDictionary != nil) {
EXIFDictionary = [AnyHashable: Any]()
}
if !(GPSDictionary != nil) {
GPSDictionary = [AnyHashable: Any]()
}
GPSDictionary![(kCGImagePropertyGPSLatitude as String)] = 30.21313
GPSDictionary![(kCGImagePropertyGPSLongitude as String)] = 76.22346
EXIFDictionary![(kCGImagePropertyExifUserComment as String)] = "Hello Image"
let UTI: CFString = CGImageSourceGetType(source!)!
let dest_data = NSMutableData()
let destination: CGImageDestination = CGImageDestinationCreateWithData(dest_data as CFMutableData, UTI, 1, nil)!
CGImageDestinationAddImageFromSource(destination, source!, 0, (metadataAsMutable as CFDictionary?))
CGImageDestinationFinalize(destination)
```
Upvotes: 5 [selected_answer] |
2018/03/21 | 1,464 | 6,276 | <issue_start>username_0: I successfully added my image to my server with the help of this <https://androidjson.com/android-upload-image-server-using-php-mysql/>. But it only helps in uploading the image to the server. I have to display the image I have uploaded to the image view. I tried Picasso but it's not working.
```
Picasso.with(context).load(ImagePath).into(image);
```
I don't know what should be written in the load method. Because I was told to write the path and name of the image but none is working.
I added it in PostExecute method.But it is giving me error of
```
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.prajakta.truckloaderowner, PID: 32651
java.lang.OutOfMemoryError: Failed to allocate a 4192268 byte allocation with 3077040 free bytes and 2MB until OOM
at java.io.ByteArrayOutputStream.toByteArray(ByteArrayOutputStream.java:122)
at com.prajakta.truckloaderowner.FragProfile.ImageUploadToServerFunction(FragProfile.java:137)
at com.prajakta.truckloaderowner.FragProfile$2.onClick(FragProfile.java:93)
at android.view.View.performClick(View.java:5721)
at android.widget.TextView.performClick(TextView.java:10949)
at android.view.View$PerformClick.run(View.java:22624)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7410)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
```
This my PHP file
```
php
$username ='root';
$password ='';
$hostname ='localhost';
$database ='truck_loader';
$con=mysqli_connect($hostname,$username,$password,$database) or die("unable
to connect");
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$DefaultId = 0;
$ImageData = $_POST['image_path'];
$ImageName = $_POST['image_name'];
$GetOldIdSQL ="SELECT id FROM users ORDER BY id ASC";
$Query = mysqli_query($con,$GetOldIdSQL);
while($row = mysqli_fetch_array($Query))
{
$DefaultId = $row['id'];
}
$ImagePath = "images/$DefaultId.png";
$ServerURL = "$ImagePath";
$InsertSQL = "insert into users (image_path,image_name) values
('$ServerURL','$ImageName')" ;
if(mysqli_query($con, $InsertSQL))
{
file_put_contents($ImagePath,base64_decode($ImageData));
echo "Your Image Has Been Uploaded.";
}
mysqli_close($con);
}
else
{
echo "Not Uploaded";
}
?
```
Edit:I am designing a profile page for an app so I need the photo to remain there until the changes are done. But according to the code, it only stays there until back button is pressed.After back press image is gone.<issue_comment>username_1: This could be from your destination definition.
This worked for me
```
(...)
let source = CGImageSourceCreateWithData(jpgData as CFData, nil)
let finalData = NSMutableData()
let destination = getDestination(finalData:finalData, source:source!)
(...)
// Note that :
// NSMutableData type variable will be cast to CFMutableData
//
fileprivate func getDestination(finalData:CFMutableData, source:CGImageSource)->CGImageDestination?{
guard let destination = CGImageDestinationCreateWithData(finalData,
CGImageSourceGetType(source)!,
1,
nil)else{return nil}
return destination
}
```
Upvotes: 1 <issue_comment>username_2: Please check this below answer.
you got error due to nil value on **EXIFDictionary** and **GPSDictionary**
```
var image = info[UIImagePickerControllerOriginalImage] as! UIImage
let jpeg = UIImageJPEGRepresentation(image, 1.0)
var source: CGImageSource? = nil
source = CGImageSourceCreateWithData((jpeg as CFData?)!, nil)
let metadata = CGImageSourceCopyPropertiesAtIndex(source!, 0, nil) as? [AnyHashable: Any]
var metadataAsMutable = metadata
var EXIFDictionary = (metadataAsMutable?[(kCGImagePropertyExifDictionary as String)]) as? [AnyHashable: Any]
var GPSDictionary = (metadataAsMutable?[(kCGImagePropertyGPSDictionary as String)]) as? [AnyHashable: Any]
if !(EXIFDictionary != nil) {
EXIFDictionary = [AnyHashable: Any]()
}
if !(GPSDictionary != nil) {
GPSDictionary = [AnyHashable: Any]()
}
GPSDictionary![(kCGImagePropertyGPSLatitude as String)] = 30.21313
GPSDictionary![(kCGImagePropertyGPSLongitude as String)] = 76.22346
EXIFDictionary![(kCGImagePropertyExifUserComment as String)] = "Hello Image"
let UTI: CFString = CGImageSourceGetType(source!)!
let dest_data = NSMutableData()
let destination: CGImageDestination = CGImageDestinationCreateWithData(dest_data as CFMutableData, UTI, 1, nil)!
CGImageDestinationAddImageFromSource(destination, source!, 0, (metadataAsMutable as CFDictionary?))
CGImageDestinationFinalize(destination)
```
Upvotes: 5 [selected_answer] |
2018/03/21 | 761 | 2,640 | <issue_start>username_0: I have a Selenium + Python + Chromedriver script which should log in to a website and click on a download button which will download a CSV file.
Inspect details of download button is:
```
CSV
```
and XPath is:
```
//*[@id="csv-button"]
```
but it says XPath element not found when I run the script. Please find the code below:
```
click_button = driver.find_element_by_xpath('//*[@id="csv-button"]')
click_button.click()
```<issue_comment>username_1: Incase of a unique *xpath* identifying the *WebElement* if you are seeing **element not found** exception you need to induce [WebDriverWait](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.wait.html#module-selenium.webdriver.support.wait) in conjunction with [`expected_conditions`](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#module-selenium.webdriver.support.expected_conditions) clause set to [`element_to_be_clickable`](https://seleniumhq.github.io/selenium/docs/api/py/webdriver_support/selenium.webdriver.support.expected_conditions.html#selenium.webdriver.support.expected_conditions.element_to_be_clickable) as follows :
```
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# other code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='csv-button']"))).click()
```
To be more granular you can use :
```
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# other code
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='block tiny-margin-top' and @id='csv-button']"))).click()
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: The problem seems that your xpath is not quite correct. You are using single quotes where double are required and visa versa.
Try:
```
click_button = driver.find_element_by_xpath("//*[@id='csv-button']")
click_button.click()
```
You can even try:
```
//button[@id='csv-button']
```
This will make the xpath search faster as it will look only for the button tags.
Upvotes: 0 <issue_comment>username_3: single quotes should come in the double quotes. Please see below
```
click_button = driver.find_element_by_xpath("//*[@id='csv-button']")
click_button.click()
```
see the change here:
```
('//*[@id="csv-button"]') ---> ("//*[@id='csv-button']")
```
Upvotes: 0 |
2018/03/21 | 933 | 3,334 | <issue_start>username_0: I'm trying to send multiple input values via AJAX to my PHP script. It's working fine when I use `getElementById`. However I have the option to add a child. It iterates the input fields, then I get values only from the first child. I tried to use `getElementsByClassName` but it gives values as `undefined`. This is my code:
```html
Name of child
Date of birth
[Add Child](#)
[Next Step](#)
```
```js
//Iterate child function
jQuery(function($) {
$("#addChild").click(function() {
$(".name-field:first").clone().find("input").val("").end()
.removeAttr("id")
.appendTo("#additionalselects")
.append($(''));
});
$("body").on('click', ".delete", function() {
$(this).closest(".name-field").remove();
});
});
//Sending values function
function btnSubmit(step) {
//Set Var with Name
//Set Var with DoB
if (step == 'step1') {
//values using ID
var Name = document.getElementById("firstname").value;
var DoB = document.getElementById("thedate").value;
//Values using classname
var Name = document.getElementsByClassName("firstname").value;
var DoB = document.getElementsByClassName("date").value;
//Create a Variable catVar Having the Var Name and Var DoB Concatinated with a --
var stepVar = Name + "--" + DoB;
$(".thevoornaam, .date").each(function() {
alert();
});
} else {
}
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", "validations/btnSubmit.php?q=" + step + "&q2=" + stepVar, true);
xmlhttp.send();
}
```
I hope you guys understand what I'm trying to achieve with this, if I did't explain it correctly.
Thanks in advance.<issue_comment>username_1: using jQuery you can do it in this way.
```
var firstname = [];
$("#name-field .firstname").each(function(){
firstname.push($(this).val());
});
```
In firstname you will all the values.
Update
------
Here is a working pen.
<https://codepen.io/smitraval27/pen/dmvwVB>
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
document.getElementsByClassName("firstname")
```
returns an array... so the following will give you the elements value with index i. To get all the values you will need to do a ForEach.
```
document.getElementsByClassName("firstname")[0].value
```
Since you're using JQuery elsewhere, why not use...
```
$('.firstname')[0].val();
```
Upvotes: 0 <issue_comment>username_3: The most ideal way to do this is :
* add a form wrapper to your fields (`id="ajaxForm"`)
* to have a `name` to all your form
fields and use the below code to generate the `data` to be passed to
your AJAX call
`$("#ajaxForm").serialize()`
The return value of `$.serialize()` can be directly used as the `data` for the ajax call
```js
$("#ajaxForm").on("submit", function () {
var ajaxData = $("#ajaxForm").serialize();
$("#ajaxData").text(ajaxData);
$.ajax({
url:"",
type: "get",
data : ajaxData,
success: function (resp) {}
});
console.log(ajaxData);
});
```
```html
```
Upvotes: 0 |
2018/03/21 | 658 | 2,227 | <issue_start>username_0: While bootstrap a node on hosted chef server i am getting following error
```
$ knife bootstrap xxx.xxx.xxx.xxx --ssh-user shivam --ssh-password '******' --sudo --use-sudo-password --node-name chefNode1 --run-list 'recipe[learn_chef_httpd1]'
Creating new client for chefNode2
Creating new node for chefNode2
Connecting to xxx.xxx.xxx.xxx
**ERROR: Network Error: Connection refused - connect(2) for xxx.xxx.xxx.xxx:22
Check your knife configuration and network settings**
```
My knife.rb is
```
current_dir = File.dirname(__FILE__)
log_level :info
log_location STDOUT
node_name "gshivam63"
client_key "#{current_dir}/gshivam63.pem"
chef_server_url "https://api.chef.io/organizations/gshivam63_chef"
cookbook_path ["#{current_dir}/../cookbooks"]
```<issue_comment>username_1: using jQuery you can do it in this way.
```
var firstname = [];
$("#name-field .firstname").each(function(){
firstname.push($(this).val());
});
```
In firstname you will all the values.
Update
------
Here is a working pen.
<https://codepen.io/smitraval27/pen/dmvwVB>
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
document.getElementsByClassName("firstname")
```
returns an array... so the following will give you the elements value with index i. To get all the values you will need to do a ForEach.
```
document.getElementsByClassName("firstname")[0].value
```
Since you're using JQuery elsewhere, why not use...
```
$('.firstname')[0].val();
```
Upvotes: 0 <issue_comment>username_3: The most ideal way to do this is :
* add a form wrapper to your fields (`id="ajaxForm"`)
* to have a `name` to all your form
fields and use the below code to generate the `data` to be passed to
your AJAX call
`$("#ajaxForm").serialize()`
The return value of `$.serialize()` can be directly used as the `data` for the ajax call
```js
$("#ajaxForm").on("submit", function () {
var ajaxData = $("#ajaxForm").serialize();
$("#ajaxData").text(ajaxData);
$.ajax({
url:"",
type: "get",
data : ajaxData,
success: function (resp) {}
});
console.log(ajaxData);
});
```
```html
```
Upvotes: 0 |
2018/03/21 | 660 | 2,417 | <issue_start>username_0: I have a set of storyboards under the `UINavigation Controller`. One of these screens contains a table view and I need to send the data of the clicked row to the next screen. I am aware that doing so would require me to use segue. But then how do I get the `Navigation Bar` and the `Navigation Button`
For better understanding I have uploaded the screen shot of my first screen. Clicking on the detail button is going to send the challenge object to next screen. However, I am looking forward to having the same navigation bar on the top of the next scree. Any idea how can I accomplish such objective?
Currently if I press on details `button`, I'll get the details of that challenge in the terminal.
```
@IBAction func CAStartChallenge(_ sender: UIButton) {
let tag = NSNumber(value: sender.tag) as! Int
print("challenge name to be printed : \(challengeTableConent[tag].display()) ")
}
```
[](https://i.stack.imgur.com/KOlFJ.png)<issue_comment>username_1: using jQuery you can do it in this way.
```
var firstname = [];
$("#name-field .firstname").each(function(){
firstname.push($(this).val());
});
```
In firstname you will all the values.
Update
------
Here is a working pen.
<https://codepen.io/smitraval27/pen/dmvwVB>
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
document.getElementsByClassName("firstname")
```
returns an array... so the following will give you the elements value with index i. To get all the values you will need to do a ForEach.
```
document.getElementsByClassName("firstname")[0].value
```
Since you're using JQuery elsewhere, why not use...
```
$('.firstname')[0].val();
```
Upvotes: 0 <issue_comment>username_3: The most ideal way to do this is :
* add a form wrapper to your fields (`id="ajaxForm"`)
* to have a `name` to all your form
fields and use the below code to generate the `data` to be passed to
your AJAX call
`$("#ajaxForm").serialize()`
The return value of `$.serialize()` can be directly used as the `data` for the ajax call
```js
$("#ajaxForm").on("submit", function () {
var ajaxData = $("#ajaxForm").serialize();
$("#ajaxData").text(ajaxData);
$.ajax({
url:"",
type: "get",
data : ajaxData,
success: function (resp) {}
});
console.log(ajaxData);
});
```
```html
```
Upvotes: 0 |
2018/03/21 | 498 | 1,792 | <issue_start>username_0: I've noticed that Visual studio looks for a referenced dll anywhere (other projects, GAC, ...) if that dll isn´t in referenced path. It happens mostly with nugget packages.
Is there anyway to prevent this behavior?
I think this behavior is dangerous, because it gives you false security that your application has all refenreced dlls correctly, at the time of deploy app you can get a surprise.
Thanks<issue_comment>username_1: using jQuery you can do it in this way.
```
var firstname = [];
$("#name-field .firstname").each(function(){
firstname.push($(this).val());
});
```
In firstname you will all the values.
Update
------
Here is a working pen.
<https://codepen.io/smitraval27/pen/dmvwVB>
Upvotes: 3 [selected_answer]<issue_comment>username_2: ```
document.getElementsByClassName("firstname")
```
returns an array... so the following will give you the elements value with index i. To get all the values you will need to do a ForEach.
```
document.getElementsByClassName("firstname")[0].value
```
Since you're using JQuery elsewhere, why not use...
```
$('.firstname')[0].val();
```
Upvotes: 0 <issue_comment>username_3: The most ideal way to do this is :
* add a form wrapper to your fields (`id="ajaxForm"`)
* to have a `name` to all your form
fields and use the below code to generate the `data` to be passed to
your AJAX call
`$("#ajaxForm").serialize()`
The return value of `$.serialize()` can be directly used as the `data` for the ajax call
```js
$("#ajaxForm").on("submit", function () {
var ajaxData = $("#ajaxForm").serialize();
$("#ajaxData").text(ajaxData);
$.ajax({
url:"",
type: "get",
data : ajaxData,
success: function (resp) {}
});
console.log(ajaxData);
});
```
```html
```
Upvotes: 0 |
2018/03/21 | 1,132 | 3,829 | <issue_start>username_0: In flutter, is it possible to place a part of a card on another container? In CSS, we would set margin-top to a negative value or use translate property. In flutter as we cannot set negative values to margin-top, is there an alternative to that?
[](https://i.stack.imgur.com/U8edR.png)<issue_comment>username_1: Yes, you can acheive it with a `Stack` widget. You can stack a card over the background and provide a top or bottom padding.
A simple example would look like:
```
class StackDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Stack(
children: [
// The containers in the background
new Column(
children: [
new Container(
height: MediaQuery.of(context).size.height \* .65,
color: Colors.blue,
),
new Container(
height: MediaQuery.of(context).size.height \* .35,
color: Colors.white,
)
],
),
// The card widget with top padding,
// incase if you wanted bottom padding to work,
// set the `alignment` of container to Alignment.bottomCenter
new Container(
alignment: Alignment.topCenter,
padding: new EdgeInsets.only(
top: MediaQuery.of(context).size.height \* .58,
right: 20.0,
left: 20.0),
child: new Container(
height: 200.0,
width: MediaQuery.of(context).size.width,
child: new Card(
color: Colors.white,
elevation: 4.0,
),
),
)
],
);
}
}
```
The output of the above code would look something like:
[](https://i.stack.imgur.com/PZ7UO.png)
Hope this helps!
Upvotes: 7 [selected_answer]<issue_comment>username_2: Here is running example with overlay:
```
class _MyHomePageState extends State {
double \_width = 0.0;
double \_height = 0.0;
@override
Widget build(BuildContext context) {
\_width = MediaQuery.of(context).size.width;
\_height = MediaQuery.of(context).size.height;
return Scaffold(
backgroundColor: Colors.white,
body: Stack(
children: [
// The containers in the background and scrollable
getScrollableBody(),
// This container will work as Overlay
getOverlayWidget()
],
),
);
}
Widget getOverlayWidget() {
return new Container(
alignment: Alignment.bottomCenter,
child: new Container(
height: 100.0,
width: \_width,
color: Colors.cyan.withOpacity(0.4),
),
);
}
Widget getScrollableBody() {
return SingleChildScrollView(
child: new Column(
children: [
new Container(
height: \_height \* .65,
color: Colors.yellow,
),
new Container(
height: \_height \* .65,
color: Colors.brown,
),
new Container(
margin: EdgeInsets.only(bottom: 100.0),
height: \_height \* .65,
color: Colors.orange,
),
],
),
);
}
}
```
Here is Result of code:
[Scrollable Body under customised Bottom Bar](https://i.stack.imgur.com/u3WKW.png)
Upvotes: 0 <issue_comment>username_3: **Screenshot:**
[](https://i.stack.imgur.com/DorA0.png)
Instead of hardcoding `Positioned` or `Container`, you should use `Align`.
**Code:**
```dart
@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
return Scaffold(
body: Stack(
children: [
Column(
children: [
Expanded(flex: 2, child: Container(color: Colors.indigo)),
Expanded(child: Container(color: Colors.white)),
],
),
Align(
alignment: Alignment(0, 0.5),
child: Container(
width: size.width * 0.9,
height: size.height * 0.4,
child: Card(
elevation: 12,
child: Center(child: Text('CARD', style: Theme.of(context).textTheme.headline2)),
),
),
),
],
),
);
}
```
Upvotes: 3 |
2018/03/21 | 1,465 | 5,820 | <issue_start>username_0: In my **`WalletTableViewController`** I have two functions, used to calculate the `Wallet Value`:
**A.** `updateCellValue()` Is called by `reloadData()` with the `tableView` and uses `indexPath.row` to fetch a `value` (price) and an `amount` (number of coins) corresponding to the cell and make a calculation to get the total value of that coin (amountValue = value \* amount). That is then saved with Core Data.
```
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! WalletTableViewCell
cell.delegate = self
cell.amountTextField.delegate = self
updateCellValue(cell, atRow: indexPath.row)
return cell
}
func updateCellValue(_ walletTableViewCell: WalletTableViewCell, atRow row: Int) {
var newCryptos : [CryptosMO] = []
var doubleAmount = 0.0
if CoreDataHandler.fetchObject() != nil {
newCryptos = CoreDataHandler.fetchObject()!
}
cryptoPrice = cryptos[row].code!
guard let cryptoDoublePrice = CryptoInfo.cryptoPriceDic[cryptoPrice] else { return }
let selectedAmount = newCryptos[row]
guard let amount = selectedAmount.amount else { return }
var currentAmountValue = selectedAmount.amountValue
doubleAmount = Double(amount)!
let calculation = cryptoDoublePrice * doubleAmount
currentAmountValue = String(calculation)
CoreDataHandler.editObject(editObject: selectedAmount, amount: amount, amountValue: currentAmountValue)
updateWalletValue()
}
```
**B.** `updateWalletValue()` Is a function that fetches all the `amountValue` objects in Core Data and adds them together to calculate the `Wallet Value`.
```
func updateWalletValue() {
var items : [CryptosMO] = []
if CoreDataHandler.fetchObject() != nil {
items = CoreDataHandler.fetchObject()!
}
total = items.reduce(0.0, { $0 + Double($1.amountValue)! } )
WalletTableViewController.staticTotal = total
}
```
**In my `MainViewController`, the `Wallet Value` is displayed too, but how can I refresh it's value?**
```
func updateMainVCWalletLabel() {
//... what can I do here??
}
```
**This works great for the `WalletViewController`** of course with the `TableView` and `indexPath`, but **how can I call `updateCellValue` from the `MainViewController` to keep the value updated?**
The `WalletViewController` is instantiated and pushed from the `MainViewController` :
```
@IBAction func walletButtonTapped(_ sender: Any) {
let walletViewController = self.storyboard?.instantiateViewController(withIdentifier: "walletTableViewController")
self.present(walletViewController!, animated: true)
}
```<issue_comment>username_1: **Update** (old answer below)
To me it is absolutly unclear what you want to achieve: Which value do you want to be updated? The `staticTotal`?
Seems a litte like an [XYProblem](http://mywiki.wooledge.org/XyProblem) to me. As @vadian commented yesterday, please clearly describe where the data is stored, how the controllers are connected, what you want to update when in order to achieve what. You could also provide a [MCVE](https://stackoverflow.com/help/mcve) which makes clear what you are asking, instead of adding more and more code snippets.
**And, even more interesting**: Why do you *modify* CoreData entries (`CoreDataHandler.editObject`) when you are in the call stack of `tableView(_: cellForRowAt:)`? **Never ever** ever do so! You are in a *reading* case - `reloadData` is intended to update the table *view* to reflect the data changes *after* the data has been changed. It is *not* intended to update the data itself. `tableView(_: cellForRowAt:)` is called many many times, especially when the user scrolls up and down, so you are causing large write impacts (and therefore: performance losses) when you write into the database.
---
**Old Post**
You could just call `reloadData` on the table view, which then will update it's cells.
There are also a few issues with your code:
* Why do you call `updateWalletValue()` that frequently? Every time a cell is being displayed, it will be called, run through the whole database and do some reduce work. You should cache the value and only update it if the data itself is modified
* Why do you call `fetchObject()` twice (in `updateWalletValue()`)?
You should do this:
```
func updateWalletValue() {
guard let items:[CryptosMO] = CoreDataHandler.fetchObject() else {
WalletTableViewController.staticTotal = 0.0
return
}
total = items.reduce(0.0, { $0 + Double($1.amountValue)! } )
WalletTableViewController.staticTotal = total
}
```
Upvotes: 0 <issue_comment>username_2: If you want to use a single method in multiple view controllers you should implement that method where you can call that method from anywhere. For example you can use singleton class here.
1. Create a swift file and name it as your wish (like WalletHelper or WalletManager)
2. Then you will get a file with the following format
```swift
class WalletHelper: NSObject
{
}
```
3. Create a shared instance for that class
```swift
static let shared = WalletHelper()
```
4. Implement the method you want
```swift
func getWalletValue() -> Float {
// write your code to get wallet value`
// and return the calculated value
}
```
5. Finally call that method like
```swift
let walletValue = WalletHelper.shared. getWalletValue()
```
WalletHelper.swift looks like
```swift
import UIKit
class WalletHelper: NSObject
{
static let shared = WalletHelper()
func getWalletValue() -> Float {
// write your code to get wallet value
// and return the calculated value
}
}
```
Upvotes: 1 |
2018/03/21 | 560 | 1,771 | <issue_start>username_0: I am using the Konvajs library. Am trying to put a border box around the main `Stage` element, but can't seem to make it work. The CSS only apply to the and the `Konva.Stage` element does not seem to have specific properties for this.
Is the only way to add line shapes on the 4 borders of the Stage Layer?
My Konva container
```
```
My Konva Declaration below
```
var stage = new Konva.Stage({
container: 'KonvaContainer', // id of container
width: 600,
height: 180
});
```<issue_comment>username_1: You can use CSS for container element:
```
stage.getContainer().style.border = '1px solid black'.
```
Upvotes: 2 <issue_comment>username_2: This is an experiment with @username_1's answer. I was curious if the stage was resized by the border. The answer appears to be no - at least on Chrome.
```js
// Set up the stage
var stage1 = new Konva.Stage({container: 'container1', width: 300, height: 100});
// add a layer.
var layer1 = new Konva.Layer();
stage1.add(layer1);
console.log('Stage size before border=' + stage1.width() + ' x ' + stage1.height());
stage1.getContainer().style.border = '5px solid black';
console.log('Stage size after border=' + stage1.width() + ' x ' + stage1.height());
var rect1 = new Konva.Rect({x:0, y: 0, width: 50, height: 40, strokeWidth: 10, stroke: 'lime'});
layer1.add(rect1)
stage1.draw()
```
```css
p
{
padding: 4px;
}
#container1
{
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
```
```html
This answers the question 'does the border reduce the size of the stage?'. Answer is no. The green rect appears with its left and top edges under the border - at least on Chrome.
```
Upvotes: 0 |
2018/03/21 | 717 | 2,189 | <issue_start>username_0: <https://jsfiddle.net/z24kaL2d/4/>
```
Login Form
html,
body {
height: 100%;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
}
.margin {
margin: 0 !important;
}
.row {
margin-left: auto;
margin-right: auto;
margin-bottom: 20px;
min-width: 300px;
}

Login Form
Email
Password
Remember me
Sign in
[Register Now!](/register)
[Forgot password?](forgot-password.html)
```
This is my code. I am using material-design and i am not able to move the form to the right side. ho ca I able to move the form to right side as given in the image
I am not able to move the form to the right side. Please help me to have a solution in this case
This is my jsfiddle. I need to change this according to the image attached[](https://i.stack.imgur.com/OYTP1.png)<issue_comment>username_1: You can use CSS for container element:
```
stage.getContainer().style.border = '1px solid black'.
```
Upvotes: 2 <issue_comment>username_2: This is an experiment with @username_1's answer. I was curious if the stage was resized by the border. The answer appears to be no - at least on Chrome.
```js
// Set up the stage
var stage1 = new Konva.Stage({container: 'container1', width: 300, height: 100});
// add a layer.
var layer1 = new Konva.Layer();
stage1.add(layer1);
console.log('Stage size before border=' + stage1.width() + ' x ' + stage1.height());
stage1.getContainer().style.border = '5px solid black';
console.log('Stage size after border=' + stage1.width() + ' x ' + stage1.height());
var rect1 = new Konva.Rect({x:0, y: 0, width: 50, height: 40, strokeWidth: 10, stroke: 'lime'});
layer1.add(rect1)
stage1.draw()
```
```css
p
{
padding: 4px;
}
#container1
{
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
```
```html
This answers the question 'does the border reduce the size of the stage?'. Answer is no. The green rect appears with its left and top edges under the border - at least on Chrome.
```
Upvotes: 0 |
2018/03/21 | 621 | 1,987 | <issue_start>username_0: I got a problem with my bootstrap nav bar. It wont color the way I want it too and I tried adding code even with the `!import` but I can't get it to work
```
[<NAME>](#)
* [Product (current)](#main)
* [Werk](#features)
* [Prijs](#pricing)
* [Team](#team)
* [Blog](#blog)
* [Contact](#contact)
```
This is what my code looks like but it won't color the background green only for the first milisecond or something.
[If I inspect the website you can see on the left that it somehow makes it a different color and I don't know why](https://i.stack.imgur.com/WkcXF.png) There is nothing in the css making it that color. If I am on the top of the website it makes it transparent and if I scrol this color<issue_comment>username_1: You can use CSS for container element:
```
stage.getContainer().style.border = '1px solid black'.
```
Upvotes: 2 <issue_comment>username_2: This is an experiment with @username_1's answer. I was curious if the stage was resized by the border. The answer appears to be no - at least on Chrome.
```js
// Set up the stage
var stage1 = new Konva.Stage({container: 'container1', width: 300, height: 100});
// add a layer.
var layer1 = new Konva.Layer();
stage1.add(layer1);
console.log('Stage size before border=' + stage1.width() + ' x ' + stage1.height());
stage1.getContainer().style.border = '5px solid black';
console.log('Stage size after border=' + stage1.width() + ' x ' + stage1.height());
var rect1 = new Konva.Rect({x:0, y: 0, width: 50, height: 40, strokeWidth: 10, stroke: 'lime'});
layer1.add(rect1)
stage1.draw()
```
```css
p
{
padding: 4px;
}
#container1
{
display: inline-block;
width: 500px;
height: 200px;
background-color: silver;
overflow: hidden;
}
```
```html
This answers the question 'does the border reduce the size of the stage?'. Answer is no. The green rect appears with its left and top edges under the border - at least on Chrome.
```
Upvotes: 0 |
2018/03/21 | 331 | 990 | <issue_start>username_0: I can do
```
import random
a = [1, 2, 3]
random.shuffle(a)
```
or
```
from random import shuffle
a = [1, 2, 3]
shuffle(a)
```
But I can't
```
import random.shuffle
a = [1, 2, 3]
random.shuffle(a)
```
which will make the interpreter complain
>
> 'random' is not a package.
>
>
>
Why is this?<issue_comment>username_1: Just putting the comments into an answer.
import a.b imports the b module or package from a. Since shuffle isn’t a package, it can’t import it.
Read more about packages [here](https://docs.python.org/2.7/tutorial/modules.html#packages).
Upvotes: 2 [selected_answer]<issue_comment>username_2: You can't `import random.shuffle`, because it's function, so error saying it's not a package is correct.
If you want to import shuffle only, you can do this:
```
from random import shuffle
a = [1, 2, 3]
shuffle(a)
```
Upvotes: 2 <issue_comment>username_3: Import shuffle like this
```
from sklearn.utils import shuffle
```
Upvotes: -1 |
2018/03/21 | 1,029 | 3,575 | <issue_start>username_0: I'm new in Angular.
I've a class called User:
```js
export class User {
private id: number;
private name: string;
private surname: string;
get Id(): number {
return this.id;
}
set Id(newId: number) {
this.id = newId;
}
get Name(): string {
return this.name;
}
set Name(newName: string) {
this.name = newName;
}
get Surname(): string {
return this.surname;
}
set Surname(newSurname: string) {
this.surname = newSurname;
}
}
```
...a function to retrive an array of user:
```js
getValues() {
this.usersService.getUsers()
.subscribe((users: User[]) => this.dataSource = users);
}
```
and a method to retrive the users array from backend WebApi:
```js
getUsers(): Observable {
return this.http.get(this.usersSearchUrl)
.pipe(
tap(users => this.log(`fetched users`)),
catchError(this.handleError('getUsers', []))
);
}
```
finally the json returned from the webapi:
```
[{"id":"1","name":"Alberico","surname":"Gauss"},{"id":"2","name":"Anassimandro","surname":"Dirac"},{"id":"3","name":"Antongiulio","surname":"Poisson"}]
```
I would have expected that the call would automatically mapped the User class, instead it only gives me an array of type User, in fact if I write something in my component .subscribe((utenti: Utente[]) => console.log(utenti[0].Surname)); the console writes me "undefined". Can you tell me where I'm wrong? Thanks<issue_comment>username_1: I think in component ts use like this code:
```
users: User[];
constructor(
private us: usersService,
public auths: AuthService
)
this.us.getUsers.subscribe(
users=> {
this.users= users.map((user) => {
return new User(user);
});
}
);
```
In service I think to write:
```
public getUsers(): Observable {
let headers = new Headers();
headers.append('x-access-token', this.auth.getCurrentUser().token);
return this.http.get(Api.getUrl(Api.URLS.getUsers), {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 1) {
this.auth.logout();
} else {
return res.StatusDescription.map(user=> {
return new User(user);
});
}
});
}
```
For me this logic work perfect. I hope to help you with this code
Upvotes: -1 [selected_answer]<issue_comment>username_2: You are retrieving JSON from your backend, as is expected. A Javascript (or typescript) class is not the same thing.
When the JSON is returned, it can be automatically converted into a simple JSON object in Javascript but it will NOT include all your getters and setters. So these class methods are not available, which is why you get undefined.
Remove all the getters and setters and add a constructor. Then you can just call Surname directly as a property and it will return the value (since it will then just be a plain JSON object).
```
export class User {
constructor() {
}
public id: number;
public name: string;
public surname: string;
}
```
Or without a constructor, and just declare the properties directly:
```
export class User {
public id: number;
public name: string;
public surname: string;
}
```
Or you could also use an interface:
```
export interface User {
id: number;
name: string;
surname: string;
}
```
You can read more about this issue [here](https://stackoverflow.com/questions/40421100/how-to-parse-a-json-object-to-a-typescript-object) and [here](https://stackoverflow.com/questions/22875636/how-do-i-cast-a-json-object-to-a-typescript-class).
Upvotes: 2 |
2018/03/21 | 794 | 2,452 | <issue_start>username_0: I'm using `MySQL 5.5`. with two tables in it:
```
DROP TABLE IF EXISTS `events_dictionary`;
CREATE TABLE `events_dictionary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `events_dictionary` VALUES (1, 'Light'),(2, 'Switch'),(3, 'on'),(4, 'off');
DROP TABLE IF EXISTS `events_log`;
CREATE TABLE `events_log` (
`log_id` bigint(20) NOT NULL AUTO_INCREMENT,
`event_name_id` int(11) NOT NULL DEFAULT '0',
`event_param1` int(11) DEFAULT NULL,
`event_value1` int(11) DEFAULT NULL,
PRIMARY KEY (`log_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `events_log` VALUES (1, 1, 2, 3),(2, 1, 2, 4);
```
Table `events_dictionary` contains names for `events_log events names,params and values`.
So, my question is - how could i select data from `event_log` table with columns `event_name_id, event_param1, event_value1` mapped to `name` values from `events_dictionary` table?
I tried to do this query:
```
SELECT name, event_param1, event_value1
FROM events_log
JOIN events_dictionary ON events_log.event_name_id = events_dictionary.id;
```
But, in this case i see only event\_name\_id replaced with values from events\_dictionary, like this:
```
name | event_param1 | event_value1
Light | 1 | 1
Light | 1 | 2
```
And i want to replace event\_param1, and event\_value1 with names from events\_dictionary too.
Thanks in advance!<issue_comment>username_1: You need to join to the events\_dictionary multiple times
```
SELECT a.name, b.name, c.name
FROM events_log
JOIN events_dictionary a ON events_log.event_name_id = a.id
JOIN events_dictionary b ON events_log.event_param1 = b.id
JOIN events_dictionary c ON events_log.event_value1 = c.id;
```
PS
Your example for the event\_log isn't that helpful , instead insert the values (1,1,2,3),(2,1,2,4) to turn the switch on and off for the light.
DS
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use correlated subqueries:
```
SELECT name,
(SELECT t.name
FROM events_dictionary AS t
WHERE t.id = event_param1) AS param_name,
(SELECT t2.name
FROM events_dictionary AS t2
WHERE t2.id = event_value1) AS event_name
FROM events_log AS el
JOIN events_dictionary AS ed ON el.event_name_id = ed.id;
```
[**Demo here**](http://sqlfiddle.com/#!9/5ad689/6)
Upvotes: 1 |
2018/03/21 | 517 | 1,726 | <issue_start>username_0: I am working on `in place edit` functionality in which, in which a user can enter values as comma separated but I have to put style on those each comma separated values which is not possible as all values are in one textbox, is it possible to put each entered values in a span tag with a class name so that I can apply `CSS` or hide the textbox and show the styled span tag .
[](https://i.stack.imgur.com/WjQkt.png)
I am doing something like this
[](https://i.stack.imgur.com/6olQ7.png)
How to take those values and put it in the span/div tags so that I can apply CSS for styling or any other method for the same.<issue_comment>username_1: You need to join to the events\_dictionary multiple times
```
SELECT a.name, b.name, c.name
FROM events_log
JOIN events_dictionary a ON events_log.event_name_id = a.id
JOIN events_dictionary b ON events_log.event_param1 = b.id
JOIN events_dictionary c ON events_log.event_value1 = c.id;
```
PS
Your example for the event\_log isn't that helpful , instead insert the values (1,1,2,3),(2,1,2,4) to turn the switch on and off for the light.
DS
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use correlated subqueries:
```
SELECT name,
(SELECT t.name
FROM events_dictionary AS t
WHERE t.id = event_param1) AS param_name,
(SELECT t2.name
FROM events_dictionary AS t2
WHERE t2.id = event_value1) AS event_name
FROM events_log AS el
JOIN events_dictionary AS ed ON el.event_name_id = ed.id;
```
[**Demo here**](http://sqlfiddle.com/#!9/5ad689/6)
Upvotes: 1 |
2018/03/21 | 335 | 1,097 | <issue_start>username_0: Is EventBus suitable for the tasks I am trying to complete? I need a callback whenever any application prints a document.<issue_comment>username_1: You need to join to the events\_dictionary multiple times
```
SELECT a.name, b.name, c.name
FROM events_log
JOIN events_dictionary a ON events_log.event_name_id = a.id
JOIN events_dictionary b ON events_log.event_param1 = b.id
JOIN events_dictionary c ON events_log.event_value1 = c.id;
```
PS
Your example for the event\_log isn't that helpful , instead insert the values (1,1,2,3),(2,1,2,4) to turn the switch on and off for the light.
DS
Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use correlated subqueries:
```
SELECT name,
(SELECT t.name
FROM events_dictionary AS t
WHERE t.id = event_param1) AS param_name,
(SELECT t2.name
FROM events_dictionary AS t2
WHERE t2.id = event_value1) AS event_name
FROM events_log AS el
JOIN events_dictionary AS ed ON el.event_name_id = ed.id;
```
[**Demo here**](http://sqlfiddle.com/#!9/5ad689/6)
Upvotes: 1 |
2018/03/21 | 498 | 1,621 | <issue_start>username_0: This is my code i and it's working perfectly fine. I just wanted to print the table by using Html tables and also want to apply bootstrap on it to add borders,the multiplication table in form of an HTML TABLE with every line as a table row ‘tr’. Table should be styled by bootstrap table-bordered class.
```html
Multiplication Table
MultiplicationTable
-------------------
Table Number:
Initial Number:
Ending Number:
Print Table
function myFunction()
{
var text = "";
var Number = document.getElementById("TN").value;
var T;
var I = document.getElementById("IN").value;
var E = document.getElementById("EN").value;
for (T = I; T <= E; T++) {
text += Number + "\*" + T + "=" + Number\*T + "<br>";
}
document.getElementById("MT").innerHTML = text;
}
```<issue_comment>username_1: ```js
function myFunction()
{
var Number = document.getElementById("TN").value;
var T;
var I = document.getElementById("IN").value;
var E = document.getElementById("EN").value;
var temp="";
for (T = I; T <= E; T++) {
temp+="| "+Number+" | \* | " + T + " | = | " + Number\*T +" |
";
}
$("#displayTables").append(temp);
}
```
```html
Multiplication Table
MultiplicationTable
-------------------
Table Number:
Initial Number:
Ending Number:
Print Table
```
Upvotes: 1 [selected_answer]<issue_comment>username_2: A simple Table using JavaScript.
**Code goes here -**
```
multiplication table
var i, j;
var m = 1;
for (i = 1; i <= 10; i++) {
for (j = 1; j <= 10; j++) {
document.write(i \* j);
}
document.write("<br/>");
}
```
Upvotes: 1 |
2018/03/21 | 506 | 1,673 | <issue_start>username_0: See this huge identations is painful (for me). Is there a way to set tab size to 4 spaces.
This picture is taken from local Gitlab CE server with minimal customization. I think tabsize 8 spaces is default.
[](https://i.stack.imgur.com/gnv3d.png)<issue_comment>username_1: Yeah, gitlab uses browser CSS property tab-size which default value is 8.
There's a bug discussion about this here:
<https://gitlab.com/gitlab-org/gitlab-ce/issues/2479>
You can change gitlab CSS and you'll have what you want.
Upvotes: 4 [selected_answer]<issue_comment>username_2: As of February 2021, this has not been addressed. One can check the current [GitLab issue](https://gitlab.com/gitlab-org/gitlab/-/issues/26768) for progress, but in the meantime, [this](https://gitlab.com/gitlab-org/gitlab/-/issues/26768#note_215634043) comment on the thread offers a solution via creating a UserScript via [Greasemonkey](https://www.greasespot.net/) / [Tampermonkey](https://tampermonkey.net/) with this script:
```js
// ==UserScript==
// @name GitLab Tab Size
// @version 1
// @include https://gitlab.com/*
// @grant none
// ==/UserScript==
const TAB_SIZE = 2
window.addEventListener('load', function() {
const styleElement = document.createElement('style')
styleElement.innerHTML = `
.diff-content, pre.code {
-moz-tab-size: ${TAB_SIZE};
tab-size: ${TAB_SIZE};
}
`
document.head.appendChild(styleElement)
})
```
Credit to <NAME> from that thread.
Upvotes: 2 <issue_comment>username_3: Go to `Settings` -> `Preferences` -> `Behavior` and set `Tab width`
Upvotes: 5 |
2018/03/21 | 957 | 3,737 | <issue_start>username_0: I need to restrict the backspace navigation within my whole app.Are there any solutions i.e something that I can perform under a single tile for my whole app ?<issue_comment>username_1: The solution LokiSinclair proposed for AngularJS should be adjustable to work with Angular 5 as well. The basic solution just prevents the key event, therefore you could enter a HostListener to your AppComponent which handles this globally:
```
@HostListener('document:keydown', ['$event'])
onKeyDown(evt: KeyboardEvent) {
if (
evt.which === 8 &&
( evt.target.nodeName !== "INPUT" && evt.target.nodeName !== "SELECT" )
) {
evt.preventDefault();
}
}
```
Credits to [Prevent backspace from navigating back in AngularJS](https://stackoverflow.com/questions/29006000/prevent-backspace-from-navigating-back-in-angularjs) for the general logic, just translated it to the Angular 5 utilities.
Upvotes: 1 <issue_comment>username_2: I am working on Angular 6 application and was facing same issue on Internet Explorer (IE).
I was searching the solution on internet then I found one solution in JQuery. Somehow I managed to convert it in Angular.
This snippet resolved the issue.
```
@HostListener('document:keydown', ['$event'])
onKeyDown(evt: KeyboardEvent) {
if (
evt.keyCode === 8 || evt.which === 8
) {
let doPrevent = true;
const types =['text','password','file','search','email','number','date','color','datetime','datetime-local','month','range','search','tel','time','url','week'];
const target = (evt.target);
const disabled = target.disabled || (event.target).readOnly;
if (!disabled) {
if (target.isContentEditable) {
doPrevent = false;
} else if (target.nodeName === 'INPUT') {
let type = target.type;
if (type) {
type = type.toLowerCase();
}
if (types.indexOf(type) > -1) {
doPrevent = false;
}
} else if (target.nodeName === 'TEXTAREA') {
doPrevent = false;
}
}
if (doPrevent) {
evt.preventDefault();
return false;
}
}
}
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: With Router Guards we can prevent users from accessing areas that they’re not allowed to access, or, we can ask them for confirmation when leaving a certain area.To control whether the user can navigate to or away from a given route, use these route guards.
You can use any of these two:
**CanActivate**
Checks to see if a user can visit a route.
**CanDeactivate**
Checks to see if a user can exit a route.
Here your preference is not to allow to to go back.
I have used for a login condition. I am giving my sample code to you. It may help you.
```
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthenticateService } from '../authenticate.service';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoginAuthService implements CanActivate {
constructor(
private checkLogin: AuthenticateService,
private router: Router) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable | Promise | boolean {
// This isLoggedIn flag is set when the token is found after login
if (!this.checkLogin.isLoggednIn()) {
return true;
} else {
this.router.navigate(['/componentOfMyChoice']);
}
}
}
```
Then I used it in the routing like this
```
{ path: 'login', component: LoginComponent , canActivate: [LoginAuthService]},
```
So when a user is logged in you cannot go back to the login page until and unless you get logged out. Hope it will help you
Upvotes: 0 |
2018/03/21 | 203 | 722 | <issue_start>username_0: I have a some data stored in $data[], there are some items in it. How do I remove duplicate values in a foreach?
```
Array
(
[0] => ABC
)
Array
(
[0] => XZY
)
Array
(
[0] => ABC
)
```
i have use some function array unique and convert it to json ... and not work<issue_comment>username_1: Use `array_unique($array)` function in order to remove duplicate value. It takes an input array and returns a new array without duplicate values.
Upvotes: 2 <issue_comment>username_2: You can use **array\_merge()** first. Then on result do **array\_unique();**
Upvotes: 0 <issue_comment>username_3: $input = array\_map("unserialize", array\_unique(array\_map("serialize", $array)));
Upvotes: 0 |
2018/03/21 | 476 | 1,677 | <issue_start>username_0: When using 7zip, clicking "edit" on a file inside of an archive, per default opens up notepad. How to use notepad++ instead?
7zip has the option to configure an external exitor.
Simply using the notepad++ exe does not work. Edit fails in notepad++ with an error message similar to "file cannot be saved, because it's already opened in another program" (I don't have an english installation).<issue_comment>username_1: Found a solution: Use a batch script to wrap the command line arguments inside and link that batch script in 7zip.
Batch file content:
```
call "C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin %*
```
Ideas used from following posts:* [How to use Jedit as the external editor of 7zip](https://stackoverflow.com/q/34921965)
* [Use Notepad++ as Git Bash editor](https://stackoverflow.com/q/30395402)
Upvotes: 3 [selected_answer]<issue_comment>username_2: for me, the zip file contains the file with ext .log. It was opened by notepad. From windows, change the default application for the file type .log. -> choose notepad++.
then the open the log file inside 7zip. it is opened by notepad++
Upvotes: 0 <issue_comment>username_3: Not sure if this will help anyone anymore, the above command by Robert can be used in
Tools > Options > Editor
in View and Editor
"C:\Program Files\Notepad++\notepad++.exe" -multiInst -notabbar -nosession -noPlugin "%\*"
This will open a new notepad++ editor without any other session and tab bar,
after editing, close the editor , you will be prompted with
File "xyz.txt" was modified . Do you want to update it in the archive ?
click ok/cancel
Upvotes: 2 |
2018/03/21 | 709 | 2,162 | <issue_start>username_0: I am new at SQL I a need help in creating one.
I have 2 tables:
**table 1:**
[](https://i.stack.imgur.com/vMQFn.jpg)
**table2:**
[](https://i.stack.imgur.com/HpdqB.jpg)
And now I want first name and last name for all friends of one user example of user <NAME> based on id from user and friend user id from table friends?<issue_comment>username_1: A simple inner join will do
```
Select First_name,Last_name
from user inner join friends on user.id = friends.user_id
where friends.id = 1
```
Or you can replace with `friends.user_id = 1` if you would like to look at `user_id` column
Upvotes: 0 <issue_comment>username_2: You should do 2 joins, one to get each friend's ID and another to retrieve that friend's name.
```
SELECT
U.ID,
U.first_name,
U.last_name,
N.first_name FriendFirstName,
N.last_name FriendLastName
FROM
[user] U
LEFT JOIN firends F ON U.ID = F.user_id
LEFT JOIN [user] N ON F.friend_id = N.id
```
Using a `LEFT JOIN` will make you see people with no friends (sniff).
If you want to see a particular user:
```
SELECT
U.ID,
U.first_name,
U.last_name,
N.first_name FriendFirstName,
N.last_name FriendLastName
FROM
[user] U
LEFT JOIN firends F ON U.ID = F.user_id
LEFT JOIN [user] N ON F.friend_id = N.id
WHERE
U.ID = 1948 -- Supplied ID
```
Upvotes: 2 [selected_answer]<issue_comment>username_3: Do the self `join`s
```
select f.first_name, u.first_name as friend_name
from user u
join (
select u.first_name, f.friend_id
from friend f
join user u on u.id = f.user_id
) f on f.friend_id = u.id
```
Upvotes: 1 <issue_comment>username_4: maybe I'm getting it wrong, but this is my suggeston:
```
SELECT
u1.first_name,
u1.last_name,
u2.first_name AS FriendFirstName,
u2.last_name AS FriendLastName,
FROM user AS u1
INNER JOIN friends AS f
ON t1.id = f.user_id
INNER JOIN user AS u2
ON f.friend_id = u2.id
```
Upvotes: 0 |
2018/03/21 | 565 | 1,735 | <issue_start>username_0: VC = ViewController
VM = ViewModel
P = Protocol
I have ViewModel protocols & classes in the format
```
protocol BaseVMP {
}
protocol VM1P: BaseVMP {
}
protocol VM2P: BaseVMP {
}
class BaseVM: BaseVMP {
}
class VM1: BaseVM, VM1P {
}
class VM2: BaseVM, VM2P {
}
ViewController classes
class BaseVC {
var baseVM: BaseVMP
}
class VC1: BaseVC {
var vm: VM1P
}
class VC2: BaseVC {
var vm: VM2P
}
```
As of now, I am keeping 2 variables for viewModel, one as vm and another one as baseVM in VC & baseVC respectively. What I want to achieve is that I keep just one variable vm in BaseVC which gets typecasted (if this is the correct term, I hope you got the meaning) to VM1P/VM2P when I want to access it in VC1/VC2. Is it possible with the help of generics?<issue_comment>username_1: You already have that, BaseVMP can both hold an instance of VM1P and VM2P since they both comply to BaseVMP protocol.
```
class BaseVC
{
var baseVM: BaseVMP! // Be sure that's initialized before use.
}
class VC1: BaseVC
{
func setVM(vm: BaseVMP)
{
baseVM = vm as! VM1P // VM1P implements BaseVMP
}
}
```
Upvotes: 0 <issue_comment>username_2: With your class hierarchy you can have your BaseVC, VC1, VC2, structure something like,
```
class BaseVC {
var vm: T
init(vm: T) {
self.vm = vm
}
}
class VC1: BaseVC {
}
class VC2: BaseVC {
}
let vc1 = VC1(vm: VM1())
let vc2 = VC2(vm: VM2())
```
Note, vm property is inherited in all the subclasses and for VC1 and VC2, they are of specific types VM1 and VM2. I hope this is what you were looking for.
By the way, you should either have initializer or make property implicitly unwrapped just so that there is no error.
Upvotes: 1 |
2018/03/21 | 171 | 579 | <issue_start>username_0: How to increase permgen space in apache 1.9.2
I looked for a solution and couldn't find. I'm calling "ANT" command from the build directory. I tried changing the antenv.cmd as well.<issue_comment>username_1: Use the environmentvariable `ANT_OPTS` , as described in [ant manual](https://ant.apache.org/manual/running.html)
(see Environment Variables section) to set JVM parameters like f.e.:
```
-XX:PermSize -XX:MaxPermSize ... etc.
```
Upvotes: 1 <issue_comment>username_2: How about adding
```
set ANT_OPTS =
```
in /bin/ant.cmd
Upvotes: 0 |
2018/03/21 | 1,729 | 7,226 | <issue_start>username_0: I am trying to make a simple service which starts with device boot. Thing is that device return message "Unfortunately, [app\_name] has stopped."
I am struggling with this problem from few hours, with looking for mistake, but it is too simple.. Hope, you guys can help me with this problem.
This is my code:
AndroidManifest.xml
```
```
StartReceiver.cs
```
[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class StartReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Intent startIntent = new Intent(context, typeof(PService));
context.StartService(startIntent);
}
}
```
and lastly PService.cs
```
[Service]
public class PService : Service
{
public override void OnCreate()
{
base.OnCreate();
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Toast.MakeText(this, "Start", ToastLength.Short).Show();
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
base.OnDestroy();
Toast.MakeText(this, "Stop", ToastLength.Short).Show();
}
}
```
Additional this service application is targetted to API 19 (4.4.2 KitKat) Android version.
I think there will be really small mistake, made by me but truly I cant find it out.. Thanks in advance for any help.<issue_comment>username_1: By adding the receiver in the manifest and via the BroadcastReceiverAttribute you have two receivers in your manifest. Plus the one in your manifest will not work since it is not the MD5-based Java name that Xamarin creates by default.
### Via Attributes
1) Remove the receiver and boot permission from your manifest
2) Add your boot permissions via an attribute)
```
[assembly: UsesPermission(Manifest.Permission.ReceiveBootCompleted)]
```
3) Add the manifest entry via attributes:
```
[BroadcastReceiver(Enabled = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootBroadcastReceiver : BroadcastReceiver
```
### Via manifest
1) Add the manifest entry for the boot permission
```
```
2) Add the receiver and use a full qualify Java class name:
```
```
3) Add a `Name` parameter to the `BroadcastReceiverAttribute` for the fully qualified Java class name that you used in the manifest
```
[BroadcastReceiver(Name = "com.yourpackagename.app.BootBroadcastReceiver", Enabled = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootBroadcastReceiver : BroadcastReceiver
```
Upvotes: 5 [selected_answer]<issue_comment>username_2: 2022 ANSWER
===========
After almost 3 hours banging my head on the wall, I finally got it to work. All answers are out dated since Google made a few API changes. Anyway, here is what worked for me.
How I tested
------------
1. Launch App on phone (Just to clear out any confusions, I even launched it using my debugger to confirm it was not due to 'debug' mode). Fyi, I am using Xiaomi Pocophone F1. My App is targeting API level 30.
2. Make the App schedule notifications to appear 3 minutes later
3. Reboot the phone
4. Wait for 3 minutes (Note that I am NOT launching my App. I also do not have App autostart permission enabled for me. There was some old answer suggesting autostart must be on. This is WRONG i.e. not required)
5. After 3 minutes the notification appears! This means during reboot the Boot BroadcastReceiver fired up.
The code
--------
```
[assembly: UsesPermission (Manifest.Permission.ReceiveBootCompleted)]
namespace MyApp.Droid
{
[BroadcastReceiver(Name = "com.myapp.whatever.BootReceiver", Enabled = true)]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
RescheduleNotifications();
}
public void RescheduleNotifications()
{
try
{
AppCenter.Start("android=cfc33334-8f5e-4ab3-1232-e8712345c860;"
//"ios={Your iOS App secret here}",
, typeof(Crashes));
//Make sure all services are instantiated
AppCore.DeviceService = new DeviceService();
AppCore.FbService = new FBService();
AppCore.AppService = new AppService();
AppCore.DeviceService.ScheduleNotifications(notif.Notifications, false);
}
catch (Exception e)
{
Crashes.TrackError(e);
}
}
}
}
```
Notes on my code
----------------
* I am using MS App Center to track crashes. You may omit these parts.
* Remember that the OnReceive is fired alone (without Main Activity being fired). So make sure your code can run and does not throw any exceptions.
* In "com.myapp.whatever.BootReceiver" replace "com.myapp.whatever" with your app's package name
The android manifest
--------------------
```
```
Upvotes: 0 <issue_comment>username_3: There are a few gotchas I faced when working on this:
1. **Android ignores broadcast receivers of applications that have *never* been started by the user.** When deploying using Visual Studio, your app is installed fresh and started automatically which doesn't satisfy the "user-started" condition so your Broadcast Receiver won't get the `ACTION_BOOT_COMPLETED` intent. You will need to close the app after deployment (I remove it from my Recent Apps list) and manually re-open it again before it begins to receive implicit intent. *This tripped me up tremendously and I had spent several hours till I came across [someone else](https://stackoverflow.com/a/71551651/694457) who discovered this.*
2. If you're using Xamarin Forms, **make sure you're not using `DependencyService.Get()` in your Broadcast Receiver** as that requires Xamarin Forms to be initialized but the Android system doesn't call your `MainActivity` when triggering your BroadcastReceiver. The result is that the BroadcastReceiver does in fact get started but because it throws an Exception, you might not realize that it got called at all. I suggest using the Android implementation of the DI service directly in these cases.
Other than that, my `BroadcastReceiver` was pretty standard:
```
[BroadcastReceiver(Enabled = true, Exported = true, DirectBootAware = true)]
[IntentFilter(new[] { Intent.ActionLockedBootCompleted })]
public class RebootReceiver : BroadcastReceiver
```
I receive the `ACTION_LOCKED_BOOT_COMPLETED` intent which is broadcast earlier than the `ACTION_BOOT_COMPLETED` but requires the `DirectBootAware` property to be enabled and has some more specific limits regarding its usage. According to your needs, `Intent.ActionBootCompleted` without the `DirectBootAware` property could be just as sufficient.
And my Assembly.info file included this:
```
[assembly: UsesPermission(Android.Manifest.Permission.ReceiveBootCompleted)]
```
Upvotes: 1 |
2018/03/21 | 998 | 3,130 | <issue_start>username_0: When implementing a function which accepts a parameter pack of pointers to `Ts...`, why can't I `const`-qualify the pointers, as is possible with regular parameters?
I get a mismatching signature error on latest GCC and Clang, and I don't see why, since the pointers being `const` is just an implementation detail (hence it being legal for regular parameters).
```
template
class C
{
void f(int\*);
void g(Ts\*...);
};
template
void C::f(int\* const) {} // Legal
template
void C::g(Ts\* const...) {} // Compiler error
```
I am getting this error:
```
prog.cc:12:16: error: out-of-line definition of 'g' does not match any declaration in 'C'
void C::g(Ts\* const...) {}
^
1 error generated.
```
You can also see the code and error [here](https://wandbox.org/permlink/HZBXjIoxC0fVNFi3).<issue_comment>username_1: I'm going to chalk it up to a pair of compiler bugs (tested Clang and GCC). It's a bold assertion, I know, but [[dcl.fct]/5](https://timsong-cpp.github.io/cppwp/n4659/dcl.fct#5) says, emphasis mine:
>
> A single name can be used for several different functions in a single
> scope; this is function overloading. All declarations for a function
> shall agree exactly in both the return type and the
> parameter-type-list. The type of a function is determined using the
> following rules. **The type of each parameter (including function
> parameter packs) is determined from its own decl-specifier-seq and
> declarator.** After determining the type of each parameter, any
> parameter of type “array of T” or of function type T is adjusted to be
> “pointer to T”. **After producing the list of parameter types, any
> top-level cv-qualifiers modifying a parameter type are deleted when
> forming the function type.** **The resulting list of transformed parameter
> types and the presence or absence of the ellipsis or a function
> parameter pack is the function's parameter-type-list.** [ Note: This
> transformation does not affect the types of the parameters. For
> example, int(*)(const int p, decltype(p)*) and int(*)(int, const int*)
> are identical types. — end note ]
>
>
>
Which reads to me, quite clearly, that the declarations of both members (`f` *and* `g`) match the out-of-class definitions, making your program valid. So Clang and GCC should accept it.
Upvotes: 5 [selected_answer]<issue_comment>username_2: 3 years later ... FYI ...
MSVC 19.28.29337 (with Visual Studio 2019 v16.8.5) compiles and runs the following with `/W4 /Wx`:
```
#include
template
class C
{
public:
void f(int\*);
void g(Ts\*...);
};
template
void C::f(int\* const pi) {
using namespace std;
cout << "f " << \*pi << endl;
}
template
void C::g(Ts\* const... tsargs) {
using namespace std;
cout << "g ";
(cout << ... << \*tsargs);
cout << endl;
}
int main() {
C cifc;
int\* pi = new int{ 5 };
cifc.f(pi);
float\* pf = new float{ 1.0f };
char\* pc = new char{ 'a' };
cifc.g(pi, pf, pc);
}
```
But neither GCC HEAD 11.0.1 20210 nor Clang HEAD 13.0.0 does, with either C++17 nor C++2a.
[Wandbox](https://wandbox.org/permlink/aeP3s6cDjjckFGOO)
Upvotes: 2 |
2018/03/21 | 1,495 | 5,309 | <issue_start>username_0: I have the below CPP source code for creating a Singleton Object of a class using unique\_ptr:
```
#include
#include
class A
{
public:
std::unique\_ptrgetInstance(int log);
~A();
private:
static bool instanceFlag;
static std::unique\_ptrsingle;
A(int log);
int mLog;
};
bool A::instanceFlag = false;
std::unique\_ptrA::single = NULL;
std::unique\_ptrA::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make\_unique(log);
single = std::unique\_ptr(new A(log));
instanceFlag = true;
return std::move(single);
}
else
{
return std::move(single);
}
}
A::A(int log) :
mLog(log)
{
std::cout << "Called A cons" << std::flush << std::endl;
}
int main()
{
std::unique\_ptrmA = A::getInstance(5);
}
```
But when I compile the code I get below error:
```
$ c++ -std=c++11 try2.cpp
try2.cpp: In function 'int main()':
try2.cpp:45:41: error: cannot call member function 'std::unique_ptrA::getInstance(int)' without object
std::unique\_ptrmA = A::getInstance(5);
^
```
However I have exactly the same format of code in my project I get an error :
```
Source code Line 39: single = std::make_unique(log);
```
Compilation error:
```
39: required from here
single = std::make_unique(log);
error: A(int log)' is private
A::A(int log) :
^
```<issue_comment>username_1: The problem is that, as error log suggests, you are calling `member function` i.e. `getInstance` without any instance. Function `std::unique_ptrgetInstance(int log);` should be declared as `static`.
Declare it `static` as follow:
```
static std::unique_ptrgetInstance(int log);
```
**Note:** In *singleton pattern* `getInstance` function is always static function.
Following is an extract from [Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern):
>
> An implementation of the singleton pattern must:
>
>
> * ensure that only one instance of the singleton class ever exists; and
> * provide global access to that instance.
>
>
> Typically, this is done by:
>
>
> * declaring all constructors of the class to be private; and
> * providing a static method that returns a reference to the instance.
>
>
> The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.
>
>
>
Upvotes: 0 <issue_comment>username_2: First, the static issue. This:
```
std::unique_ptrgetInstance(int log);
```
is an instance method. You need an instance of `A` to call it on, but you can't get an instance of `A` without calling this method first, so ...
The reason for using instance methods is that they have access to the instance they're invoked on. Your method only uses the following members:
```
static bool instanceFlag;
static std::unique_ptrsingle;
```
which, since they're static, don't need an instance. Just make the method static too, and you'll be able to call it without first getting an `A` from somewhere.
---
Second, the logic issue. Your `getInstance` method returns a `unique_ptr` to your single instance. The entire point of `unique_ptr` is that's it's *unique*: exactly one pointer owns and controls the lifetime of an object. When you returned a `unique_ptr`, you *transferred ownership* of the singleton object from the singleton class itself, to the caller. You even explicitly called `move` to make it really clear that this is happening.
Now, after calling `getInstance` once, your singleton is completely broken. If you call `getInstance` again, the singleton believes it has an instance (because `instanceFlag`), but the `unique_ptr` is in an indeterminate state. The only thing we can say for sure is that it *doesn't* control an instance of `A`.
Just return a raw pointer (or reference) to `A` instead of transferring ownership.
Upvotes: 3 <issue_comment>username_3: Short answer: Don't use singletons.
Long answer: `std::make_unique()` uses constructor of an object it tries to create, and in your code it's private. Since it is an external function, it's not possible. You can create an object on your own and pass it to `std::unique_ptr` to manage, like you do on the line below the commented one.
The most important problem is, when you do `std::move()`, your class member `single` is gone. It becomes empty `unique_ptr` (aka. `std::unique_ptr{}`, it doesn't manage anything). With any next call to `getInstance`, you're essentially returning `nullptr`. You should use `std::shared_ptr`, which you'll want to return by copy or return reference to your `std::unique_ptr`.
Upvotes: 3 [selected_answer]<issue_comment>username_4: Even after making the `getInstance` static, it won't compile because the definition for destructor is missing. Either give empty definition or leave it as default.
`~A() = default;`
Moving `single` will work first time and invokes UB for subsequent calls to `getInstance`. Instead return by reference `&` and remove `std::move`
`static std::unique_ptr& getInstance(int log);`
```
std::unique_ptr& A::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make\_unique(log);
single = std::unique\_ptr(new A(log));
instanceFlag = true;
return single;
}
else
{
return single;
}
}
```
Inside `main()` you can get by reference
`std::unique_ptr& mA = A::getInstance(5);`
Upvotes: 2 |
2018/03/21 | 1,440 | 5,605 | <issue_start>username_0: In my application I don't want that the application always crash if there was thrown a unhandled exception. I did some research and found a few EventHandlers.
On this [Page](https://dzone.com/articles/order-chaos-handling-unhandled) is writtin:
>
> In a typical WPF application you should use `Application.Current.DispatcherUnhandledException` for exceptions generated on the UI thread and `AppDomain.CurrentDomain.UnhandledException` for all the other exceptions.
>
>
>
In my case I need the `Application.Current.DispatcherUnhandledException` handler (I think so).
I did following. First in the App.xaml.cs OnStartup(...)-Method I wrote:
```
protected override void OnStartup(StartupEventArgs e)
{
Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(Application_DispatcherUnhandledException);
}
```
I few rows below I created the method:
```
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
//TODO: StackTrace
MessageBox.Show("An unhandled exception just occurred: " + e.Exception.Message + e.Exception.Data, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
```
Is that all I need?
In my MainView code-behind file I create a exception:
```
private void Button_Click(object sender, RoutedEventArgs e)()
{
string asd = null;
asd.Trim();
}
```
After executing my programm still crash with a System.NullReferenceException, because the string `asd` is null. What did I wrong.<issue_comment>username_1: The problem is that, as error log suggests, you are calling `member function` i.e. `getInstance` without any instance. Function `std::unique_ptrgetInstance(int log);` should be declared as `static`.
Declare it `static` as follow:
```
static std::unique_ptrgetInstance(int log);
```
**Note:** In *singleton pattern* `getInstance` function is always static function.
Following is an extract from [Wikipedia](https://en.wikipedia.org/wiki/Singleton_pattern):
>
> An implementation of the singleton pattern must:
>
>
> * ensure that only one instance of the singleton class ever exists; and
> * provide global access to that instance.
>
>
> Typically, this is done by:
>
>
> * declaring all constructors of the class to be private; and
> * providing a static method that returns a reference to the instance.
>
>
> The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called.
>
>
>
Upvotes: 0 <issue_comment>username_2: First, the static issue. This:
```
std::unique_ptrgetInstance(int log);
```
is an instance method. You need an instance of `A` to call it on, but you can't get an instance of `A` without calling this method first, so ...
The reason for using instance methods is that they have access to the instance they're invoked on. Your method only uses the following members:
```
static bool instanceFlag;
static std::unique_ptrsingle;
```
which, since they're static, don't need an instance. Just make the method static too, and you'll be able to call it without first getting an `A` from somewhere.
---
Second, the logic issue. Your `getInstance` method returns a `unique_ptr` to your single instance. The entire point of `unique_ptr` is that's it's *unique*: exactly one pointer owns and controls the lifetime of an object. When you returned a `unique_ptr`, you *transferred ownership* of the singleton object from the singleton class itself, to the caller. You even explicitly called `move` to make it really clear that this is happening.
Now, after calling `getInstance` once, your singleton is completely broken. If you call `getInstance` again, the singleton believes it has an instance (because `instanceFlag`), but the `unique_ptr` is in an indeterminate state. The only thing we can say for sure is that it *doesn't* control an instance of `A`.
Just return a raw pointer (or reference) to `A` instead of transferring ownership.
Upvotes: 3 <issue_comment>username_3: Short answer: Don't use singletons.
Long answer: `std::make_unique()` uses constructor of an object it tries to create, and in your code it's private. Since it is an external function, it's not possible. You can create an object on your own and pass it to `std::unique_ptr` to manage, like you do on the line below the commented one.
The most important problem is, when you do `std::move()`, your class member `single` is gone. It becomes empty `unique_ptr` (aka. `std::unique_ptr{}`, it doesn't manage anything). With any next call to `getInstance`, you're essentially returning `nullptr`. You should use `std::shared_ptr`, which you'll want to return by copy or return reference to your `std::unique_ptr`.
Upvotes: 3 [selected_answer]<issue_comment>username_4: Even after making the `getInstance` static, it won't compile because the definition for destructor is missing. Either give empty definition or leave it as default.
`~A() = default;`
Moving `single` will work first time and invokes UB for subsequent calls to `getInstance`. Instead return by reference `&` and remove `std::move`
`static std::unique_ptr& getInstance(int log);`
```
std::unique_ptr& A::getInstance(int log)
{
if(!instanceFlag)
{
//single = std::make\_unique(log);
single = std::unique\_ptr(new A(log));
instanceFlag = true;
return single;
}
else
{
return single;
}
}
```
Inside `main()` you can get by reference
`std::unique_ptr& mA = A::getInstance(5);`
Upvotes: 2 |
2018/03/21 | 628 | 1,762 | <issue_start>username_0: I want to create a multidimensionnale array using a for loop.
The result i need is :
```
[
[1, 2, 3],
[4,5,6],
[7,8,9]
]
```
So how can i loop from 1 to 10 and each 3 numbers i create a new array ?
I don't find a solution.. Thanks a lot for your help<issue_comment>username_1: ```
var c = 1;
for(var i = 0; i < 3; i++)
for(var j = 0; j < 3; j++)
array[i][j] = ++c;
```
Upvotes: 0 <issue_comment>username_2: This should be what you're looking for:
```js
var outer = [];
var inner = [];
for (var i = 1; i < 10; i++) {
inner.push(i);
if (inner.length == 3) {
outer.push(inner);
inner = [];
}
}
if (inner.length > 0) outer.push(inner);
console.log(outer);
```
Remove the `if` after the loop, if you don't want any elements with less than 3 inner elements.
Upvotes: 2 <issue_comment>username_3: You could take a single loop and use a variable for the first index of the 2D array.
```js
var i, r, array = [];
for (i = 0; i < 9; i++) {
r = Math.floor(i / 3);
array[r] = array[r] || [];
array[r].push(i + 1);
}
console.log(array);
```
Upvotes: 0 <issue_comment>username_4: This *might* be the simplest solution:
```js
const result = [];
for(let i = 1; i < 10; i = i + 3) {
result.push([i, i+1, i+2]);
}
console.log(result);
```
If you're sure you want 3 consecutive numbers, you can loop from 1 to 10 skipping 3 every time, so your `i` inside `for` loop would be `1`, then `4` and then `7` in last iteration. With every iteration you create `[i, i+1, i+2]` array on the spot and push it to `result` array. However this solution is based on above conditions. It works well for `10`, for *any* number it would require additional `if` statement inside `for` loop.
Upvotes: 1 |
2018/03/21 | 518 | 1,740 | <issue_start>username_0: I have problem in my controller with optional params in requestmapping, look on my controller below:
```
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity> getBooks() {
return ResponseEntity.ok().body(booksService.getBooks());
}
@GetMapping(
produces = MediaType.APPLICATION\_JSON\_VALUE,
params = {"from", "to"}
)
public ResponseEntity>getBooksByFromToDate(
@RequestParam(value = "from", required = false) String fromDate,
@RequestParam(value = "to", required = false) String toDate)
{
return ResponseEntity.ok().body(bookService.getBooksByFromToDate(fromDate, toDate));
}
```
Now, when I send request like:
```
/getBooks?from=123&to=123
```
it's ok, request goes to "getBooksByFromToDate" method
but when I use send something like:
```
/getBooks?from=123
```
or
```
/getBooks?to=123
```
it goes to "getAlerts" method
Is it possible to make optional params = {"from", "to"} in @RequestMapping ? Any hints?<issue_comment>username_1: Just use `defaultValue` as explained in [the Spring's docs](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html#defaultValue--):
>
> ### defaultValue
>
>
> The default value to use as a fallback when the request parameter is
> not provided or has an empty value.
>
>
>
Upvotes: 2 <issue_comment>username_2: Use the default values. Example:-
```
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity> getBooksByFromToDate(@RequestParam(value = "from", required = false, defaultValue="01/03/2018") String fromDate, @RequestParam(value = "to", required = false, defaultValue="21/03/2018") String toDate) {
....
}
```
Upvotes: 3 |
2018/03/21 | 2,047 | 6,345 | <issue_start>username_0: I have to do a procedure that add plus 1 to the previous value every time its is called in PL/SQL language. But I don't know how to do that.
I mean, if the procedure is call "plus1":
First execution:
```
exec plus1
```
will return value 1.
Second execution:
```
exec plus1
```
will return value 2.
And go on<issue_comment>username_1: I've answered a similar question recently (have a look [here](https://stackoverflow.com/questions/49380437/how-to-use-oracle-db-sequences-without-losing-the-next-sequence-number-in-case-o/49382283#49382283)); basically, you need to store *current* value somewhere (a table might be a good choice) and create a function (or, in your case, a procedure) that returns the next number.
How to convert the function I wrote to a procedure? Use it as a wrapper.
Here's the whole example:
```
SQL> CREATE TABLE broj (redni_br NUMBER NOT NULL);
Table created.
SQL>
SQL> CREATE OR REPLACE FUNCTION f_get_broj
2 RETURN NUMBER
3 IS
4 PRAGMA AUTONOMOUS_TRANSACTION;
5 l_redni_br broj.redni_br%TYPE;
6 BEGIN
7 SELECT b.redni_br + 1
8 INTO l_redni_br
9 FROM broj b
10 FOR UPDATE OF b.redni_br;
11
12 UPDATE broj b
13 SET b.redni_br = l_redni_br;
14
15 COMMIT;
16 RETURN (l_redni_br);
17 EXCEPTION
18 WHEN NO_DATA_FOUND
19 THEN
20 LOCK TABLE broj IN EXCLUSIVE MODE;
21
22 INSERT INTO broj (redni_br)
23 VALUES (1);
24
25 COMMIT;
26 RETURN (1);
27 END f_get_broj;
28 /
Function created.
SQL>
SQL> CREATE PROCEDURE p_get_Broj
2 AS
3 BEGIN
4 DBMS_OUTPUT.put_line (f_get_broj);
5 END;
6 /
Procedure created.
SQL>
SQL> EXEC p_get_broj;
PL/SQL procedure successfully completed.
SQL> set serveroutput on
SQL> EXEC p_get_broj;
2
PL/SQL procedure successfully completed.
SQL> EXEC p_get_broj;
3
PL/SQL procedure successfully completed.
SQL> EXEC p_get_broj;
4
PL/SQL procedure successfully completed.
```
Upvotes: 0 <issue_comment>username_2: The best way is to create a sequence, as noticed in comments:
```
create sequence my_seq;
```
To call the sequence in PL/SQL:
```
my_var := my_seq.nextval;
```
To call in SQL:
```
select t.*, my_seq.nextval from table t;
```
In the SQL query, a new value will be generated for each line.
If you don't need a sequence, and you don't need to store the value between sessions, create a package:
```
create or replace package my_package as
function get_next_value return number;
end my_package;
/
create or replace package body my_package as
current_num number := 0;
function get_next_value return number is
begin
current_num := current_num + 1;
return current_num;
end;
end my_package;
/
```
And then call `my_package.get_next_value`.
Upvotes: 2 <issue_comment>username_3: It is not entirely clear what you need. Here is one approach, assuming you need a session variable, initialized to zero at the start of the session, which you can call as needed, and is increased only when a procedure is executed. This is different from a function that increments the variable and returns it at the same time.
If you need to access the variable in SQL (rather than just in PL/SQL), you need to write a wrapper function that returns the value; I included the wrapper function in the code below.
```
create or replace package silly_p as
v number := 0;
function show_v return number;
procedure increment_v;
end;
/
create or replace package body silly_p as
function show_v return number is
begin
return v;
end show_v;
procedure increment_v is
begin
v := v+1;
end increment_v;
end silly_p;
/
```
Here is a SQL\*Session demonstrating the compilation of this package and then its use - I access the variable both through SQL SELECT and from PL/SQL (with DBMS\_OUTPUT) to demonstrate both access methods. Notice how the value is unchanged between calls to the procedure, and increases by one every time the procedure is executed.
```
SQL> create or replace package silly_p as
2 v number := 0;
3 function show_v return number;
4 procedure increment_v;
5 end;
6 /
Package created.
Elapsed: 00:00:00.03
SQL>
SQL> create or replace package body silly_p as
2 function show_v return number is
3 begin
4 return v;
5 end show_v;
6 procedure increment_v is
7 begin
8 v := v+1;
9 end increment_v;
10 end silly_p;
11 /
Package body created.
Elapsed: 00:00:00.00
SQL> select silly_p.show_v from dual;
SHOW_V
----------
0
1 row selected.
Elapsed: 00:00:00.00
SQL> exec dbms_output.put_line(silly_p.v)
0
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.01
SQL> exec silly_p.increment_v
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.04
SQL> select silly_p.show_v from dual;
SHOW_V
----------
1
1 row selected.
Elapsed: 00:00:00.14
SQL> exec silly_p.increment_v
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.07
SQL> exec dbms_output.put_line(silly_p.v)
2
PL/SQL procedure successfully completed.
Elapsed: 00:00:00.07
SQL>
```
Upvotes: 1 <issue_comment>username_4: I believe you need a session a variable like mathguy's assumption above. You can try below code and understand how it works. Note that each DB session could have different value to the NUM\_VAR variable in var\_pkg package depending on how many times the procedure below was executed for each session.
```
CREATE OR REPLACE PACKAGE var_pkg
IS
num_var NUMBER := 0;
PROCEDURE set_num_var(p_number NUMBER);
FUNCTION get_num_var RETURN NUMBER;
END;
/
CREATE OR REPLACE PACKAGE BODY var_pkg
IS
PROCEDURE set_num_var(p_number NUMBER)
IS
BEGIN
num_var := p_number;
END;
FUNCTION get_num_var RETURN NUMBER
IS
BEGIN
RETURN num_var;
END;
END;
/
CREATE PROCEDURE plus1
IS
v_num NUMBER;
BEGIN
v_num := var_pkg.get_num_var + 1;
var_pkg.set_num_var(v_num);
DBMS_OUTPUT.PUT_LINE(v_num);
END;
/
```
To run the procedure,
```
exec plus1;
```
or
```
BEGIN
plus1;
END;
/
```
And in case you want to know the current value of the variable, you can query it using below code,
```
SELECT var_pkg.get_num_var
FROM dual;
```
Upvotes: 0 |
2018/03/21 | 343 | 1,483 | <issue_start>username_0: When in (unit) test stage I'm running the following commands:
```
echo "Installing Node Modules"
npm install
echo "Run Unit Tests"
npm run test-mocha
```
My problem is that I cannot access the VCAP\_SERVICES in the test stage (job is set to unit test).
Is there a way to access / pass them?<issue_comment>username_1: The only way I see, is using the cf cli over the provided shell in that stage. But that would require authentication and you do not want to store your user date there for sure.
So one way would be to store the data in the provided environment tab for that stage. Then you have to adapt these data, in case something is changed, because it is not provided by the vcap file but that seems to be how it is for the test stage at least.
Upvotes: 1 <issue_comment>username_2: As already mentioned, the best way to use `VCAP_SERVICES` in the test stage is to set it yourself in the stage's Environment Properties configuration.
The pipeline is the build environment. It needs to be able to run even if the app is not yet deployed or has crashed. We sometimes copy in values from the runtime environment, but the build environment should minimize its dependencies on the runtime environment wherever possible.
There's also the question of the pipeline workers being able to access the runtime services specified in `VCAP_SERVICES`. For the services I've used in my pipelines it has always worked, but it's not a guaranteed thing.
Upvotes: 0 |
2018/03/21 | 1,153 | 3,873 | <issue_start>username_0: I am really confused about the keyword "this" and without "this" on classes, because i think it is the same :
```
public class thisthing {
public int a;
public arrays(){
a=1;
}
public void A(){
this.a=10;
}
public void printa(){
System.out.println(a);
System.out.println(this.a);
}
}
```
if I call `printa` without calling `A()` I get this results :
```
1
1
```
but if i do the same with calling `A()` :
```
10
10
```
What is the difference between these two?<issue_comment>username_1: Here there is no difference. For a difference, you would need a ***local*** variable with that name. For example,
```
public void printa(int a){
System.out.println(a); // the argument a
System.out.println(this.a); // the field a
}
```
Upvotes: 2 <issue_comment>username_2: this is used to say you want the "a" from the class, not the parameter
```
public void printa(int a){
System.out.println(a); //print the parameter of function
System.out.println(this.a); //print the attribute of the class
}
```
for example, if you call `printa(2)` :
```
2
1
```
Upvotes: 0 <issue_comment>username_3: `this` refers to the current object - the instance of the class in whose method is the scope.
In the scope of the method you could see local variables, member variables and static variables. If you have a name collision between a local variable and member variable you could use `this` to differentiate between the two - you explicitly state that you work with the member variable.
In case you don't have a local variable with matching name you could not use the `this` reference - the member variable would be recognised easily.
Example:
```
new MyClass().printAVar(1);
class MyClass {
private int x = 2;
public void printAVar(int x) {
// this.x == 2;
// x == 1;
}
}
```
Upvotes: 1 <issue_comment>username_4: >
> What is the difference between these two?
>
>
>
If an identifier unambiguously refers to an instance variable in the class, there is no difference between using `this` and not. However, if the instance variable is shadowed by a local variable or a function argument, using `this` forces the compiler to use the instance variable instead. For example
```
public class Main
{
int a = 1;
void bar(int a)
{
System.out.println("local " + a);
System.out.println("instance " + this.a);
}
public static void main(String[] args)
{
new Main().bar(2);
}
}
```
Prints
```
local 2
instance 1
```
I find this is most useful when assigning values in a constructor. You don't have to think of new variable names for the constructor arguments.
```
public class Main {
int a;
Main(int a)
{
this.a = a; // Assigns the instance variable from the argument
}
void bar(int a)
{
System.out.println("local " + a);
System.out.println("instance " + this.a);
}
public static void main(String[] args)
{
new Main(3).bar(2);
}
}
```
Prints
```
local 2
instance 3
```
Upvotes: 1 <issue_comment>username_5: "this" is a keyword.
"this" is a reference variable that refers to the current object.
without "this"
```
class Student{
String name;
void data(String name){
name=name;
}
void disp(){
System.out.println("Name:"+name);
}
public static void main(String args[]){
Student s1=new Student();
s1.data("A");
s1.disp();
}}
```
Output
```
Output:- Name:null
```
Now using "this" keyword
```
class Student {
String name;
void data(String name){
this.name=name;
}
void disp(){
System.out.println("Name:"+name);
}
public static void main(String args[]){
Student s1=new Student();
s1.data("A");
s1.disp();
}}
```
Now Output will be
```
Output:- Name:A
```
Upvotes: 1 |
2018/03/21 | 782 | 3,327 | <issue_start>username_0: As it was mentioned here <https://restfulapi.net/http-methods/> (and in other places as well):
>
> GET APIs should be idempotent, which means that making multiple
> identical requests must produce same result everytime until another
> API (POST or PUT) has changed the state of resource on server.
>
>
>
How to make this true in an API that return time for example? or that return data that is affected by time.
In other words, each time I use `GET http://ip:port/get-time-now/`, it is going to return a different response. However, I did not send any `POST` or `PUT` between two sequenced `GET's`
Does this make the previous statement wrong? Did I misunderstand something?<issue_comment>username_1: Idempotency is a promise to clients/intermediaries that the request can be reissued in case of network failures or the like without any further considerations and not so much that the data will never change.
If you take a `POST` request for example, in case of a network failure you do not know if the previous request reached the server but the response got lost midway or if the initial request didn't even reach the server at all. If you re-issue the request you might create a further resource actually, hence `POST` is not idempotent. `PUT` on the other side has the contract that it replaces the current representation with the one contained in the request. If you send the same request twice the content of the resource should be the same after any of the two `PUT` requests was processed. Note that the actual result can still differ as the service is free to modify the received entity to a corresponding representation. Also, between sending the data via `PUT` and retrieving it via `GET` a further client could have updated the state in between, so there is no guarantee that you will actually receive the exact representation you've sent to the service.
Safetiness is an other promise that only `GET`, `HEAD` and `OPTIONS` supports. It promises the invoker that it wont modify any state at all hence clients/intermediaries are safe on issuing such request without having to fear that it will modify any state. In practice this is an important promise to crawlers which blindly invoke any URLs in order to learn their content. In case of violating such promises, i.e. by deleting data while processing a `GET` request the only one to blame is the service implementor but not the invoker. If a crawler invokes such URLs and hence removes some data it is not the crawlers fault actually but only the service implementor.
As you have a dynamic value in your response, you might want to prevent caching of responses though as otherwise intermediaries might return an old state for your resource
Upvotes: 2 [selected_answer]<issue_comment>username_2: The main basic concept of **idempotent** and **safe** methods of HTTP:-
**Idempotent Method:-** The method can called multiple times with same input and it produce same result.
**Safe Method:-** The method can called multiple times with same input and it doesn't modify the resource onto the server side.
Http methods are categorized into following 3 groups-
1. GET,HEAD,OPTIONS are **safe** and **idempotent**
2. PUT,DELETE are **not safe** but **idempotent**
3. POST,PATCH are **neither safe** & **nor idempotent**
Upvotes: 0 |
2018/03/21 | 667 | 2,128 | <issue_start>username_0: I get three dates: *From date*, *To date* and *current date*.
I want to find whether current date is in between From and To dates. If current date is in between these two dates then I want to create two new From and To dates.
**Example:**
* From Date = 15 march
* To Date = 25 march
* current date = 21 march
Expected result should be:
1. From Date= 15 march, To Date=21 march
2. From date= 21 march, To Date=25 march
To implement this logic I want to check my current date status whether it's in middle of date range or it's before or after.<issue_comment>username_1: Try something like this :
```
ArrayList dates = new ArrayList<>();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString1 = "2017-02-15";
String dateString2 = "2015-03-12";
String dateString3 = "2016-07-19";
Date date1 = null,date2=null,date3=null;
try {
date1 = sdf.parse(dateString1);
date2 = sdf.parse(dateString2);
date3 = sdf.parse(dateString3);
} catch (ParseException e) {
e.printStackTrace();
}
dates.add(date1);
dates.add(date2);
dates.add(date3);
Collections.sort(dates, new Comparator() {
public int compare(Date d1, Date d2) {
return d1.compareTo(d2);
}
});
```
Upvotes: 0 <issue_comment>username_2: You said in the comments that your inputs are *"in date format"*, but that's a very vague description, because, technically speaking, [`Date` objects don't have a format](https://codeblog.jonskeet.uk/2017/04/23/all-about-java-util-date/).
If your inputs are instances of `java.util.Date`, then just use the [methods `before`, `after` and `equals`](https://docs.oracle.com/javase/7/docs/api/java/util/Date.html#method_summary) to compare the dates.
If you're using Java 8, the [`java.time` API](https://docs.oracle.com/javase/tutorial/datetime/) is a much better choice. You can either use a `java.time.LocalDate` or even a `java.time.MonthDay`, if you don't care about the year.
Both classes have comparison methods: `isAfter`, `isBefore` and `equals`, and a `now()` method to get the current date.
With those, you have all the tools to implement your logic.
Upvotes: 1 |
2018/03/21 | 483 | 1,908 | <issue_start>username_0: I'm working on a web app with React. I am using React Router with it. I would like to add the ability to access to some protected pages with authentication. I have a back-end server running with Express. I have looked for information to implement that but it is still confusing to me.
I have look for redirection on [this page](https://reacttraining.com/react-router/web/example/auth-workflow). On this page, a fake authentication system is simulated to explain the redirection system. I would like to replace it. I have read about JWT in order to deal with that but I do not really understand how to use it...
Can I have some tips for that? I would like to have an endpoint like /login on my express server which will serve, if it is done that way, a token when the login and the passwords are correct. And I would like to use this token for handling access to restricted pages.
Thanks!<issue_comment>username_1: You can add onEnter in your router.onEnter property allows you to inspect the requested route and send the user to a different route based on parameters you define.
You can use it like this.
```
function requireAuth(nextState, replace) {
if (!loggedIn()) {
replace({
pathname: '/login'
})
}
}
function routes() {
return (
);
}
```
Upvotes: 1 <issue_comment>username_2: I have managed to get the authentification working through this link <https://hptechblogs.com/using-json-web-token-react/>
and <https://medium.com/@rajaraodv/securing-react-redux-apps-with-jwt-tokens-fcfe81356ea0> for server side.
For the first link, you have to change some lines. When you implement handleFormSubmit(), do not forget to call it with onClick on the submit button and remove "type=submit".
In AuthService, do not forget to return a Promise.Reject() in login, when there is an error.
With those changes, it had worked for me!
Upvotes: 1 [selected_answer] |
2018/03/21 | 451 | 1,815 | <issue_start>username_0: I'm trying to save object in background by using Parse.com but I can't override
```
override fun done(e: ParseException?) {
//code
}
```
I'm getting error: `Modifier 'override' is not applicable to 'local function`
In java I would use:
```
myObject.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e == null) {
myObjectSavedSuccessfully();
} else {
myObjectSaveDidNotSucceed();
}
}
});
```
Here is my whole class
```
class StarterApplication : Application() {
override fun onCreate() {
super.onCreate()
Parse.initialize(Parse.Configuration.Builder(this)
.applicationId(appID)
.clientKey(null)
.server(serverUrl)
.build()
)
var exampleObject: ParseObject = ParseObject("ExampleObject")
exampleObject.put("myString", "fwfwe")
exampleObject.saveInBackground( {
override fun done(e: ParseException?) { //here is an error //`Modifier 'override' is not applicable to 'local function`
}
})
}
}
```<issue_comment>username_1: Just do like that:
```
exampleObject.saveInBackground(object : SaveCallback {
override fun done(e: ParseException?) {
// Add your code here
}
})
```
In Java, you declare an anonymous class that extend `SaveCallback`. In Kotlin, you do this with [Object Expressions](https://kotlinlang.org/docs/reference/object-declarations.html).
Upvotes: 3 [selected_answer]<issue_comment>username_2: you can also try the simplest solution like this
```
exampleObject.saveInBackground({
//you code here
})
```
<https://kotlinlang.org/docs/reference/java-interop.html#sam-conversions>
Upvotes: 2 |
2018/03/21 | 665 | 2,456 | <issue_start>username_0: I am trying to form a string ( of length 10,000 ) with 1's and 0's based on a certain condition 'valid'.
Although I am able to do this, I am concerned about the performance and would need some help to decide on which of the below two methods would be better performant.
Method 1 (Using Stringbuilder)
```
StringBuilder output = new StringBuilder();
for( int i = 0; i < 10000; i++ )
{
if ( valid )
{
output.append( "1" );
}
else
{
output.append( "0" );
}
}
```
Method 2 (Using integer array)
```
int[] gridArray = new int[ 10000 ];
for( int i = 0; i < 10000; i++ )
{
if ( valid )
{
gridArray[i] = 1;
}
}
//Convert grid array to string output
```
Also, how *best* to convert the integer array to a String?<issue_comment>username_1: None of the above.
The best suitable class for you is [BitSet](https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html).
>
> This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.
>
>
>
By default, all bits in the set initially have the value false.
Upvotes: 1 <issue_comment>username_2: If you really want to build a string with `1`s and `0`s of a known length then the most efficient would be probably to build a charater array and create a string out of it. Something along the lines:
```
char[] result = new char[10000];
for (int index = 0; index < result.length; index++) {
result[index] = (index %2 == 0) ? '1' : '0';
}
String stringResult = new String(result);
```
`StringBuilder` (initialized with sufficient capacity) will probably have the same performance, so I'd actually took it. There is some minimal capacity, but it's not even worth mentioning.
Other structures suggested here (integer array or bitset) may be better to store your `1`s and `0`s, but they still need to be converted to a string. And that will probably require a `StringBuilder` anyway. `BitSet`, for instance, uses `StringBuilder` in its `toString()` method.
Upvotes: 3 [selected_answer] |
2018/03/21 | 1,512 | 6,188 | <issue_start>username_0: I am trying to redirect request if authorization is failed for it. I have following code:
```
class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}
public function rules(){ /* ... */}
public function failedAuthorization() {
return redirect('safepage');
}
}
```
By default I am redirected to the 403 error page, but I would like to specify some specific route. I noticed that method `failedAuthorization()` is run, but `redirect()` method does not work...
Previously this code worked well with Laravel 5.1 but I used `forbiddenResponse()` method to redirect wrong request. How can I fix it with new LTS version?<issue_comment>username_1: You can do through a middleware/policy i think. I don't know if you can do it from the validation.
You can override the function from FormRequest like this below:
```
/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
throw new AuthorizationException('This action is unauthorized.');
}
```
And redirect where you want.
Upvotes: 0 <issue_comment>username_2: Looks like it is impossible to `redirect()` directly from the custom `ValidateRequest` class. The only solution that I found is create custom exception and than handle it in the Handler class. So, now it works with following code:
**Update:** The method `redirectTo()` was updated to make solution work on Laravel 6.x and higher
**app/Requests/ValidateRequest.php**
```
class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}
public function rules(){
return [];
}
public function failedAuthorization() {
$exception = new NotAuthorizedException('This action is unauthorized.', 403);
throw $exception->redirectTo("safepage");
}
}
```
**app/Exceptions/NotAuthorizedException.php**
```
php
namespace App\Exceptions;
use Exception;
class NotAuthorizedException extends Exception
{
protected $route;
public function redirectTo($route) {
$this-route = $route;
abort(Redirect::to($route));
}
public function route() {
return $this->route;
}
}
```
and **app/Exceptions/Handler.php**
```
...
public function render($request, Exception $exception){
...
if($exception instanceof NotAuthorizedException){
return redirect($exception->route());
}
...
}
```
So, it works, but much more slower than I expected... Simple measuring shows that handling and redirecting take 2.1 s, but with Laravel 5.1 the same action (and the same code) takes only 0.3 s
Adding `NotAuthorizedException::class` to the `$dontReport` property does not help at all...
**Update**
It runs much more faster with php 7.2, it takes 0.7 s
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you are revisiting this thread because in 2021 you are looking to redirect after failed authorization here's what you can do:
1. You cannot redirect from the failedAuthorization() method because it is expected to throw an exception (check the method in the base FormRequest class that you extend), the side effect of changing the return type is the $request hitting the controller instead of being handled on FormRequest authorization level.
2. You do not need to create a custom exception class, neither meddle with the Laravel core files like editing the render() of app/Exceptions/Handler.php, which will pick up the exception you threw and by default render the bland 403 page.
3. All you need to do is throw new HttpResponseException()
In the [Laravel reference API](https://laravel.com/api/8.x/Illuminate/Http/Exceptions/HttpResponseException.html) we can see its job is to "Create a new HTTP response exception instance." and that is exactly what we want, right?
So we need to pass this Exception a $response. We can pass a redirect or JSON response!
Redirecting:
```
protected function failedAuthorization()
{
throw new HttpResponseException(response()->redirectToRoute('postOverview')
->with(['error' => 'This action is not authorized!']));
}
```
So we are creating a new instance of the HttpResponseException and we use the [response() helper](https://laravel.com/docs/8.x/helpers#method-response), which has this super helpful redirectToRoute('routeName') method, which we can further chain with the well known with() method and pass an error message to display on the front-end.
JSON:
Inspired by this [topic](https://stackoverflow.com/questions/42096014/formrequest-failed-authorization-laravel5-3-4?fbclid=IwAR3VCKFWRK5TU3sLVBkc-t8nRXeye0tZcBStlybzMY4zwRXSBTznRdw3oDU)
```
throw new HttpResponseException(response()->json(['error' => 'Unauthorized action!'], 403));
```
Thats'it.
You don't have to make ANY checks for validation or authorization in your controller, everything is done in the background before it hits the controller. You can test this by putting a dd('reached controller'); at the top of your controller method and it shouln't get trigered.
This way you keep your controller thin and separate concerns :)
Sidenote:
forbiddenResponse() has been replaced after lara 5.4 with failedAuthorization()
Upvotes: 2 <issue_comment>username_4: Answer for 2023 (Laravel v8++):
```php
php
namespace App\Http\Requests;
class MyCustomFormRequest extends Request
{
public function authorize()
{
// check your logic, and:
throw new \Illuminate\Http\Exceptions\HttpResponseException(
redirect()-route('your route')->with('error', 'your error')
);
}
}
```
`HttpResponseException` is a [renderable exception](https://laravel.com/docs/10.x/errors#renderable-exceptions), i.e. it accepts a response when created and the application will process said response - in this case redirect the browser.
The `authorize()` form request method is just one of the places where throwing it makes sense, but you can do it from almost anywhere.
Upvotes: 0 |
2018/03/21 | 1,655 | 6,485 | <issue_start>username_0: I would like to do a group\_by or aggregate. I have something like:
```
> head(affiliation_clean)
Affiliation_ID Affiliation_Name City Country
1 000001 New Mexico State University Las Cruces Las Cruces United States
2 000001 New Mexico State University Las Cruces Las Cruces
3 000001 New Mexico State University Las Cruces
4 000002 Palo Alto Research Center Incorporated Palo Alto
5 000002 Palo Alto Research Center Incorporated United States
6 000002 Palo Alto Research Center Incorporated
```
Grouping by "Affiliation\_ID" and taking the longest string of "Affiliation\_Name", "City" and "Country", I would like to get:
```
> head(affiliation_clean)
Affiliation_ID Affiliation_Name City Country
1 000001 New Mexico State University Las Cruces Las Cruces United States
2 000002 Palo Alto Research Center Incorporated Palo Alto United States
```
Thanks in advance.<issue_comment>username_1: You can do through a middleware/policy i think. I don't know if you can do it from the validation.
You can override the function from FormRequest like this below:
```
/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
throw new AuthorizationException('This action is unauthorized.');
}
```
And redirect where you want.
Upvotes: 0 <issue_comment>username_2: Looks like it is impossible to `redirect()` directly from the custom `ValidateRequest` class. The only solution that I found is create custom exception and than handle it in the Handler class. So, now it works with following code:
**Update:** The method `redirectTo()` was updated to make solution work on Laravel 6.x and higher
**app/Requests/ValidateRequest.php**
```
class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}
public function rules(){
return [];
}
public function failedAuthorization() {
$exception = new NotAuthorizedException('This action is unauthorized.', 403);
throw $exception->redirectTo("safepage");
}
}
```
**app/Exceptions/NotAuthorizedException.php**
```
php
namespace App\Exceptions;
use Exception;
class NotAuthorizedException extends Exception
{
protected $route;
public function redirectTo($route) {
$this-route = $route;
abort(Redirect::to($route));
}
public function route() {
return $this->route;
}
}
```
and **app/Exceptions/Handler.php**
```
...
public function render($request, Exception $exception){
...
if($exception instanceof NotAuthorizedException){
return redirect($exception->route());
}
...
}
```
So, it works, but much more slower than I expected... Simple measuring shows that handling and redirecting take 2.1 s, but with Laravel 5.1 the same action (and the same code) takes only 0.3 s
Adding `NotAuthorizedException::class` to the `$dontReport` property does not help at all...
**Update**
It runs much more faster with php 7.2, it takes 0.7 s
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you are revisiting this thread because in 2021 you are looking to redirect after failed authorization here's what you can do:
1. You cannot redirect from the failedAuthorization() method because it is expected to throw an exception (check the method in the base FormRequest class that you extend), the side effect of changing the return type is the $request hitting the controller instead of being handled on FormRequest authorization level.
2. You do not need to create a custom exception class, neither meddle with the Laravel core files like editing the render() of app/Exceptions/Handler.php, which will pick up the exception you threw and by default render the bland 403 page.
3. All you need to do is throw new HttpResponseException()
In the [Laravel reference API](https://laravel.com/api/8.x/Illuminate/Http/Exceptions/HttpResponseException.html) we can see its job is to "Create a new HTTP response exception instance." and that is exactly what we want, right?
So we need to pass this Exception a $response. We can pass a redirect or JSON response!
Redirecting:
```
protected function failedAuthorization()
{
throw new HttpResponseException(response()->redirectToRoute('postOverview')
->with(['error' => 'This action is not authorized!']));
}
```
So we are creating a new instance of the HttpResponseException and we use the [response() helper](https://laravel.com/docs/8.x/helpers#method-response), which has this super helpful redirectToRoute('routeName') method, which we can further chain with the well known with() method and pass an error message to display on the front-end.
JSON:
Inspired by this [topic](https://stackoverflow.com/questions/42096014/formrequest-failed-authorization-laravel5-3-4?fbclid=IwAR3VCKFWRK5TU3sLVBkc-t8nRXeye0tZcBStlybzMY4zwRXSBTznRdw3oDU)
```
throw new HttpResponseException(response()->json(['error' => 'Unauthorized action!'], 403));
```
Thats'it.
You don't have to make ANY checks for validation or authorization in your controller, everything is done in the background before it hits the controller. You can test this by putting a dd('reached controller'); at the top of your controller method and it shouln't get trigered.
This way you keep your controller thin and separate concerns :)
Sidenote:
forbiddenResponse() has been replaced after lara 5.4 with failedAuthorization()
Upvotes: 2 <issue_comment>username_4: Answer for 2023 (Laravel v8++):
```php
php
namespace App\Http\Requests;
class MyCustomFormRequest extends Request
{
public function authorize()
{
// check your logic, and:
throw new \Illuminate\Http\Exceptions\HttpResponseException(
redirect()-route('your route')->with('error', 'your error')
);
}
}
```
`HttpResponseException` is a [renderable exception](https://laravel.com/docs/10.x/errors#renderable-exceptions), i.e. it accepts a response when created and the application will process said response - in this case redirect the browser.
The `authorize()` form request method is just one of the places where throwing it makes sense, but you can do it from almost anywhere.
Upvotes: 0 |
2018/03/21 | 1,923 | 8,093 | <issue_start>username_0: I have one activity in which there is a webview. when the webview goes to a few pages and I click the back button on the device runs fine, but if I click the back button in the actionbar then return it wrong.
can I make function back button in action bar like back button in the device?
this is my code :
```
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tes_backbutton);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
view = (WebView)findViewById(R.id.wv_tes);
progressBar = (ProgressBar)findViewById(R.id.prgbarhome);
view.setWebViewClient(new WebViewClient());
view.loadUrl(URL);
view.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
view.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//Show loader on url load
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(tes_backbutton.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
progressDialog = null;
} catch (Exception exception) {
exception.printStackTrace();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Intent myIntent = new Intent(tes_backbutton.this, main_noconnect.class);
tes_backbutton.this.startActivity(myIntent);
}
});
view.canGoBack();
view.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getAction() == MotionEvent.ACTION_UP
&& view.canGoBack()) {
view.goBack();
return true;
}
return false;
}
});
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
```<issue_comment>username_1: You can do through a middleware/policy i think. I don't know if you can do it from the validation.
You can override the function from FormRequest like this below:
```
/**
* Handle a failed authorization attempt.
*
* @return void
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
protected function failedAuthorization()
{
throw new AuthorizationException('This action is unauthorized.');
}
```
And redirect where you want.
Upvotes: 0 <issue_comment>username_2: Looks like it is impossible to `redirect()` directly from the custom `ValidateRequest` class. The only solution that I found is create custom exception and than handle it in the Handler class. So, now it works with following code:
**Update:** The method `redirectTo()` was updated to make solution work on Laravel 6.x and higher
**app/Requests/ValidateRequest.php**
```
class ValidateRequest extends Request{
public function authorize(){
// some logic here...
return false;
}
public function rules(){
return [];
}
public function failedAuthorization() {
$exception = new NotAuthorizedException('This action is unauthorized.', 403);
throw $exception->redirectTo("safepage");
}
}
```
**app/Exceptions/NotAuthorizedException.php**
```
php
namespace App\Exceptions;
use Exception;
class NotAuthorizedException extends Exception
{
protected $route;
public function redirectTo($route) {
$this-route = $route;
abort(Redirect::to($route));
}
public function route() {
return $this->route;
}
}
```
and **app/Exceptions/Handler.php**
```
...
public function render($request, Exception $exception){
...
if($exception instanceof NotAuthorizedException){
return redirect($exception->route());
}
...
}
```
So, it works, but much more slower than I expected... Simple measuring shows that handling and redirecting take 2.1 s, but with Laravel 5.1 the same action (and the same code) takes only 0.3 s
Adding `NotAuthorizedException::class` to the `$dontReport` property does not help at all...
**Update**
It runs much more faster with php 7.2, it takes 0.7 s
Upvotes: 3 [selected_answer]<issue_comment>username_3: If you are revisiting this thread because in 2021 you are looking to redirect after failed authorization here's what you can do:
1. You cannot redirect from the failedAuthorization() method because it is expected to throw an exception (check the method in the base FormRequest class that you extend), the side effect of changing the return type is the $request hitting the controller instead of being handled on FormRequest authorization level.
2. You do not need to create a custom exception class, neither meddle with the Laravel core files like editing the render() of app/Exceptions/Handler.php, which will pick up the exception you threw and by default render the bland 403 page.
3. All you need to do is throw new HttpResponseException()
In the [Laravel reference API](https://laravel.com/api/8.x/Illuminate/Http/Exceptions/HttpResponseException.html) we can see its job is to "Create a new HTTP response exception instance." and that is exactly what we want, right?
So we need to pass this Exception a $response. We can pass a redirect or JSON response!
Redirecting:
```
protected function failedAuthorization()
{
throw new HttpResponseException(response()->redirectToRoute('postOverview')
->with(['error' => 'This action is not authorized!']));
}
```
So we are creating a new instance of the HttpResponseException and we use the [response() helper](https://laravel.com/docs/8.x/helpers#method-response), which has this super helpful redirectToRoute('routeName') method, which we can further chain with the well known with() method and pass an error message to display on the front-end.
JSON:
Inspired by this [topic](https://stackoverflow.com/questions/42096014/formrequest-failed-authorization-laravel5-3-4?fbclid=IwAR3VCKFWRK5TU3sLVBkc-t8nRXeye0tZcBStlybzMY4zwRXSBTznRdw3oDU)
```
throw new HttpResponseException(response()->json(['error' => 'Unauthorized action!'], 403));
```
Thats'it.
You don't have to make ANY checks for validation or authorization in your controller, everything is done in the background before it hits the controller. You can test this by putting a dd('reached controller'); at the top of your controller method and it shouln't get trigered.
This way you keep your controller thin and separate concerns :)
Sidenote:
forbiddenResponse() has been replaced after lara 5.4 with failedAuthorization()
Upvotes: 2 <issue_comment>username_4: Answer for 2023 (Laravel v8++):
```php
php
namespace App\Http\Requests;
class MyCustomFormRequest extends Request
{
public function authorize()
{
// check your logic, and:
throw new \Illuminate\Http\Exceptions\HttpResponseException(
redirect()-route('your route')->with('error', 'your error')
);
}
}
```
`HttpResponseException` is a [renderable exception](https://laravel.com/docs/10.x/errors#renderable-exceptions), i.e. it accepts a response when created and the application will process said response - in this case redirect the browser.
The `authorize()` form request method is just one of the places where throwing it makes sense, but you can do it from almost anywhere.
Upvotes: 0 |
2018/03/21 | 832 | 2,219 | <issue_start>username_0: I have a script that calculates the percentage of an input.
```
$total_debt = "16,000";
$debt_written_off_percentage = 70;
$debt_written_off = ($debt_written_off_percentage / 100) * $total_debt;
$reduced_debt_percentage = 30;
$reduced_debt = ($reduced_debt_percentage / 100) * $total_debt;
echo $total_debt;
echo '
';
echo $debt_written_off;
echo '
';
echo $reduced_debt;
echo '
';
exit();
```
When I run this script, I get the following output:
```
16,000
11.2
4.8
```
Why is it not:
```
16,000
11,200
4,800
```<issue_comment>username_1: With `error_reporting(-1)`, you'll get:
>
> Notice: A non well formed numeric value encountered in ...
>
>
>
indicating that `$total_debt` is problematic.
---
**Solution**: Use a real number value, e.g.:
```
$total_debt = 16000;
// ...
```
---
Reference: [Integers](https://php.net/manual/language.types.integer.php), [Floating point numbers](https://php.net/manual/language.types.float.php) and for what it's worth [Type Juggling](https://secure.php.net/manual/language.types.type-juggling.php).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Because your `$total_debt = "16,000";` is a string and when used it will be cast to `int` removing the comma. So use
```
$total_debt = 16000;
```
You have to format your output in order to fit your needs with:
```
function number_format ($number , $decimals = 0 , $dec_point = '.' , $thousands_sep = ',' ) {}
```
So you should replace with:
```
echo number_format($total_debt, 3, ",");
echo '
';
echo number_format($debt_written_off, 3, ",");
echo '
';
echo number_format($reduced_debt, 3, ",");
echo '
';
exit();
```
Upvotes: 1 <issue_comment>username_3: Covert your `total_debt` **string to integer** first and then you can try your logic.
```
php
$total_debt = (int)16000;
$debt_written_off_percentage = 70;
$debt_written_off = ($debt_written_off_percentage / 100) * $total_debt;
$reduced_debt_percentage = 30;
$reduced_debt = ($reduced_debt_percentage / 100) * $total_debt;
echo $total_debt;
echo '<br';
echo $debt_written_off;
echo '
';
echo $reduced_debt;
echo '
';
exit();
?>
```
Upvotes: 1 |
2018/03/21 | 821 | 2,640 | <issue_start>username_0: I have an app in iOS and am using firebase for my user login/validation etc. I want to be able to login, and if a user closes the app and then re-opens it, they are not forced to re-log in every time. Currently I have this code in my AppDelegate:
```
func setRootViewController(){
if Auth.auth().currentUser != nil {
self.presentTabBar()
} else {
self.presentLoginViewController()
}
}
func presentTabBar(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier :"myTabBar")
self.present(viewController, animated: true)
}
```
However because this is in my AppDelegate I'm getting an error on my line self.present(viewController...) saying that AppDelegate has no memeber called self. I understand that this is because self is only available to ViewControllers.
How can I implement this functionality from within my AppDelegate file?<issue_comment>username_1: With `error_reporting(-1)`, you'll get:
>
> Notice: A non well formed numeric value encountered in ...
>
>
>
indicating that `$total_debt` is problematic.
---
**Solution**: Use a real number value, e.g.:
```
$total_debt = 16000;
// ...
```
---
Reference: [Integers](https://php.net/manual/language.types.integer.php), [Floating point numbers](https://php.net/manual/language.types.float.php) and for what it's worth [Type Juggling](https://secure.php.net/manual/language.types.type-juggling.php).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Because your `$total_debt = "16,000";` is a string and when used it will be cast to `int` removing the comma. So use
```
$total_debt = 16000;
```
You have to format your output in order to fit your needs with:
```
function number_format ($number , $decimals = 0 , $dec_point = '.' , $thousands_sep = ',' ) {}
```
So you should replace with:
```
echo number_format($total_debt, 3, ",");
echo '
';
echo number_format($debt_written_off, 3, ",");
echo '
';
echo number_format($reduced_debt, 3, ",");
echo '
';
exit();
```
Upvotes: 1 <issue_comment>username_3: Covert your `total_debt` **string to integer** first and then you can try your logic.
```
php
$total_debt = (int)16000;
$debt_written_off_percentage = 70;
$debt_written_off = ($debt_written_off_percentage / 100) * $total_debt;
$reduced_debt_percentage = 30;
$reduced_debt = ($reduced_debt_percentage / 100) * $total_debt;
echo $total_debt;
echo '<br';
echo $debt_written_off;
echo '
';
echo $reduced_debt;
echo '
';
exit();
?>
```
Upvotes: 1 |
2018/03/21 | 770 | 2,262 | <issue_start>username_0: I'm very new to bootstrap so this is probably an easy question for most. I have a navbar, want two nav items and an input field to be on the left side of the navbar. With the two remaining nav items on the right. I have tried messing with the classes to make this happen and using the "float-left" and "float-right" classes but no joy :(
```
[L'amour](index.php)
* [Contact Us](order.php)
* [Testimonial](order.php)
*
* [Order Wesbite](order.php)
* [Account](#)
[Login](signIn.php)
[Sign up](sign-up)
[Account details](homeUser.php)
[Logout](logout.php)
```<issue_comment>username_1: With `error_reporting(-1)`, you'll get:
>
> Notice: A non well formed numeric value encountered in ...
>
>
>
indicating that `$total_debt` is problematic.
---
**Solution**: Use a real number value, e.g.:
```
$total_debt = 16000;
// ...
```
---
Reference: [Integers](https://php.net/manual/language.types.integer.php), [Floating point numbers](https://php.net/manual/language.types.float.php) and for what it's worth [Type Juggling](https://secure.php.net/manual/language.types.type-juggling.php).
Upvotes: 3 [selected_answer]<issue_comment>username_2: Because your `$total_debt = "16,000";` is a string and when used it will be cast to `int` removing the comma. So use
```
$total_debt = 16000;
```
You have to format your output in order to fit your needs with:
```
function number_format ($number , $decimals = 0 , $dec_point = '.' , $thousands_sep = ',' ) {}
```
So you should replace with:
```
echo number_format($total_debt, 3, ",");
echo '
';
echo number_format($debt_written_off, 3, ",");
echo '
';
echo number_format($reduced_debt, 3, ",");
echo '
';
exit();
```
Upvotes: 1 <issue_comment>username_3: Covert your `total_debt` **string to integer** first and then you can try your logic.
```
php
$total_debt = (int)16000;
$debt_written_off_percentage = 70;
$debt_written_off = ($debt_written_off_percentage / 100) * $total_debt;
$reduced_debt_percentage = 30;
$reduced_debt = ($reduced_debt_percentage / 100) * $total_debt;
echo $total_debt;
echo '<br';
echo $debt_written_off;
echo '
';
echo $reduced_debt;
echo '
';
exit();
?>
```
Upvotes: 1 |
2018/03/21 | 1,639 | 5,702 | <issue_start>username_0: My intention is to build a simple process with which I can split the word into syllables. The approach is to split the word whenever the vowel occurs. However, the trouble is when a consonant is not followed by a vowel, in such a case the split occurs at that consonant.
My test cases are as follows:
```
hair = ["hair"]
hairai = ["hai", "rai"]
hatred = ["hat", "red"]
```
In the first example hair is one syllable, as the final consonant is not followed by a vowel, similarly, in the final example, the "t" is followed by an r and so should considered along "ha" as one syllable.
In the second example, ai is considered as one vowel sound and so hai will become one syllable.
More examples include
```
father = ["fat", "her"]
kid = ["kid"]
lady = ["la","dy"]
```
Please note that, I am using simplistic examples as the ENglish language is quite complex when it comes to sound
My code is as follows
```js
function syllabify(input) {
var arrs = [];
for (var i in input) {
var st = '';
var curr = input[i];
var nxt = input[i + 1];
if ((curr == 'a') || (curr == 'e') || (curr == 'i') || (curr == 'o') || (curr == 'u')) {
st += curr;
} else {
if ((nxt == 'a') || (nxt == 'e') || (nxt == 'i') || (nxt == 'o') || (nxt == 'u')) {
st += nxt;
} else {
arrs.push(st);
st = '';
}
}
}
console.log(arrs);
}
syllabify('hatred')
```
However, my code does not even return the strings. What am I doing wrong?<issue_comment>username_1: Problems with your current approach
===================================
There are a number of problems with your code:
* First thing in the loop, you set `st` to an empty string. This means that you never accumulate any letters. You probably want that line above, *outside* the loop.
* You are trying to loop over the indexes of letters by using `i in input`. In JavaScript, the `in` keyword gives you the keys of an object as strings. So you get strings, not numbers, plus the names of some methods defined on strings. Try `var i = 0; i < input.length; i++` instead.
* Maybe not the direct cause of the problems, but still - your code is messy. How about these?
+ Use clearer names. `currentSyllable` instead of `st`, `syllables` instead of `arrs` and so on.
+ Instead of a nested `if` - `else`, use one `if` - `else if` - `else`.
+ You repeat the same code that checks for vowels twice. Separate it into a function `isVowel(letter)` instead.
A new approach
==============
Use [regular expressions](https://www.regular-expressions.info/tutorial.html)! Here is your definition of a syllable expressed in regex:
* First, zero or more consonants: `[^aeiouy]*`
* Then, one or more vowels: `[aeiouy]+`
* After that, zero or one of the following:
+ Consonants, followed by the end of the word: `[^aeiouy]*$`
+ A consonant (if it is followed by another consonant): `[^aeiouy](?=[^aeiouy])`
Taken together you get this:
```
/[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?/gi
```
You can see it in action [here](https://regex101.com/r/At64WO/1). To run it in JavaScript, use the [`match`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) function:
```js
const syllableRegex = /[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?/gi;
function syllabify(words) {
return words.match(syllableRegex);
}
console.log(['away', 'hair', 'halter', 'hairspray', 'father', 'lady', 'kid'].map(syllabify))
```
Note that this does not work for words without vowels. You would either have to modify the regex to accomodate for that case, or do some other workaround.
Upvotes: 4 <issue_comment>username_2: I am weak in the ways of RegEx and while username_1 example is right most of the time, I did find a few exceptions. Here is what I have found to work so far (but I am sure there are other exceptions I have not found yet). I am sure it can be RegEx'ified by masters of the art. This function returns an array of syllables.
```
function getSyllables(word){
var response = [];
var isSpecialCase = false;
var nums = (word.match(/[aeiou]/gi) || []).length;
//debugger;
if (isSpecialCase == false && (word.match(/[0123456789]/gi) || []).length == word.length ){
// has digits
response.push(word);
isSpecialCase = true;
}
if (isSpecialCase == false && word.length < 4){
// three letters or less
response.push(word);
isSpecialCase = true;
}
if (isSpecialCase == false && word.charAt(word.length-1) == "e"){
if (isVowel(word.charAt(word.length-2)) == false){
var cnt = (word.match(/[aeiou]/gi) || []).length;
if (cnt == 3){
if (hasDoubleVowels(word)){
// words like "piece, fleece, grease"
response.push(word);
isSpecialCase = true;
}
}
if (cnt == 2){
// words like "phase, phrase, blaze, name",
if (hasRecurringConsonant(word) == false) {
// but not like "syllable"
response.push(word);
isSpecialCase = true;
}
}
}
}
if (isSpecialCase == false){
const syllableRegex = /[^aeiouy]*[aeiouy]+(?:[^aeiouy]*$|[^aeiouy](?=[^aeiouy]))?/gi;
response = word.match(syllableRegex);
}
return response;
}
```
Upvotes: 0 |
2018/03/21 | 1,252 | 4,606 | <issue_start>username_0: I have the following *PDF template* which should be consistent for all the *pages* that gets added in the PDF I am creating ,
[](https://i.stack.imgur.com/vDSNj.png)
The issue is that, am getting this template only for *Page 1* and for rest of the pages only **blank template** is used , Here's the code am using right now,
```
PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC),new PdfWriter(baosPDF));
PageSize ps = new PageSize(900, 780);
// Initialize document
Document document = new Document(pdfDoc, ps);
document.setMargins(80f, 20f, 50f, 20f);
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA);
PdfFont bold = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
for(int i = 0; i < 10; i++){
document.add(new Paragraph("Some Content"));
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
}
document.close();
```
I have referred this [itextsharp add 1 page template to all pages](https://stackoverflow.com/questions/16917433/itextsharp-add-1-page-template-to-all-pages) example already , but I need something specific to Itext 7 since it varies a lot from 5.x.x versions
how do I get my PDF to have the single template as shown in image to be common for all the pages ?<issue_comment>username_1: As explained in the comments, you need to create an `IEventHandler` as described in [chapter 7 of the tutorial](https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-7-handling-events-setting-viewer-preferences-and-writer-properties)
This is an example from the PDF to HTML tutorial ([chapter 4](https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml)).
```
class Background implements IEventHandler {
PdfXObject stationery;
public Background(PdfDocument pdf, String src) throws IOException {
PdfDocument template = new PdfDocument(new PdfReader(src));
PdfPage page = template.getPage(1);
stationery = page.copyAsFormXObject(pdf);
template.close();
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.addXObject(stationery, 0, 0);
Rectangle rect = new Rectangle(36, 32, 36, 64);
Canvas canvas = new Canvas(pdfCanvas, pdf, rect);
canvas.add(
new Paragraph(String.valueOf(pdf.getNumberOfPages()))
.setFontSize(48).setFontColor(Color.WHITE));
canvas.close();
}
}
```
As you can see, we read the template in the constructor, and we draw it to the Canvas in the `handleEvent()` method. In this example, we also add a page number in white, you can remove all those lines.
```
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.addXObject(stationery, 0, 0);
}
```
Obviously, you also need to declare the handler:
```
PdfDocument pdf = new PdfDocument(writer);
IEventHandler handler = new Background(pdf, stationery);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: .Net(C#) version of the code:
```
//Call the handler before multiple page generation
PdfDocument pdfDocument = new PdfDocument(writer);
IEventHandler handler = new Background(pdfDocument, @"YourTemplateFilePath");
pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
public class Background : IEventHandler
{
PdfXObject stationery;
public Background(PdfDocument pdf, String src)
{
PdfDocument template = new PdfDocument(new PdfReader(src));
PdfPage page = template.GetPage(1);
stationery = page.CopyAsFormXObject(pdf);
template.Close();
}
public void HandleEvent(Event @event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(), page.GetResources(), pdf);
pdfCanvas.AddXObjectAt(stationery, 0, 0);
}
}
```
Upvotes: 0 |
2018/03/21 | 920 | 3,549 | <issue_start>username_0: I would like to start the program from this repository:
<https://github.com/SaifurRahmanMohsin/Personal-Diary>
but when I dowload or clone it there is no Install file or no command in the readme file to compile it.
How do I use it?<issue_comment>username_1: As explained in the comments, you need to create an `IEventHandler` as described in [chapter 7 of the tutorial](https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-7-handling-events-setting-viewer-preferences-and-writer-properties)
This is an example from the PDF to HTML tutorial ([chapter 4](https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml)).
```
class Background implements IEventHandler {
PdfXObject stationery;
public Background(PdfDocument pdf, String src) throws IOException {
PdfDocument template = new PdfDocument(new PdfReader(src));
PdfPage page = template.getPage(1);
stationery = page.copyAsFormXObject(pdf);
template.close();
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.addXObject(stationery, 0, 0);
Rectangle rect = new Rectangle(36, 32, 36, 64);
Canvas canvas = new Canvas(pdfCanvas, pdf, rect);
canvas.add(
new Paragraph(String.valueOf(pdf.getNumberOfPages()))
.setFontSize(48).setFontColor(Color.WHITE));
canvas.close();
}
}
```
As you can see, we read the template in the constructor, and we draw it to the Canvas in the `handleEvent()` method. In this example, we also add a page number in white, you can remove all those lines.
```
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.addXObject(stationery, 0, 0);
}
```
Obviously, you also need to declare the handler:
```
PdfDocument pdf = new PdfDocument(writer);
IEventHandler handler = new Background(pdf, stationery);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: .Net(C#) version of the code:
```
//Call the handler before multiple page generation
PdfDocument pdfDocument = new PdfDocument(writer);
IEventHandler handler = new Background(pdfDocument, @"YourTemplateFilePath");
pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
public class Background : IEventHandler
{
PdfXObject stationery;
public Background(PdfDocument pdf, String src)
{
PdfDocument template = new PdfDocument(new PdfReader(src));
PdfPage page = template.GetPage(1);
stationery = page.CopyAsFormXObject(pdf);
template.Close();
}
public void HandleEvent(Event @event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(), page.GetResources(), pdf);
pdfCanvas.AddXObjectAt(stationery, 0, 0);
}
}
```
Upvotes: 0 |
2018/03/21 | 1,675 | 7,018 | <issue_start>username_0: I have an applicaton that implements a listener for smartcards reader.
When I run the application I send it to tray.
When the aplication detects a card I want it to restore the jFrame back to normal so the user can select the options available on the screen.
Problem is when I try to restore the window it creates a new one.
How is possible to restore the jFrame back to normal.
This code is what I have inside the jFrame constructor:
It creates the tray Icon and the options Close and Open. But I want it to open automatically. Is it possible to programatically click the Open option?
```
initComponents();
setResizable(false);
setLocationRelativeTo(null);
setTitle("App Title");
UFRInstance = (uFrFunctions) Native.loadLibrary(GetLibFullPath(false), uFrFunctions.class);
this.wsc = new WebSocketConnection();
System.out.println("creating instance");
try {
System.out.println("setting look and feel");
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.out.println("Unable to set LookAndFeel");
}
if (SystemTray.isSupported()) {
System.out.println("system tray supported");
tray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage("bulb.png");
ActionListener exitListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Exiting....");
System.exit(0);
}
};
PopupMenu popup = new PopupMenu();
MenuItem defaultItem = new MenuItem("Close");
defaultItem.addActionListener(exitListener);
popup.add(defaultItem);
defaultItem = new MenuItem("Open");
defaultItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(true);
setExtendedState(JFrame.NORMAL);
}
});
popup.add(defaultItem);
trayIcon = new TrayIcon(createIcon("bulb.png", "Icon"), "SystemTray Demo", popup);
trayIcon.setImageAutoSize(true);
} else {
System.out.println("system tray not supported");
}
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent e) {
if (e.getNewState() == ICONIFIED) {
try {
tray.add(trayIcon);
setVisible(false);
System.out.println("added to SystemTray");
} catch (AWTException ex) {
System.out.println("unable to add to tray");
}
}
if (e.getNewState() == 7) {
try {
tray.add(trayIcon);
setVisible(false);
System.out.println("added to SystemTray");
} catch (AWTException ex) {
System.out.println("unable to add to system tray");
}
}
if (e.getNewState() == MAXIMIZED_BOTH) {
tray.remove(trayIcon);
setVisible(true);
System.out.println("Tray icon removed");
}
if (e.getNewState() == NORMAL) {
tray.remove(trayIcon);
setVisible(true);
System.out.println("Tray icon removed1");
}
}
});
setIconImage(Toolkit.getDefaultToolkit().getImage("bulb.png"));
setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("bulb.png")));
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
```<issue_comment>username_1: As explained in the comments, you need to create an `IEventHandler` as described in [chapter 7 of the tutorial](https://developers.itextpdf.com/content/itext-7-building-blocks/chapter-7-handling-events-setting-viewer-preferences-and-writer-properties)
This is an example from the PDF to HTML tutorial ([chapter 4](https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml)).
```
class Background implements IEventHandler {
PdfXObject stationery;
public Background(PdfDocument pdf, String src) throws IOException {
PdfDocument template = new PdfDocument(new PdfReader(src));
PdfPage page = template.getPage(1);
stationery = page.copyAsFormXObject(pdf);
template.close();
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.addXObject(stationery, 0, 0);
Rectangle rect = new Rectangle(36, 32, 36, 64);
Canvas canvas = new Canvas(pdfCanvas, pdf, rect);
canvas.add(
new Paragraph(String.valueOf(pdf.getNumberOfPages()))
.setFontSize(48).setFontColor(Color.WHITE));
canvas.close();
}
}
```
As you can see, we read the template in the constructor, and we draw it to the Canvas in the `handleEvent()` method. In this example, we also add a page number in white, you can remove all those lines.
```
public void handleEvent(Event event) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
PdfDocument pdf = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.newContentStreamBefore(), page.getResources(), pdf);
pdfCanvas.addXObject(stationery, 0, 0);
}
```
Obviously, you also need to declare the handler:
```
PdfDocument pdf = new PdfDocument(writer);
IEventHandler handler = new Background(pdf, stationery);
pdf.addEventHandler(PdfDocumentEvent.START_PAGE, handler);
```
Upvotes: 3 [selected_answer]<issue_comment>username_2: .Net(C#) version of the code:
```
//Call the handler before multiple page generation
PdfDocument pdfDocument = new PdfDocument(writer);
IEventHandler handler = new Background(pdfDocument, @"YourTemplateFilePath");
pdfDocument.AddEventHandler(PdfDocumentEvent.START_PAGE, handler);
public class Background : IEventHandler
{
PdfXObject stationery;
public Background(PdfDocument pdf, String src)
{
PdfDocument template = new PdfDocument(new PdfReader(src));
PdfPage page = template.GetPage(1);
stationery = page.CopyAsFormXObject(pdf);
template.Close();
}
public void HandleEvent(Event @event)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent)@event;
PdfDocument pdf = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
PdfCanvas pdfCanvas = new PdfCanvas(
page.NewContentStreamBefore(), page.GetResources(), pdf);
pdfCanvas.AddXObjectAt(stationery, 0, 0);
}
}
```
Upvotes: 0 |
2018/03/21 | 989 | 3,950 | <issue_start>username_0: How can I make a selenium Project to one exe without installation?
I want to embed chromeDriver and geckodriver into my exe.
[](https://i.stack.imgur.com/B8KfL.jpg)
Is this possible?<issue_comment>username_1: Technically, you can do what you asked for this way:
First, add ChromeDriver.exe to your project as an embedded resource (see <https://support.microsoft.com/en-us/help/319292/how-to-embed-and-access-resources-by-using-visual-c> for more details). This will embed ChromeDriver.exe directly into your compiled application.
Then when you're application starts, read the content of that resource (as a stream of bytes) and write that content to a new file. Name this file ChromeDriver.exe. This way your application "spawns" ChromeDriver.exe from within itself.
Finally, instantiate the ChromeDriver class, and pass the path to the newly created ChromeDriver.exe file.
However, while this solution looks cool, embedding ChromeDriver.exe by itself isn't enough. You also need to have all of your references, including Webdriver.dll in the same folder as your application. In fact, most.net applications can be installed just by copying a folder, but not just as a single file. Theoretically, you can also embed all of the dlls that your project needs and load then into memory when the applicator starts, but that's a huge overkill for most cases. Therefore, if deploying a folder instead of a single file is acceptable, then you can simply add ChromeDriver.exe to that output folder (by adding it to the project as a content file with the Copy Always setting), and save all the work of spawning it from the resource.
Lastly, one important note: if you embed ChromeDriver.exe as an embedded resource, you'll have harder time updating it when new version is published, than if you'd use the NuGet package that installes it as a separate file for you.
Upvotes: 1 [selected_answer]<issue_comment>username_2: Actually the process is so easy by following several steps!
* According to username_1's answer, you should put your chromedriver file as an embedded resource file to your project and create it on your application load.
You can do this from: Solution Explorer -> Properties -> (double click on) Resources.resx
a new tab will pop! then you can add your exe file like this picture:
[Adding exe file as a resource](https://i.stack.imgur.com/rkesp.png)
* In the next step you should select the added file from "Solution Explorer" and make it as an embedded resource file from "Properties" window of the selected file. This picture may help you more: [Setting a resource file as an embedded resource file](https://i.stack.imgur.com/5staZ.png)
* Then you can use the following functions to read, create and delete the driver file:
```c#
//Reading and creating the chrome driver file
void ExtractResource(string path)
{
byte[] bytes = Properties.Resources.chromedriver;
File.WriteAllBytes(path, bytes);
}
```
```c#
//Create the chromedriver file on form load
private void Form1_Load(object sender, EventArgs e)
{
string exePath = ".\\ChromeDriver.exe";
ExtractResource(exePath);
}
```
```c#
//Deleting the created file
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
File.Delete(exePath);
}
```
* Now you can refrence the ChromeDriver File when creating the ChromeDriver object using the following code:
```c#
ChromeDriver chromeDriver = new ChromeDriver(@".\\");
```
It's also better to check if the file exists or not before creating the above object!
* For the last step you should embed your dll files in your exe output. The most straightforward way to achieve this is by installing "Fody" from NuGet package manager. you can check [this link](https://github.com/Fody/Home/blob/master/pages/usage.md) for more information about adding this awesome tool to your project.
Upvotes: 1 |
2018/03/21 | 285 | 1,175 | <issue_start>username_0: I'm working on Hyper Ledger Composer and integrating the REST API in a nodejs web app "using js client side to call the API "
and I'm wondering how can I keep some interface private and prevent from show and post to it .
Should I simply call the api server side before or is there an elegant way ?<issue_comment>username_1: To protect access to the REST APIS, you can implement an authentication strategy - see here <https://hyperledger.github.io/composer/integrating/enabling-rest-authentication.html> and <https://hyperledger.github.io/composer/integrating/enabling-multiuser.html> (the latter requires that authentication is enabled).
A tutorial on using one such strategy - eg using Google OAUTH2 as an auth provider - is shown here -> <https://hyperledger.github.io/composer/next/tutorials/google_oauth2_rest>
Upvotes: 2 [selected_answer]<issue_comment>username_2: There is another way to develop your own rest api using NodeJs sdk.
You can connect to the network using Cards and perform any action using BusinessNetworkConnection class and factory object.
Read [<https://hyperledger.github.io/composer/v0.16/applications/node][1]>
Upvotes: 0 |
2018/03/21 | 351 | 1,313 | <issue_start>username_0: I am developing a full text search backend with support for Unicode.
(Database PostgreSQL 9.5, PHP7, Ubuntu 17, Apache2).
The database is correctly indexing (using tsearch) the relevant text data. So far so good.
Now I need to search the data using user-supplied search words. My first idea is to split a searchstring using `explode(" ", $rawseachstring)` and then search for the individual words, generating a resultset with best matches.
However, Unicode seems to have a whole bunch of 'space-like' characters defined, see next article:
<http://jkorpela.fi/chars/spaces.html>
After trying to understand that page (written by the Unicode guru Korpela), I wonder if splitting the string on ' ' is a bit naive.
Should one split on all possible 'space-like' characters?<issue_comment>username_1: If you expect these kind of spaces then you can use preg\_split to explode by a regex of multiple characters.
```
$words = preg_split('/regex/', $string);
```
However consider doing a query with `LIKE` keyword to get only the results that may match.
Upvotes: 0 <issue_comment>username_2: Use the [unicode property for spaces](https://en.wikipedia.org/wiki/Unicode_character_property) `\p{Zs}`
```
$words = preg_split('/\p{Zs}/u', $rawseachstring);
```
Upvotes: 2 [selected_answer] |
2018/03/21 | 558 | 2,193 | <issue_start>username_0: Problem : In collectionview cell which has player
if I play two Video simultaneously and seek first Video to end then `AVPlayerItemDidPlayToEndTime` fired for two times and both videos restarted
In collection view cell I have
```
override func awakeFromNib() {
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player?.currentItem, queue: .main, using: {[weak self] (notification) in
if self?.player != nil {
self?.player?.seek(to: kCMTimeZero)
self?.player?.play()
}
})
}
```
and one play button action which play the video.
In cell I have slider to seek.
[](https://i.stack.imgur.com/ca1eh.gif)
Any Help would be appreciated<issue_comment>username_1: Make sure that `player` and `player?.currentItem` are not equal to `nil` when you're registering for notifications. To me, it seems like one of them was nil and you're basically subscribing to all of the `.AVPlayerItemDidPlayToEndTime` notifications (since `object` is nil).
To avoid that, subscribe to the notifications right after assigning `AVAsset` to the player.
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Swift 5.1**
Pass the item as your object:
```
// Stored property
let player = AVPlayer(url: videoUrl)
// When you are adding your video layer
let playerLayer = AVPlayerLayer(player: player)
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
// add layer to view
```
Then when you get that notification, here's how you can get the `currentItem`:
```
// Grab the item from the notification object and ensure its the same item as the current players item
if let item = notification.object as? AVPlayerItem,
let currentItem = player.currentItem,
item == currentItem {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
// remove player from view or do whatever you need to do here
}
```
Upvotes: 1 |
2018/03/21 | 1,084 | 4,573 | <issue_start>username_0: This is my first question and I've been trying to find a solution to this for hours but can't get it to work. I'm building an android app that takes an input from the user (number of hours) to fast (not eat). The input is then taken to the service where it does a countdown in the background. Along the way, I'd like the user to access other activities that could you the results from the countdown timer (eg, time\_left/total\_time = percentage complete). So far, my button that I've created works to make the call for the service. but the service never gets called to update the text view. Thanks
Here is what I have,
```
public class StartFast extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start_fast);
startService(new Intent(this, MyService.class));
Log.i("Started service", "hello started service...");
registerReceiver(br, new IntentFilter("COUNTDOWN_UPDATED"));
}
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
intent.getExtras();
long millisUntilFinished = intent.getLongExtra("countdown",0);
String time = Long.toString((millisUntilFinished));
TextView tv = findViewById(R.id.timeView1);
tv.setText(time);
}
};
public void BeginFast(View view){
//Intent intent = new Intent( this, StartFast.class);
// below is how to pass an intent for use in a Service to run in the backgroun
Intent intent =new Intent(this, MyService.class);
startService(intent);
// intent.putExtra() // putExtra longs ...will do after static run succeeds
//intent.putExtra("data", data); //adding the data
Intent intent1 = new Intent(this, Heart.class);
startActivity(intent1);
}
}
```
and here is the service class,
```
public class MyService extends Service {
private final static String TAG = "MyService";
public static final String COUNTDOWN_BR = "FastBreak.countdown_br";
Intent bi = new Intent(COUNTDOWN_BR);
CountDownTimer cdt = null;
public void OnCreate(){
super.onCreate();
Log.i(TAG, "starting timer...");
cdt = new CountDownTimer(30000,1000) {
@Override
public void onTick(long millisUntilFinished){
Log.i(TAG, "Countdown seconds remaining: " +millisUntilFinished /1000);
bi.putExtra("countdown", millisUntilFinished);
sendBroadcast(bi);
}
@Override
public void onFinish(){
Log.i(TAG, "Timer finished");
}
};
cdt.start();
}
@Override
public void onDestroy() {
cdt.cancel();
Log.i(TAG, "Timer cancelled");
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
```<issue_comment>username_1: Make sure that `player` and `player?.currentItem` are not equal to `nil` when you're registering for notifications. To me, it seems like one of them was nil and you're basically subscribing to all of the `.AVPlayerItemDidPlayToEndTime` notifications (since `object` is nil).
To avoid that, subscribe to the notifications right after assigning `AVAsset` to the player.
Upvotes: 4 [selected_answer]<issue_comment>username_2: **Swift 5.1**
Pass the item as your object:
```
// Stored property
let player = AVPlayer(url: videoUrl)
// When you are adding your video layer
let playerLayer = AVPlayerLayer(player: player)
NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: .AVPlayerItemDidPlayToEndTime, object: player.currentItem)
// add layer to view
```
Then when you get that notification, here's how you can get the `currentItem`:
```
// Grab the item from the notification object and ensure its the same item as the current players item
if let item = notification.object as? AVPlayerItem,
let currentItem = player.currentItem,
item == currentItem {
NotificationCenter.default.removeObserver(self, name: .AVPlayerItemDidPlayToEndTime, object: nil)
// remove player from view or do whatever you need to do here
}
```
Upvotes: 1 |
2018/03/21 | 329 | 1,576 | <issue_start>username_0: Is it possible to restrict the purchase order created automatically like when any dropship or special offer item selected in sales order?<issue_comment>username_1: The behaviour of dropship and special order items is dependent on a checkbox. If you clear the checkbox when the order is approved then the automatic POs will not be created.
Checkbox clearing may be done by the user or may be done via a Before Submit user event script on the Sales Order.
If the need to restrict PO creation has something to do with PO vendor characteristics where you may also need to restrict general PO creation then you should extract the vendor check to a library file. that way it could be used in the SO beforeSubmit to clear the createpo flag and the PO beforeSubmit to throw an error.
You could also use the PO After Submit "specialorder" or "dropship" events to check the PO vendor after submit and delete the created PO.
However given your explanation in the comments the SO shouldn't be able to be approved. i.e. why take a drop ship order where the components are not orderable?
Upvotes: 0 <issue_comment>username_2: I can confirm as of very recent discussions and testing with Netsuite that before submit does not trigger on automatically generated purchase orders.
We have an approvals system in place and were hoping purchase orders could be auto generated and stay pending supervisor approval but this is not possible as the before submit does not trigger.
An enhancement request has been raised by Netsuite for this functionality.
Upvotes: 1 |
2018/03/21 | 731 | 2,613 | <issue_start>username_0: Looking for a way that could help me drag a formula over a range with an autofill sentence, depending on a previous selected range through an application.selection.
I am stuck in the autofill statement as you can see below.
Code:
```
xTitleId = "KutoolsforExcel"
Set range2 = Application.Selection
Set range2 = Application.InputBox("Source Ranges:", xTitleId, range2.Address, Type:=8)
Set range3 = Application.Selection
Set range3 = Application.InputBox("Source Ranges:", xTitleId, range2.Address, Type:=8)
range2.AutoFill Destination:=range3 'It returns "run time error 1004 autofill method of range failed
```
Here is a background picture of what I want to do...
[](https://i.stack.imgur.com/nHWRZ.jpg)<issue_comment>username_1: Can you do this? Range 2 is single cell at present. Use FormulaR1C1 to keep relative references.
```
Option Explicit
Sub test()
Dim range2 As Range
Dim range3 As Range
Set range2 = Application.Selection
Set range2 = Application.InputBox("Source Ranges:", "Text", range2.Address, Type:=8)
Set range3 = Application.Selection
Set range3 = Application.InputBox("Source Ranges:", "Text", range2.Address, Type:=8)
range3.Formula = range2.Formula
End Sub
```
Example with FormulaR1C1
[](https://i.stack.imgur.com/730qW.gif)
Upvotes: 3 [selected_answer]<issue_comment>username_2: If you have corner cells `TopLeftCell` and `BottomRightCell` as the Corners for your range-to-fill, then you can fill the rectangle like this:
```vb
With Range(TopLeftCell, BottomRightCell)
If .Columns.Count > 1 Then .Rows(1).FillRight 'First fill horizontally
If .Rows.Count > 1 Then .FillDown 'Then fill vertically
End With
```
If you have `FormulaCell` and `OtherCorner` as your corner-cell ranges then you need to extend with checks as to whether you fill Right/Left or Up/Down: (i.e work out which diagonals and which direction to fill)
```vb
With Range(FormulaCell, OtherCorner)
If .Columns.Count > 1 Then 'More than 1 column, fill horizontal
If FormulaCell.Column < OtherCorner.Column Then
Intersect(.Cells, FormulaCell.EntireRow).FillRight
Else
Intersect(.Cells, FormulaCell.EntireRow).FillLeft
End If
End If
If .Rows.Count > 1 Then 'More than 1 row, fill vertical
If FormulaCell.Row < OtherCorner.Row Then
.FillDown
Else
.FillUp
End If
End If
End With
```
Upvotes: 0 |
2018/03/21 | 905 | 2,603 | <issue_start>username_0: I have been trying to work out getting a similar table to a picture that I have been studied from. Which looks like:

However I have been getting something similar:
This is what I have done:

However im getting issues when it comes to:
1. Underscore line under the bold text, Which I managed to only get on a small text which I wish to get in the whole line
2. Also I want to adjust the Size of the table so it gets stuck like in the first picture. I don't know if I did the correct way now but I assume iam on the correct way. Maybe someone here can help me out seeing the issue.
```
table {
border: 1px solid black;
background-color: #ffcc99;
}
tr.hello {
background-color: #000000;
color: #ffffff;
}
tr.bigtext {
font-weight: bold;
}
##### Tabell 2
| | |
| --- | --- |
| Studenter | 17000 |
| Högskoleingejör | 2800 |
| Ekonomi | 1800 |
| Fristående kurser | 8300 |
| Cirka 600 utländska studenter ingår i det totaala antalet studenter |
```<issue_comment>username_1: You have done all almost correct, except you should:
* not underline the border stuff.
* not use tags.
* use the colspan for the full width.
And your code seems to be incomplete. Here's your updated code:
```css
table {
border: 1px solid black;
background-color: #ffcc99;
}
tr.hello {
background-color: #000000;
color: #ffffff;
}
tr.bigtext td {
font-weight: bold;
border-bottom: 1px solid #000;
}
```
```html
##### Tabell 2
| | |
| --- | --- |
| Studenter | 17000 |
| Högskoleingejör | 2800 |
| Ekonomi | 1800 |
| Fristående kurser | 8300 |
| Cirka 600 utländska studenter ingår i det totaala antalet studenter |
```
**Preview**
[](https://i.stack.imgur.com/utFYK.png)
Upvotes: 2 [selected_answer]<issue_comment>username_2: This is how I did it. I added the following under the `bigtext` tr class:
```
| |
```
and I added the following CSS to fix the fonts and the underline:
```
.underline {
border-top: solid 1px black;
}
tr:not(.bigtext) td:first-child{
font-family: Papyrus, fantasy;
}
tr:not(.bigtext) td:not(first-child){
font-family: Georgia;
}
tr.bigtext td:not(first-child){
font-family: Georgia;
}
```
The table width has also been adjusted. So the in-line CSS style was removed and this was added to your `table` css:
```
width: 70%;
```
[**Here is the JSFiddle demo**](https://jsfiddle.net/kp71ah0g/)
Upvotes: 0 |
2018/03/21 | 189 | 643 | <issue_start>username_0: post has a type observable not array , I need a help
[](https://i.stack.imgur.com/jDe23.png)<issue_comment>username_1: Use the async pipe
```
```
to get the values for the current emit of your Observable.
Upvotes: 3 [selected_answer]<issue_comment>username_2: Would like to improve previous ans..
async pipe itself check for null or undefined value therefore no need to check .length>0 . So improved answer would be
```
*ngIf="(post | async)"
```
or another way is
```
*ngIf="post.value.length>0"
```
Hope this will help you :)
Upvotes: 0 |
2018/03/21 | 270 | 1,006 | <issue_start>username_0: There is an issue with Bootstrap 4 and Safari brower on Mac.
When using cols inside a row it breaks it, and doesn't work like on firefox or chrome. I'm using a simple code like this:
```
### TEXT
TEXT
TEXT
TEXT
```
I'm trying different 'fix codes' from another questions but they doesn't solve the problem. Any clue?
Thanks in advance<issue_comment>username_1: Finally solved the problem with this simple CSS:
```
.row:before, .row:after {display: none !important;}
```
It seems there is some code hidden in :before and :after elements inside the rows. This causes some kind of issues in safari browsers.
Hope it helps.
Upvotes: 7 [selected_answer]<issue_comment>username_2: ```
.row:before, .row:after {width:0px; height:0px;}
```
There is a reason for display:table before and after row.
By using display:none, the row will not preserve its height depending on the elements inside it, and row height is now 0px because the columns inside is floating..
Upvotes: 3 |
2018/03/21 | 1,066 | 4,008 | <issue_start>username_0: I have two tasks. I run both of them with Task.WhenAll. What happens if one of them throws an exception? Would the other one complete?<issue_comment>username_1: Just run this code to test it:
```
private static async Task TestTaskWhenAll()
{
try
{
await Task.WhenAll(
ShortOperationAsync(),
LongOperationAsync()
);
}
catch (Exception exception)
{
Console.WriteLine(exception.Message); // Short operation exception
Debugger.Break();
}
}
private static async Task ShortOperationAsync()
{
await Task.Delay(1000);
throw new InvalidTimeZoneException("Short operation exception");
}
private static async Task LongOperationAsync()
{
await Task.Delay(5000);
throw new ArgumentException("Long operation exception");
}
```
Debugger will stop in 5 seconds. Both exceptions are thrown, but `Debugger.Break()` is hit only once. What is more, the `exception` value is not `AggregateException`, but `InvalidTimeZoneException`. This is because of new `async/await` which does the unwrapping into the actual exception. You can read more [here](https://stackoverflow.com/questions/12007781/why-doesnt-await-on-task-whenall-throw-an-aggregateexception). If you want to read other `Exceptions` (not only the first one), you would have to read them from the `Task` returned from `WhenAll` method call.
Upvotes: 5 [selected_answer]<issue_comment>username_2: ### Will the other one complete?
It won't be *stopped* as a result of the other one failing.
### But will it **complete**?
`Task.When` will wait for all to complete, whether any or none fail. I just tested with this to verify - and it took 5 seconds to complete:
```
Task allTasks = Task.WhenAll(getClientToken, getVault, Task.Delay(5000));
```
If you want to group the tasks you can create a 'new task', then await that.
```
Task allTasks = Task.WhenAll(getClientToken, getVault, Task.Delay(5000));
try
{
await allTasks;
} catch (Exception ex)
{
// ex is the 'unwrapped' actual exception
// I'm not actually sure if it's the first task to fail, or the first in the list that failed
// Handle all if needed
Exceptions[] allExceptions = allTasks.Exceptions;
// OR
// just get the result from the task / exception
if (getVault.Status == TaskStatus.Faulted)
{
...
}
}
```
Upvotes: 4 <issue_comment>username_3: Had the same question and tested by myself. In short:
* It always wait for all tasks to finish.
* The first exception is thrown if there is any after all tasks are finished (crash if you don't catch).
* For *all* exceptions, keep the `Task` instance returned by `Task.WhenAll` and use `Exception.InnerExceptions` property.
Here's my test:
```
static async Task Main(string[] args)
{
var tasks = new[] { Foo1(), Foo2(), Foo3() };
Task t = null;
try
{
t = Task.WhenAll(tasks);
await t;
}
catch (Exception ex)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
Console.WriteLine("All have run.");
if (t.Exception != null)
{
foreach (var ex in t.Exception.InnerExceptions)
{
Console.WriteLine($"{ex.GetType().Name}: {ex.Message}");
}
}
}
static async Task Foo1()
{
await Task.Delay(50);
throw new ArgumentException("zzz");
}
static async Task Foo2()
{
await Task.Delay(1000);
Console.WriteLine("Foo 2");
throw new FieldAccessException("xxx");
}
static async Task Foo3()
{
for (int i = 0; i < 10; i++)
{
await Task.Delay(200);
Console.WriteLine("Foo 3");
}
}
```
Output:
```
Foo 3
Foo 3
Foo 3
Foo 3
Foo 2
Foo 3
Foo 3
Foo 3
Foo 3
Foo 3
Foo 3
ArgumentException: zzz
All have run.
ArgumentException: zzz
FieldAccessException: xxx
```
Upvotes: 2 |
2018/03/21 | 1,049 | 2,821 | <issue_start>username_0: I need to perform the following operation on a dataframe in R 3.4.1 on Windows
1. Split the dataframe by a categorical variable -> get a list of dataframe splitted by that categorical variable (getting the list is not necessary, that's just how I do it).
2. Extract a variable from the splitted dataframe list.
3. Combine the splitted variables in a matrix.
4. Transpose the matrix.
Currently I'm doing these operations as follows:
```
t(sapply(split(df, df$date), function(x) x$avg_mean))
```
I'd like this operation to be more efficient, that is:
1. Use the least memory possible, i.e. not duplicate objects, if possible. I may need to use this with a 1.5 GB dataframe.
2. Be fast with large dataframes.
What is the most appropriate/efficient way of doing this in R? Parallelization is also appreciated but not strictly necessary since I'm not sure I'll be able to use it.
If you need a toy dataframe, use [this](https://pastebin.com/p4b0eTuP).<issue_comment>username_1: I have added an index for each group and data table cast functions to achieve the same. You should use data table to make it more efficient
```
DF = data.table(DF)
DF[ , index := 1:.N, by=Col1]
DF_trx = dcast(DF, index~Col1, value.var = "Col2")
DF_trx$index=NULL
as.matrix(DF_trx)
```
Upvotes: 0 <issue_comment>username_2: The best approach is probably to go in the direction suggested in comments with `split(df$avg_mean, df$date)` and bind the results together. A pretty close second would be to just convert your vector to a matrix directly exploiting the fact that the number of observations for each date must be constant in your case. Some approaches and their speed below:
```r
library(microbenchmark)
library(data.table)
dat <- data.frame(date = rep(c('A', 'B', 'C'), each = 1000),
avg_mean = rnorm(3000))
f1 <- function(dat) {
t(sapply(split(dat, dat$date), function(x) x$avg_mean))
}
f2 <- function(dat) {
matrix(dat$avg_mean, nrow=length(unique(dat$date)), byrow = T)
}
f3 <- function(dat) {
do.call(rbind, split(dat$avg_mean, dat$date))
}
f4 <- function(DF) {
DF = data.table(DF)
DF[ , index := 1:.N, by=date]
DF_trx = dcast(DF, index~date, value.var = "avg_mean")
DF_trx$index=NULL
t(as.matrix(DF_trx))
}
microbenchmark(f1(dat), f2(dat), f3(dat), f4(dat))
#> Unit: microseconds
#> expr min lq mean median uq max neval
#> f1(dat) 456.064 475.542 617.0032 489.9390 515.6205 4250.471 100
#> f2(dat) 107.062 110.907 150.3135 117.6060 124.1925 2992.862 100
#> f3(dat) 74.313 79.927 122.2712 84.4455 89.4250 2504.850 100
#> f4(dat) 3797.694 3893.886 4563.4614 4021.6505 5053.5800 15757.085 100
```
It seems `do.call(rbind, split(dat$avg_mean, dat$date)` is probably your best bet.
Upvotes: 1 |
2018/03/21 | 244 | 817 | <issue_start>username_0: I am writing an angular 4 web application and I want to integrate the google maps in it? What is the best? Which library should I use?<issue_comment>username_1: You can use the **[`Angular Google Maps (AGM)`](https://angular-maps.com/)** library which is quite popular.
```
import { AgmCoreModule } from '@agm/core';
```
Upvotes: 1 <issue_comment>username_2: You can use [AGM](https://angular-maps.com/) and below is the code to enter:
```
import { AgmCoreModule } from '@agm/core';
@NgModule({
imports: [
BrowserModule,
AgmCoreModule.forRoot({
apiKey: 'YOUR_GOOGLE_MAPS_API_KEY'
})
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
```
In HTML,
```
```
Read [Docs](https://angular-maps.com/guides/getting-started/) to Get Started
Upvotes: 0 |
2018/03/21 | 761 | 2,318 | <issue_start>username_0: I have read many post on this topic but I am not yet satisfied.
I have a table called `ticket` with the following columns
```
TicketID | AirlineID | PassengerID | TicketPrice | TicketVolume | DestinationCountry | ExitCountry | TicketDate`
```
I have multiple queries like
```
SELECT AVG(TicketPrice)
FROM ticket
WHERE TicketPrice between 552 and 1302
AND AirlineID=1
AND TicketDate between '2016-01-01' and '2016-12-31'
GROUP BY TicketDate
SELECT AVG(TicketPrice)
FROM ticket
WHERE TicketPrice between 552 and 1302
AND AirlineID=1
AND TicketDate between '2017-01-01' and '2017-12-31'
GROUP BY TicketDate
```
Please how can I join both queries to form another table side by side
```
+--------------------------------++-----------
| AirlineID || Average Ticket Price 2016/2017|
+--------------------------------++-----------
```
they are actually more queries.<issue_comment>username_1: If you want to merge the results into a single table, use UNION.
```
SELECT {...}
UNION
SELECT {...}
```
The SELECT statements must return the same columns
Upvotes: 1 <issue_comment>username_2: Simply use `CASE` to achieve this:
Try this:
```
SELECT
AirlineID,
AVG(CASE WHEN TicketDate BETWEEN '2016-01-01' AND '2016-12-31' THEN TicketPrice END),
AVG(CASE WHEN TicketDate BETWEEN '2017-01-01' AND '2017-12-31' THEN TicketPrice END)
FROM ticket
WHERE
TicketPrice BETWEEN 552 AND 1302 AND
AirlineID = 1
GROUP BY
AirlineID, TicketDate;
```
Upvotes: 4 [selected_answer]<issue_comment>username_3: ***SQL***
```
SELECT
(SELECT AVG(TicketPrice) FROM ticket
WHERE TicketPrice between 552 and 1302
AND AirlineID=1
AND TicketDate between '2016-01-01' and '2016-12-31'
GROUP BY TicketDate) as Col1,
(SELECT AVG(TicketPrice) FROM ticket
WHERE TicketPrice between 552 and 1302
AND AirlineID=1
AND TicketDate between '2017-01-01' and '2017-12-31'
GROUP BY TicketDate) as Col2
```
Upvotes: 0 <issue_comment>username_4: Here is my solution for this, maybe not the desired output by OP but in my opinion a better output and also no need for hardcoded dates
```
SELECT AirlineID, extract(YEAR from TicketDate) as year, AVG(TicketPrice)
FROM ticket
WHERE TicketPrice between 552 and 1302
GROUP BY AirLineID, year
```
Upvotes: 2 |
2018/03/21 | 951 | 2,746 | <issue_start>username_0: For algorithms like yolo or R-CNN, they use the concept of anchor boxes for predicting objects. <https://pjreddie.com/darknet/yolo/>
The anchor boxes are trained on specific dataset, one for COCO dataset is:
```
anchors = 0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828
```
However, i don't understand how to interpret these anchor boxes? What does a pair of values (0.57273, 0.677385) means?<issue_comment>username_1: That's what I understood: YOLO divides an **416x416** image into **13x13** grids. Each grid as **32** pixels. The anchor boxes size are relative to the size of the grid.
So an anchor box of width and height 0.57273, 0.677385 pixels has actually a size of
* w = 0.57273 \* 32 = 18.3 pixels
* h = 0.677385 \* 32 = 21.67 pixels
If you convert all those values, you can then plot them on a 416x416 image to visualise them.
Upvotes: 2 <issue_comment>username_2: In the original YOLO or [YOLOv1](https://arxiv.org/pdf/1506.02640.pdf), the prediction was done without any assumption on the shape of the target objects. Let's say that the network tries to detect humans. We know that, generally, humans fit in a vertical rectangle box, rather than a square one. However, the original YOLO tried to detect humans with rectangle and square box with equal probability.
But this is not efficient and might decrease the prediction speed.
So in [YOLOv2](https://arxiv.org/pdf/1612.08242.pdf), we put some assumption on the shapes of the objects. These are Anchor-Boxes. Usually we feed the anchor boxes to the network as a list of some numbers, which is a series of pairs of width and height:
anchors = [0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282, 3.52778, 9.77052, 9.16828]
In the above example, (0.57273, 0.677385) represents a single anchor box, in which the two elements are width and height respectively. That is, this list defines 5 different anchor boxes. Note that these values are relative to the output size. For example, YOLOv2 outputs 13x13 feature mat and you can get the absolute values by multiplying 13 to the values of anchors.
Using anchor boxes made the prediction a little bit faster. But the accuracy might decrease. [The paper of YOLOv2](https://arxiv.org/pdf/1612.08242.pdf) says:
>
> Using anchor boxes we get a small decrease in accuracy. YOLO only
> predicts 98 boxes per image but with anchor boxes our model predicts
> more than a thousand. Without anchor boxes our intermediate model gets
> 69.5 mAP with a recall of 81%. With anchor boxes our model gets 69.2 mAP with a recall of 88%. Even though the mAP decreases, the increase
> in recall means that our model has more room to improve
>
>
>
Upvotes: 3 |
2018/03/21 | 1,688 | 4,755 | <issue_start>username_0: Apologies if this question has already been asked before - I was struggling to think of how to phrase my searches (hence the awkward title)!
What I have is a data frame of single-character values, like so:
```
-------------------------
| Parent | Daughter |
-------------------------
| A | B |
| B | C |
| B | D |
| A | E |
-------------------------
```
Where for every parent there will always be two daughters (like a complete binary tree). I'm trying to write a segment of code that will produce the vectors of paths from the top parent down to the final daughters:
```
A B C
A B D
A E
```
But with varying numbers of parents, and varying lengths of vectors.
I thought about using a for loop but came unstuck because I think I'd need one for every 'level' of the tree, which I don't know in advance.
I don't necessarily want the code, just advice on how to go about such a problem! But any help would be hugely appreciated, thanks!
**EDIT:** I should point out that the 'from end to start' is just because I figure that way would be easier - it's certainly not necessary!
Data:
```
df <- data.frame(Parent = c("A", "B", "B", "A"), Daughter = c("B", "C", "D", "E"))
```
**EDIT2:** Here are some more examples of the desired result. If I made the table a little bigger, so that:
```
-------------------------
| Parent | Daughter |
-------------------------
| A | B |
| B | C |
| B | D |
| A | E |
| C | F |
| C | G |
| E | H |
| E | I |
-------------------------
```
Data 2:
```
df <- data.frame(Parent = c("A", "B", "B", "A", "C", "C", "E", "E"), Daughter = c("B", "C", "D", "E", "F", "G", "H", "I"))
```
Then the vectors I'd want would be:
```
A B C F
A B C G
A B D
A E H
A E I
```<issue_comment>username_1: Here is something that could be helpful:
```
parent <- "A"
lev <- df$Daughter[which(df$Parent == parent)]
output <- cbind(parent, lev)
while(length(lev) > 0){
lev <- df$Daughter[which(is.element(df$Parent, lev))]
output <- cbind(output, lev)
}
# which returns
> output
parent lev lev
[1,] "A" "B" "C"
[2,] "A" "E" "D"
```
This could easily be translated into a `function(parent)`:
```
myfct <- function(parent){
lev <- df$Daughter[which(df$Parent == parent)]
output <- data.frame(parent, lev, stringsAsFactors = F)
while(length(lev) > 0){
dat <- df[which(is.element(df$Parent, lev)),]
newdat <- merge(x = output, y = dat, by.x = "lev", by.y = "Parent", all = TRUE)
col.first <- which(names(newdat) == "parent")
col.last <- which(names(newdat) == "Daughter")
col.sec.last <- which(names(newdat) == "lev")
col.rest <- setdiff(1:dim(newdat)[2], c(col.first, col.sec.last,col.last))
newdat <- newdat[, c(col.first, col.rest, col.sec.last, col.last)]
names(newdat)[2:(length(names(newdat))-1)] <- paste0("x.",2:(length(names(newdat))-1))
names(newdat)[length(names(newdat))] <- "lev"
output <- newdat
lev <- df$Daughter[which(is.element(df$Parent, lev))]
}
cols <- as.numeric(which(!sapply(output, function(x)all(is.na(x)))))
output <- output[,cols]
return(output)
}
```
And here one can apply the function:
```
parents.list <- unique(df$Parent)
sapply(parents.list, myfct)
# which returns
$A
parent x.2 x.3 x.4
1 A B C F
2 A B C G
3 A B D
4 A E H
5 A E I
$B
parent x.2 x.3
1 B C F
2 B C G
3 B D
$C
parent x.2
1 C F
2 C G
$E
parent x.2
1 E H
2 E I
```
Now you can always modify it in order to change the structure of the output.
---
**Edit**
The key is do add a `while`. I edited my code and now it ought to work without having to specify the number of levels.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Using *igraph* package, convert dataframe to graph object, get the paths, remove paths that are subset of other paths.
```
library(igraph)
# example data
df <- data.frame(Parent = c("A", "B", "B", "A", "C", "C", "E", "E"),
Daughter = c("B", "C", "D", "E", "F", "G", "H", "I"))
# convert to graph object
g <- graph_from_data_frame(df)
# get all the paths, extract node ids from paths
res <- all_simple_paths(g, from = "A")
res <- lapply(res, as_ids)
# get index where vector is not subset of other vector
ix <- sapply(res, function(i) {
x <- sapply(res, function(j) length(intersect(i, j)))
sum(length(i) == x) == 1
})
# result
res <- res[ix]
# res
# [[1]]
# [1] "A" "B" "C" "F"
#
# [[2]]
# [1] "A" "B" "C" "G"
#
# [[3]]
# [1] "A" "B" "D"
#
# [[4]]
# [1] "A" "E" "H"
#
# [[5]]
# [1] "A" "E" "I"
```
Upvotes: 2 |
2018/03/21 | 1,318 | 3,683 | <issue_start>username_0: I'm building a file upload form where users can submit XML configuration files. My goal is to get the full contents and insert them into Wordpress as a new post (custom post type). It's working for the most part, except I am having difficulty pulling the XML tags with the content when using `file_get_contents()`. Does this omit XML tags when used? If so, how can I get the full contents of the file?
Here is my code for the form and handler...
```
function slicer_profile_form()
{
echo '';
echo '';
echo 'Profile
';
echo '';
echo '
';
echo '';
echo '';
}
function slicer_profile_submit()
{
// if the submit button is clicked, submit
if (isset($_POST['slicer-profile-submitted']))
{
$contents = file_get_contents( $_FILES['slicer-profile']['tmp_name'] );
var_dump($contents);
}
}
```<issue_comment>username_1: Here is something that could be helpful:
```
parent <- "A"
lev <- df$Daughter[which(df$Parent == parent)]
output <- cbind(parent, lev)
while(length(lev) > 0){
lev <- df$Daughter[which(is.element(df$Parent, lev))]
output <- cbind(output, lev)
}
# which returns
> output
parent lev lev
[1,] "A" "B" "C"
[2,] "A" "E" "D"
```
This could easily be translated into a `function(parent)`:
```
myfct <- function(parent){
lev <- df$Daughter[which(df$Parent == parent)]
output <- data.frame(parent, lev, stringsAsFactors = F)
while(length(lev) > 0){
dat <- df[which(is.element(df$Parent, lev)),]
newdat <- merge(x = output, y = dat, by.x = "lev", by.y = "Parent", all = TRUE)
col.first <- which(names(newdat) == "parent")
col.last <- which(names(newdat) == "Daughter")
col.sec.last <- which(names(newdat) == "lev")
col.rest <- setdiff(1:dim(newdat)[2], c(col.first, col.sec.last,col.last))
newdat <- newdat[, c(col.first, col.rest, col.sec.last, col.last)]
names(newdat)[2:(length(names(newdat))-1)] <- paste0("x.",2:(length(names(newdat))-1))
names(newdat)[length(names(newdat))] <- "lev"
output <- newdat
lev <- df$Daughter[which(is.element(df$Parent, lev))]
}
cols <- as.numeric(which(!sapply(output, function(x)all(is.na(x)))))
output <- output[,cols]
return(output)
}
```
And here one can apply the function:
```
parents.list <- unique(df$Parent)
sapply(parents.list, myfct)
# which returns
$A
parent x.2 x.3 x.4
1 A B C F
2 A B C G
3 A B D
4 A E H
5 A E I
$B
parent x.2 x.3
1 B C F
2 B C G
3 B D
$C
parent x.2
1 C F
2 C G
$E
parent x.2
1 E H
2 E I
```
Now you can always modify it in order to change the structure of the output.
---
**Edit**
The key is do add a `while`. I edited my code and now it ought to work without having to specify the number of levels.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Using *igraph* package, convert dataframe to graph object, get the paths, remove paths that are subset of other paths.
```
library(igraph)
# example data
df <- data.frame(Parent = c("A", "B", "B", "A", "C", "C", "E", "E"),
Daughter = c("B", "C", "D", "E", "F", "G", "H", "I"))
# convert to graph object
g <- graph_from_data_frame(df)
# get all the paths, extract node ids from paths
res <- all_simple_paths(g, from = "A")
res <- lapply(res, as_ids)
# get index where vector is not subset of other vector
ix <- sapply(res, function(i) {
x <- sapply(res, function(j) length(intersect(i, j)))
sum(length(i) == x) == 1
})
# result
res <- res[ix]
# res
# [[1]]
# [1] "A" "B" "C" "F"
#
# [[2]]
# [1] "A" "B" "C" "G"
#
# [[3]]
# [1] "A" "B" "D"
#
# [[4]]
# [1] "A" "E" "H"
#
# [[5]]
# [1] "A" "E" "I"
```
Upvotes: 2 |
2018/03/21 | 1,560 | 3,718 | <issue_start>username_0: I have a hive table with the following structure:
```
id1, id2, year, value
1, 1, 2000, 20
1, 1, 2002, 23
1, 1, 2003, 24
1, 2, 1999, 34
1, 2, 2000, 35
1, 2, 2001, 37
2, 3, 2005, 50
2, 3, 2006, 56
2, 3, 2008, 60
```
I have 2 ids which identify the 'user', and for each user and year I have a value, but there are years with no values which do not appear in the table. I would like to add for each id [id1,id2] and year (considering all the years between the minimum and maximum year) a value, using the previous year value in case a year does not exists. So the table should become:
```
id1, id2, year, value
1, 1, 2000, 20
1, 1, 2001, 20
1, 1, 2002, 23
1, 1, 2003, 24
1, 2, 1999, 34
1, 2, 2000, 35
1, 2, 2001, 37
2, 3, 2005, 50
2, 3, 2006, 56
2, 3, 2007, 56
2, 3, 2008, 60
```
I need to do that in hive or pig, or in the worst case I could go with spark
thanks,<issue_comment>username_1: Here is something that could be helpful:
```
parent <- "A"
lev <- df$Daughter[which(df$Parent == parent)]
output <- cbind(parent, lev)
while(length(lev) > 0){
lev <- df$Daughter[which(is.element(df$Parent, lev))]
output <- cbind(output, lev)
}
# which returns
> output
parent lev lev
[1,] "A" "B" "C"
[2,] "A" "E" "D"
```
This could easily be translated into a `function(parent)`:
```
myfct <- function(parent){
lev <- df$Daughter[which(df$Parent == parent)]
output <- data.frame(parent, lev, stringsAsFactors = F)
while(length(lev) > 0){
dat <- df[which(is.element(df$Parent, lev)),]
newdat <- merge(x = output, y = dat, by.x = "lev", by.y = "Parent", all = TRUE)
col.first <- which(names(newdat) == "parent")
col.last <- which(names(newdat) == "Daughter")
col.sec.last <- which(names(newdat) == "lev")
col.rest <- setdiff(1:dim(newdat)[2], c(col.first, col.sec.last,col.last))
newdat <- newdat[, c(col.first, col.rest, col.sec.last, col.last)]
names(newdat)[2:(length(names(newdat))-1)] <- paste0("x.",2:(length(names(newdat))-1))
names(newdat)[length(names(newdat))] <- "lev"
output <- newdat
lev <- df$Daughter[which(is.element(df$Parent, lev))]
}
cols <- as.numeric(which(!sapply(output, function(x)all(is.na(x)))))
output <- output[,cols]
return(output)
}
```
And here one can apply the function:
```
parents.list <- unique(df$Parent)
sapply(parents.list, myfct)
# which returns
$A
parent x.2 x.3 x.4
1 A B C F
2 A B C G
3 A B D
4 A E H
5 A E I
$B
parent x.2 x.3
1 B C F
2 B C G
3 B D
$C
parent x.2
1 C F
2 C G
$E
parent x.2
1 E H
2 E I
```
Now you can always modify it in order to change the structure of the output.
---
**Edit**
The key is do add a `while`. I edited my code and now it ought to work without having to specify the number of levels.
Upvotes: 2 [selected_answer]<issue_comment>username_2: Using *igraph* package, convert dataframe to graph object, get the paths, remove paths that are subset of other paths.
```
library(igraph)
# example data
df <- data.frame(Parent = c("A", "B", "B", "A", "C", "C", "E", "E"),
Daughter = c("B", "C", "D", "E", "F", "G", "H", "I"))
# convert to graph object
g <- graph_from_data_frame(df)
# get all the paths, extract node ids from paths
res <- all_simple_paths(g, from = "A")
res <- lapply(res, as_ids)
# get index where vector is not subset of other vector
ix <- sapply(res, function(i) {
x <- sapply(res, function(j) length(intersect(i, j)))
sum(length(i) == x) == 1
})
# result
res <- res[ix]
# res
# [[1]]
# [1] "A" "B" "C" "F"
#
# [[2]]
# [1] "A" "B" "C" "G"
#
# [[3]]
# [1] "A" "B" "D"
#
# [[4]]
# [1] "A" "E" "H"
#
# [[5]]
# [1] "A" "E" "I"
```
Upvotes: 2 |
2018/03/21 | 764 | 2,595 | <issue_start>username_0: I don't know if the problem is related to jenkins, java or apache. But since i did a server reboot my jenkins.example.com returns a 503 service unavailable.
---
What I tried
------------
Restart jenkins, restart apache, reinstall jenkins.
While restarting jenkins I was able to see the default installation page of jenkins but it returned a 503 a few seconds later.
---
My Settings
-----------
Here is my apache.conf
```
ServerAdmin webmaster@localhost
ServerName jenkins.example.com
ServerAlias jenkins
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.\*) https://%{SERVER\_NAME}/$1 [R,L]
```
and apache-ssl.conf
```
ServerAdmin webmaster@localhost
ServerName jenkins.example.com
ServerAlias jenkins
ProxyRequests Off
Order deny,allow
Allow from all
ProxyPreserveHost on
ProxyPass / http://localhost:8081/ retry=0 timeout=5 nocanon
ProxyPassReverse / http://localhost:8081
AllowEncodedSlashes NoDecode
RequestHeader set X-Forwarded-Proto "https"
RequestHeader set X-Forwarded-Port "443"
SSLCertificateFile /home/staff/x.example.com.crt
SSLCertificateKeyFile /home/staff/x.example.com.key
```
Also this is my apache error.log
```
[Wed Mar 21 10:59:16.798407 2018] [proxy:error] [pid 6611] (111)Connection refused: AH00957: HTTP: attempt to connect to 127.0.0.1:8081 (localhost) failed
[Wed Mar 21 10:59:16.798481 2018] [proxy_http:error] [pid 6611] [client xx.xxx.xx.xx:xxxxx] AH01114: HTTP: failed to make connection to backend: localhost
```
This server has also installed phabricator which is running perfectly after reboot. Only jenkins seemed to crash.
---
Fixed!
------
Got this fixed reinstalling jenkins under a new server. I think it was an error with phabricator which was already installed in the same server. Now under the new server, even if I reboot the server, jenkins will show up under jenkins.example.com<issue_comment>username_1: You need to configure your `jenkins` to work under the `proxy`. For that to happen, please follow [this link](https://jazz.net/forum/questions/214230/how-do-you-configure-jenkins-to-work-with-a-proxy-server). I haven't tried this on my own. But looks promising. There are more tutorials to configure jenkins under proxy. Hope this will resolve your issue.
Upvotes: 1 <issue_comment>username_2: Got this fixed by reinstalling jenkins under a new server. I think it was an error with phabricator which was already installed in the same server. Now under the new server, even if I reboot the server, jenkins will show up under jenkins.example.com
Upvotes: 1 [selected_answer] |
2018/03/21 | 241 | 858 | <issue_start>username_0: XNamespace aw = "<http://www.adventure-works.com>";
How this is possible ? Normally to create an instance of a particular class we need to use the New keyword or a specific static method returning the created instance.
There is a specific implementation allowing this to be possible ?
Thank's.<issue_comment>username_1: There is an implicit conversion operator defined in `System.Xml.Linq`, see [MSDN](https://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.op_implicit(v=vs.110).aspx).
Upvotes: 0 <issue_comment>username_2: The XNamespace class has an implicit operator defined that converts from type String to type XNamespace.
[XNamespace Implicit Conversion (String to XNamespace) - MSDN](https://msdn.microsoft.com/en-us/library/system.xml.linq.xnamespace.op_implicit(v=vs.110).aspx).
Upvotes: 2 [selected_answer] |
2018/03/21 | 620 | 2,336 | <issue_start>username_0: In my `datagrid`, one of columns is `DataGridComboBoxColumn`, where I'm trying to display different drop down menu in every row. Easy task when creating combo box in XAML instead of doing it programatically. My problem is that I have no idea how to bind it properly. This is what I tried:
```
private DataGridComboBoxColumn CreateComboValueColumn(List elements)
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
column.ItemsSource = elements;
column.DisplayMemberPath = "Text";
column.SelectedValuePath = "ID";
column.SelectedValueBinding = new Binding("Value");
return column;
}
public class Elements
{
public string Name { get; set; }
public string Value { get; set; }
public string Comment { get; set; }
public List ComboItems { get; set; }
}
public class ComboItem
{
public string ID { get; set; }
public string Text { get; set; }
}
```<issue_comment>username_1: You have to think from above and read what you are doing.
```
column.ItemsSource = elements;
```
That sets your column itemssource to a list of elements.
```
column.DisplayMemberPath = "Text";
```
It's not a member of Element so it won't show anything. You should set your column.ItemsSource to:
```
column.ItemsSource = elements[i].ComboItems
```
Being "i" the element you want to show.
Then if you want to show the text you should:
```
column.DisplayMemberPath = "Text";
```
If you want the Id then just:
```
column.DisplayMemberPath = "ID";
```
I wrote this without any editor and I think this is close to the answer you want, if I'm wrong comment this and I'll try to answer in a more accurate way.
Upvotes: 1 <issue_comment>username_2: It seems that adding binding from `style` works better than direct approach. This works:
```
private DataGridComboBoxColumn CreateComboValueColumn(List elements)
{
DataGridComboBoxColumn column = new DataGridComboBoxColumn();
Style style = new Style(typeof(ComboBox));
//set itemsource = {Binding ComboItems}
style.Setters.Add(new Setter(ComboBox.ItemsSourceProperty, new Binding("ComboItems")));
column.DisplayMemberPath = "Text";
column.SelectedValuePath = "ID";
column.SelectedValueBinding = new Binding("Value");
column.ElementStyle = style;
column.EditingElementStyle = style;
return column;
}
```
Upvotes: 1 [selected_answer] |
2018/03/21 | 678 | 1,975 | <issue_start>username_0: I have a list of list, as such
```
list = [[title, description, ~N[2018-01-01 23:00:07], comment, user],
[title, description, ~N[2018-03-02 12:10:18], comment, user]]
```
Now I need to convert every NaiveDateTime to Erlang date (or Unix timestamp).
I believe I can do something like
```
new_list = Enum.map(list,&modify_date/1)
def modify_date(list) do
##
end
```
But I can't figure out how to make `modify_date/1` only affect the third element. Any ideas?<issue_comment>username_1: ```
new_list = update_in(list, [Access.all(), Access.at(2)], &modify_date/1)
```
Upvotes: 2 <issue_comment>username_2: You can transfer list to tuple also.
```
list = [["fds", "fds", ~N[2018-01-01 23:00:07], "sfd", "fdsa"],
["fds", "fds", ~N[2018-03-02 12:10:18], "fds", "fdsa"]]
Enum.map(list, fn x ->
IO.inspect x|> List.to_tuple |> elem(2)
end)
```
Upvotes: 0 <issue_comment>username_3: The easiest and most idiomatic way in Elixir of solving this problem is by directly pattern matching. This will increase readability considerably as contrasted to the other solutions presented so far.
You are correct about utilizing `Enum.map(list, &modify_date/1)`, and if you pattern match like this:
`modify_date([title, description, date, comment, user])`
you can easily pick out any data that you require and manipulate accordingly.
A full working solution is presented below, which you can run as `A.run()`:
```
defmodule A do
def run do
[["title", "description", ~N[2018-01-01 23:00:07], "comment", "user"], ["title", "description", ~N[2018-03-02 12:10:18], "comment", "user"]]
|> process
end
def process(list) do
Enum.map(list, &modify_date/1)
end
def modify_date([title, description, date, comment, user]) do
unix_timestamp = date
|> DateTime.from_naive!("Etc/UTC")
|> DateTime.to_unix()
[title, description, unix_timestamp, comment, user]
end
end
```
Upvotes: 3 [selected_answer] |
2018/03/21 | 716 | 2,454 | <issue_start>username_0: Updated Android studio.
Downloaded Gradle. Changed Gradle folder in PC's environmental settings.
In computer, `gradle -version` returns `Gradle 4.4.1`.
[](https://i.stack.imgur.com/ltFZB.png)
In Android Studio, returns `Gradle 3.5`
*Smart* Android IDE refuses to recognise gradle and I can't compile.
It even gives the **wrong** error message
>
> Minimum supported Gradle version is 4.1. Current version is 3.5. If using the gradle wrapper, try editing the distributionUrl in C:\xxxxxx\gradle\wrapper\gradle-wrapper.properties to gradle-4.1-all.zip
>
>
>
[](https://i.stack.imgur.com/6xN3I.png)
[](https://i.stack.imgur.com/HamN2.png)
I have tried restarting, `invalidate and restart`. Nothing works.
How to fix it?<issue_comment>username_1: You need to go to
`File->Settings->Build,Execution,Deployment->Gradle`
Then tick `User local gradle distribution` and set the path to your local gradle
Upvotes: 2 <issue_comment>username_2: I check android studio offical web, android studio IDE now support version just to gradle-4.1.
I think you can go to gradle-wrapper.properties, and change to `distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip`
or
```
distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-all.zip
```
, maybe it can solve the problem.
Reference site:
<https://developer.android.com/studio/releases/gradle-plugin.html>
Upvotes: 0 <issue_comment>username_3: Fixed it by restarting the computer.
Restarting the IDE is not good enough. After restarting computer and going into Android Studio's terminal, typing in `gradle -version` shows the correct version. That's when I know it'd work. Sure enough, `gradle` commands now work.
Answered this just to show how *genius* the IDE written by *geniuses* is.
Upvotes: 2 [selected_answer]<issue_comment>username_4: I faced this problem and i had fixed it. first goto <https://services.gradle.org/distributions/gradle-4.10.1-all.zip> and download it locally. Goto File->Settings->Build,Execution,Deployment->Gradle and select "Use local gradle" and set local gradle path that you downloaded just.
[gradle path](https://i.stack.imgur.com/9GNjQ.jpg)
Upvotes: 0 |
2018/03/21 | 1,300 | 4,517 | <issue_start>username_0: How can I redirect to another page when someone access the detail page but without a record or if record is not available?
I have detail records like
```
domain.com/abc/ABC1234
```
When somone enters
```
domain.com/abc/
```
... I get:
```
Uncaught TYPO3 Exception
#1298012500: Required argument "record" is not set for Vendor\Extension\Controller\ActionController->show. (More information)
TYPO3\CMS\Extbase\Mvc\Controller\Exception\RequiredArgumentMissingException thrown in file
/is/htdocs/www/typo3_src-8.7.11/typo3/sysext/extbase/Classes/Mvc/Controller/AbstractController.php in line 425.
```
... in this case I want it to redirect to:
```
domain.com/other-page/
```
... I also need it if a specific record is not available.
... how to do so?
```
/**
* action show
*
* @param \Action $record
* @return void
*/
public function showAction(Action $record) {
$this->view->assign('record', $record);
}
```
Here are some examples [TYPO3 Extbase - redirect to pid](https://stackoverflow.com/questions/40551408/typo3-extbase-redirect-to-pid) ... but not sure how to implement it
Edit: What works is ...
```
/**
* action show
*
* @param \Action $record
* @return void
*/
public function showAction(Action $record=null) {
if ($record === null) {
$pageUid = 75;
$uriBuilder = $this->uriBuilder;
$uri = $uriBuilder
->setTargetPageUid($pageUid)
->build();
$this->redirectToUri($uri, 0, 404);
} else {
$this->view->assign('record', $record);
}
}
```<issue_comment>username_1: This could be a solution:
```
/\*\*
\* Show a booking object
\*
\* @return void
\* @throws \TYPO3\CMS\Extbase\Mvc\Exception\NoSuchArgumentException
\*/
```
public function showAction()
{
$bookingObject = null;
$bookingObjectUid = 0;
if ($this->request->hasArgument('bookingObject')) {
$bookingObjectUid = (int)$this->request->getArgument('bookingObject');
}
if ($bookingObjectUid > 0) {
$bookingObject = $this->bookingObjectRepository->findByIdentifier($bookingObjectUid);
}
if (!($bookingObject instanceof BookingObject)) {
$messageBody = 'Booking object can\'t be displayed.';
$messageTitle = 'Error';
$this->addFlashMessage($messageBody, $messageTitle, AbstractMessage::ERROR);
$this->redirect('list');
}
$this->view->assign('bookingObject', $bookingObject);
}
```
```
Upvotes: -1 <issue_comment>username_2: This should do the trick:
```
public function showAction(Action $record=null) {
if ($record === null) {
$this->redirect(/* add parameters as needed */);
} else {
// other code
}
```
Alternative Solution (from <NAME>)
```
public function intializeShowAction() {
if (!$this->request->hasArgument('record')) {
$this->redirect(/* add parameters as needed */); // stops further execution
}
}
```
Your question suggests that there should be an other action without arguments, probably a listAction, that is the DEFAULT action. The default action gets called when no action is specified. It is the first action enlisted in the ExtensionUtility::configurePlugin() call.
```
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Vendor.' . $_EXTKEY,
'Pluginname',
array(
'Domainobject' => 'list, show',
),
// non-cacheable actions
array(
'Domainobject' => 'list, show',
)
);
```
Regarding > The identity property "TTTT" is no UID
You have to distinguish between no parameter and an invalid parameter. For the latter you can add @ignorevalidation to the showAction comments and do your validation testing within the action - or you can leave it to extbase that displays the error message you have seen.
Where would you get a link like domain.com/abc/TTTT/ from anyhow? Unless the link is expired.
BTW: in a production system you would disable the display of exceptions, thus the display of the website would work.
Upvotes: 1 <issue_comment>username_3: The `redirect` method needs an action and controller parameter. So your redirect code is wrong.
```
$this->redirect($actionName, $controllerName = NULL, $extensionName = NULL, array $arguments = NULL, $pageUid = NULL, $delay = 0, $statusCode = 303);
```
To redirect to an PageUID you need to use the uriBuilder and the `redirectToUri` method. See [here](https://stackoverflow.com/questions/40551408/typo3-extbase-redirect-to-pid/40551878#40551878) for an example.
Upvotes: 4 [selected_answer] |
2018/03/21 | 1,378 | 4,455 | <issue_start>username_0: I'm struggling with how is it possible to get the data-value of these multiple classes?
```js
$(function() {
getUserName();
});
function getUserName() {
var o = $('div.YoutubePlaylist').length;
for (var i = 0; i < o; i++) {
console.log($("div.YoutubePlaylist").get(i));
console.log($("div.YoutubePlaylist").get(i).attr('data-username'));
console.log($("div.YoutubePlaylist").get(i).attr('data-playlist'));
}
};
```
```html
```<issue_comment>username_1: The [`get()`](https://api.jquery.com/get/) method returns DOM object so [`attr()`](https://api.jquery.com/attr/) method doesn't work with it. To get jQuery object use [`eq()`](https://api.jquery.com/eq/) method and apply [`attr()`](https://api.jquery.com/attr/) method on that.
```
$(function() {
getUserName();
});
function getUserName() {
var o = $('div.YoutubePlaylist').length;
for (var i = 0; i < o; i++) {
console.log($("div.YoutubePlaylist").eq(i).attr('data-username'));
// ---^^^^^----
console.log($("div.YoutubePlaylist").eq(i).attr('data-playlist'));
// ---^^^^^----
}
};
```
```js
$(function() {
getUserName();
});
function getUserName() {
var o = $('div.YoutubePlaylist').length;
for (var i = 0; i < o; i++) {
console.log($("div.YoutubePlaylist").eq(i).attr('data-username'));
console.log($("div.YoutubePlaylist").eq(i).attr('data-playlist'));
}
};
```
```html
```
In the above code, you can make some modification for better performance(caching reference, using [`data()`](https://api.jquery.com/data/) method etc).
```
$(function() {
var $o = $('div.YoutubePlaylist'); // cache the refernece
for (var i = 0; i < $o.length; i++) {
console.log($o.eq(i).data('username')); // get data atribute value
console.log($o.eq(i).data('playlist'));
}
});
```
```js
$(function() {
var $o = $('div.YoutubePlaylist');
for (var i = 0; i < $o.length; i++) {
console.log($o.eq(i).data('username'));
console.log($o.eq(i).data('playlist'));
}
});
```
```html
```
---
You can simplify the code by using jQuery [`each()`](https://api.jquery.com/each) method, which helps to iterate over jQuery element collection.
```
$(function() {
$('div.YoutubePlaylist').each(function() {
console.log($(this).attr('data-username'));
// or use
// console.log($(this).data('username'));
// console.log(this.dataset['username'])
console.log($(this).attr('data-playlist'));
// or use
// console.log($(this).data('playlist'));
// console.log(this.dataset['playlist'])
})
});
```
```js
$(function() {
$('div.YoutubePlaylist').each(function() {
console.log($(this).attr('data-username'));
// or use
// console.log($(this).data('username'));
// console.log(this.dataset['username'])
console.log($(this).attr('data-playlist'));
// or use
// console.log($(this).data('playlist'));
// console.log(this.dataset['playlist'])
})
});
```
```html
```
Upvotes: 0 <issue_comment>username_2: ***Simplify your code through*** [.each()](https://api.jquery.com/each/) and [.data()](https://api.jquery.com/jquery.data/)
```
$(document).ready(function(){
$('.YoutubePlaylist').each(function(){
console.log($(this).data('username'));
console.log($(this).data('playlist'));
});
});
```
***Working snippet:-***
```js
$(document).ready(function() {
$('.YoutubePlaylist').each(function() {
console.log($(this).data('username'));
console.log($(this).data('playlist'));
});
});
```
```html
```
Upvotes: 3 [selected_answer]<issue_comment>username_3: You can use `map` to get an array of attribute values
```
var output = $("div.YoutubePlaylist").map((i, v) => $(v).attr("data-username")).get();
```
**Demo**
```js
var output = $("div.YoutubePlaylist").map((i, v) => $(v).attr("data-username")).get();
console.log(output);
```
```html
```
If multiple values need to be returned, then `map` can return an object itself
```
var output = $("div.YoutubePlaylist").map((i, v) => ({
username: $(v).attr("data-username"),
playlist: $(v).attr("data-playlist")
})).get();
```
**Demo**
```js
var output = $("div.YoutubePlaylist").map((i, v) => ({
username: $(v).attr("data-username"),
playlist: $(v).attr("data-playlist")
})).get();
console.log(output);
```
```html
```
Upvotes: 0 |
2018/03/21 | 1,037 | 2,336 | <issue_start>username_0: I have a list of tuples (representing an http request headers),
before saving it to the database, I inspected it.
For example, an original value:
`[{"Content-Type", "application/json"}, {"x-request-id", "fatlud3104arjj91jtig2qrj3u7320la"}]`
is saved as:
`"[{\"Content-Type\", \"application/json\"}, {\"x-request-id\", \"fatlud3104arjj91jtig2qrj3u7320la\"}]"`
Is there a way to bring these values back to there original type (when loading from the db)?<issue_comment>username_1: you can make a workaround like this:
```
your_string = "[{\"Content-Type\", \"application/json\"}, {\"x-request-id\", \"fatlud3104arjj91jtig2qrj3u7320la\"}]"
your_string
|> String.split(~r/\"?\"/)
|> Enum.filter(fn value -> value not in ["[{", ", ", "}, {", "}]"] end)
|> Enum.chunk_every(2)
|> Enum.map(fn [key, value] -> {key, value} end)
```
:D
Upvotes: 1 <issue_comment>username_2: You may use `:erlang.term_to_binary/1` to encode any term and save in in the DB as some BLOB:
```
iex(1)> t = [{"Content-Type", "application/json"}, {"x-request-id", "fatlud3104arjj91jtig2qrj3u7320la"}]
[
{"Content-Type", "application/json"},
{"x-request-id", "fatlud3104arjj91jtig2qrj3u7320la"}
]
iex(3)> encoded = :erlang.term_to_binary(t)
<<131, 108, 0, 0, 0, 2, 104, 2, 109, 0, 0, 0, 12, 67, 111, 110, 116, 101, 110,
116, 45, 84, 121, 112, 101, 109, 0, 0, 0, 16, 97, 112, 112, 108, 105, 99, 97,
116, 105, 111, 110, 47, 106, 115, 111, 110, 104, 2, 109, 0, ...>>
```
Then use `binary_to_term/1` to get your list back:
```
iex(4)> :erlang.binary_to_term(encoded)
[
{"Content-Type", "application/json"},
{"x-request-id", "fatlud3104arjj91jtig2qrj3u7320la"}
]
```
If you don't want to save the binary, but rather a text, you may additionally encode it with Base64
```
iex(4)> t |> :erlang.term_to_binary() |> Base.encode64()
"<KEY>
```
Upvotes: 1 <issue_comment>username_3: You can use the `Code.eval_string/1` for that.
Here is a pipe with the full trip into and back from your DB.
```
[{"C", "json"}, {"x", "fa"}]
|> inspect
|> Code.eval_string
|> fn {recovered, []} -> recovered end.()
```
Just be careful to prevent code injections!!!
Upvotes: 3 [selected_answer] |
2018/03/21 | 419 | 1,389 | <issue_start>username_0: I have a variable that has a hardcoded value,
>
> customers.name = 'Schmidt'
>
>
>
```
declare @value as nvarchar(max)
set @value = 'customers.name = ''Schmidt'''
```
that I would like to change @value in this way
>
> customers.last\_name = 'Schmidt'
>
>
>
how this can be done using query?
Thank you in advance.<issue_comment>username_1: ```
DECLARE @Value AS NVARCHAR(MAX) = 'customers.name = ''Schmidt'''
,@Replacement AS NVARCHAR(MAX) = 'last_name'
,@SearchString AS NVARCHAR(MAX) = 'name'
SET @Value = REPLACE(@value, @SearchString, @Replacement)
PRINT @Value;
```
Upvotes: 2 <issue_comment>username_2: You should replace `customers.name` for `customers.last_name`.
```
DECLARE @text VARCHAR(200) = 'customers.name = ''Schmidt'''
SELECT
OriginalText = @text,
ReplacedText = REPLACE(@text, 'customers.name', 'customers.last_name')
/*
Result:
OriginalText: customers.name = 'Schmidt'
ReplacedText: customers.last_name = 'Schmidt'
*/
```
In general basis, when replacing strings, the bigger they are the lower the chance of replacing by mistake. If you are sure that the value will always start with `customers.name =` then you should replace that with `customers.last_name =`. If you try to replace simply `name` you might end up replacing it on another occurence of the string.
Upvotes: 2 [selected_answer] |
Subsets and Splits