date
stringlengths
10
10
nb_tokens
int64
60
629k
text_size
int64
234
1.02M
content
stringlengths
234
1.02M
2018/03/21
870
2,401
<issue_start>username_0: I tried to run the sample code shown [here](https://developers.itextpdf.com/content/itext-7-jump-start-tutorial/chapter-1-introducing-basic-building-blocks) but it's complaining that SLF4J is missing, so I downloaded the zip archive from the official website. The tutorial [video](https://www.youtube.com/watch?v=sxArv-GskLc&) shows that 3 of the jar files are used (log4j-over-slf4j, slf4j-api & slf4j-log4j12) but if I add all 3 of them to the build path of my project (I'm not using Maven!), it complains that both "log4j-over..." and the api are there. If I get rid of the "over" file, it says "Failed to instantiate SLF4J LoggerFactory". So, which jar files do I need exactly to stop the complaints and run the sample code?<issue_comment>username_1: Try removing log4j12. You cannot use both over and log4j12 at the same time. [link](https://stackoverflow.com/questions/31044619/difference-between-slf4j-log4j12-and-log4j-over-slf4j) Upvotes: 1 <issue_comment>username_2: There is a tutorial showing all the dependencies needed for the sample code. Try this please: <https://developers.itextpdf.com/content/itext-7-jump-start-tutorial/installing-itext-7> It basically gives you a list of the exact maven dependencies your project will need to run. You'll also find some indications how to make it work with the IDE like [eclipse](https://www.youtube.com/watch?v=sxArv-GskLc&), [netbeans](https://www.youtube.com/watch?v=VcOi99zW7O4) and [intelliJ](https://www.youtube.com/watch?v=6WxITuCgpHQ) By using ``` org.slf4j slf4j-log4j12 1.7.18 ``` Edit: you could manually download these 3 dependencies. They get any slf4j with log4j project going: * [slf4j-api-1.6.1.jar](http://www.java2s.com/Code/Jar/s/Downloadslf4japi161jar.htm) * [slf4j-log4j12-1.6.1.jar](http://www.java2s.com/Code/Jar/s/Downloadslf4jlog4j12161jar.htm) * [log4j-1.2.16.jar](http://www.java2s.com/Code/Jar/l/Downloadlog4j1216jar.htm) if you don't trust 3rd party site go the [slf4j site](https://www.slf4j.org/download.html) and the [log4j](https://logging.apache.org/log4j/1.2/download.html) homepage. We simply need the slf4j api, its log4j implementation and log4j itself. Upvotes: 3 [selected_answer]<issue_comment>username_3: If you wish to use log4j 1.2.x as the logging back-end with slf4j, you need log4j-1.2.17.jar, slf4j-api-1.7.25.jar and slf4j-log4j12-1.7.25.jar. Upvotes: 0
2018/03/21
818
2,987
<issue_start>username_0: I'm working on creating a radial progress bar, I'm getting the percent from the database. So what should happen: 1- Getting the percent value from the database (Done) 2- Send the value from script to div in HTML. 3- jQuery takes the percent div and create the radial progress. But I'm getting a problem in number 2, I'm not sending the value correctly because it is in div inside a div. This is the div part: ``` ``` This is the part where I send a value I'm getting from my script method that gets the percent from database: ``` document.getElementById('ia-radial red1').getElementById('precent').innerHTML = HappyCity; ``` And this is the jQuery part: ``` $('.ia-radial').each(function(){ var utilslider = parseInt($(this).find("#precent").html()), circle = $(this).find("#pie"), radius = parseInt(circle.attr('r')), circumf= 2 * radius * Math.PI, percentV = (utilslider / 100) * circumf; circle.css('strokeDasharray', percentV + " " + circumf); ``` [codepen](https://codepen.io/MoorLex/pen/XdwwKr?depth=everything&order=popularity&page=5&q=radial%20progress&show_forks=false)<issue_comment>username_1: You should be able to do something similar to this with jQuery... ``` $('.ia-radial.red1').children('#precent').html(HappyCity) ``` Upvotes: 0 <issue_comment>username_2: Two things may help you fix the issue. First, the method `document.getElementById()` returns a DOM element that doesn't have a method `getElementById`, meaning that it cannot get called twice in a row like that. Also, `ia-radial red1` are two class names, rather than ID names, so `getElementById` won't succeed in selecting . The best way to get around this, is to use one ID name per div in the document, which is the conventional way. Try setting to (and also don't forget to change `#precent` to `.precent` in the CSS file). Then assign a specific ID to both divs (e.g. `id="precent1`" and `id="precent2"`). Then you can select a div with `document.getElementById('precent1').innerHTML = HappyCity;`. Second, the jQuery part gets called only once, when the page loads. You need to call it again after `innerHTML` is changed. Try wrapping it in a function like so, and adding an input `idName` so you can call the function on a particular element: ``` function updateProgressBar(idName) { $('.ia-radial').each(function(){ var utilslider = parseInt($(this).find("#"+idName).html()), // Note the idName circle = $(this).find("#pie"), radius = parseInt(circle.attr('r')), circumf= 2 * radius * Math.PI, percentV = (utilslider / 100) * circumf; circle.css('strokeDasharray', percentV + " " + circumf); }); } ``` Now, putting the two things together, you can update each element like so: ``` updateProgressBar("precent1"); document.getElementById('precent1').innerHTML = HappyCity; // Update progress bar after changing innerHTML updateProgressBar("precent1"); ``` Upvotes: 2 [selected_answer]
2018/03/21
710
2,469
<issue_start>username_0: Suppose I have a String containing static tags that looks like this: `mystring = "[tag]some text[/tag] untagged text [tag]some more text[/tag]"` I want to remove everything between each tag pair. I've figured out how to do so by using the following regex: `mystring = mystring.replaceAll("(?<=\\[tag])(.*?)(?=\\[/tag])", "");` The result of which will be: `mystring = "[tag][/tag] untagged text [tag][/tag]"` However, I'm unsure how to accomplish the same goal if the opening tag is dynamic. Example: `mystring = "[tag parameter="123"]some text[/tag] untagged text [tag parameter="456"]some more text[/tag]"` The "value" of the `parameter` portion of the tag is dynamic. Somehow, I have to introduce a wildcard to my current regex, but I am unsure how to do this. Essentially, replace the contents of all pairings of `"[tag*]"` and `"[/tag]"` with empty string. An obvious solution would be to do something like this: `mystring = mystring.replaceAll("(?<=\\[tag)(.*?)(?=\\[/tag])", "");` However, I feel like that would be hacking around the problem because I'm not really capturing a full tag. Could anyone provide me with a solution to this problem? Thanks!<issue_comment>username_1: I guess I've got it. I thought long and hard about what @AshishMathew said, and yeah, lookbehinds can't have unfixed, lengths, but maybe instead of replacing it with nothing, we add a `]` to it, like so: ``` mystring = mystring.replaceAll("(?<=\\[tag)(.*?)(?=\\[/tag])", "]"); ``` `(?<=\\[tag)` is the look-behind which matches `[tag` `(.*?)` is all the code between `[tag` and `[/tag]`, which may even be the parameters of the tag, all of which is replaced by a `]` When I tried this code by replacing the match with `""`, I got `[tag[/tag] untagged text [tag[/tag]` as the output. Hence, by replacing the match with a `]` instead of nothing, you get the (hopefully) desired output. So this is my **lazy** solution (pardon the regex pun) to the problem. Upvotes: 2 <issue_comment>username_2: I suggest matching the whole tag with content and replacing with the opening/closing tags without content : ``` mystring.replaceAll("\\[tag[^\\]]*\\][^\\[]*\\[/tag]", "[tag][/tag]") ``` [Ideone test](https://ideone.com/eJmO0g). Note that I didn't bother conserving the tag attributes since you mentionned in another answer's comments that you didn't need them, but they could be kept by using a capturing group. Upvotes: 2 [selected_answer]
2018/03/21
758
2,846
<issue_start>username_0: Ok I've spent a week trying to figure this out but I can't seem to find what I'm looking for. There are two similar problems that, I think, are easier to explain after seeing the pseudo(ish) code. Here is the first one ``` SELECT P_CODE, P_DESCRIPT, @diff FROM PRODUCT WHERE @diff := (SELECT ROUND(ABS(P_PRICE -(SUM(P_PRICE)/COUNT(P_PRICE))),2) FROM PRODUCT WHERE P_PRICE in (SELECT P_PRICE FROM PRODUCT)); ``` Basically, I have product table where I'm trying to return the primary key, description, and difference between the product's price and the average price for all entries. In a similar note here is the second problem ``` SELECT *, @val FROM LINE WHERE P_CODE in (SELECT P_CODE FROM LINE HAVING COUNT(P_CODE) > (@val = (SELECT COUNT(*) FROM LINE)/(SELECT COUNT(DISTINCT P_CODE) FROM LINE))); ``` Here I'm trying to return all fields from the line table (which is basically a receipt table) for which the product for that entry has more items sold than the average number sold Is it clear what I'm trying to do with these? I'm trying to return other values as well as a calculated value that I can only calculate using values from another table (in list form if that wasn't clear). I'm not too sure but perhaps JOIN statements might work here? I'm new to mysql and haven't quite understood how to best employ JOIN statements yet. If someone could show me how to approach problems like these or at least point me to a link that describes how to do this (as I've had no luck finding one)<issue_comment>username_1: I guess I've got it. I thought long and hard about what @AshishMathew said, and yeah, lookbehinds can't have unfixed, lengths, but maybe instead of replacing it with nothing, we add a `]` to it, like so: ``` mystring = mystring.replaceAll("(?<=\\[tag)(.*?)(?=\\[/tag])", "]"); ``` `(?<=\\[tag)` is the look-behind which matches `[tag` `(.*?)` is all the code between `[tag` and `[/tag]`, which may even be the parameters of the tag, all of which is replaced by a `]` When I tried this code by replacing the match with `""`, I got `[tag[/tag] untagged text [tag[/tag]` as the output. Hence, by replacing the match with a `]` instead of nothing, you get the (hopefully) desired output. So this is my **lazy** solution (pardon the regex pun) to the problem. Upvotes: 2 <issue_comment>username_2: I suggest matching the whole tag with content and replacing with the opening/closing tags without content : ``` mystring.replaceAll("\\[tag[^\\]]*\\][^\\[]*\\[/tag]", "[tag][/tag]") ``` [Ideone test](https://ideone.com/eJmO0g). Note that I didn't bother conserving the tag attributes since you mentionned in another answer's comments that you didn't need them, but they could be kept by using a capturing group. Upvotes: 2 [selected_answer]
2018/03/21
521
2,061
<issue_start>username_0: I have an application in ASP.NET MVC that we bought that has multiples possible routes and that might get even bigger because we can dynamically add pluggins. We're talking hundreds of different pages and controllers. We modified/added the ones that we needed (mostly reskinning). And now we have to make sure that only the pages that we modified are accessible to the user. Someone that knows the application that we bought could go to routes that we don't want him to see. So in the end, my question is : Is there a way to deny access to all the routes except the ones that I want. Since the application is HUGE. I can't/don't want to go to individual controller and add a redirect or a Data annotation. Also, I dont want to list every url I deny because that would also be crazy long and would not work if we add a plugin later on. I have like 300 url to deny, 20 to allow.. I'm thinking something like this in the webconfig ?? ``` deny * permit mycontroller/action1 permit mycontroller/action2 ``` I should also add, that this application does not use any kind of authentication/authorization. I want any user to be able to use the application. We're hosting it in Azure wep app, would that be a solution ?<issue_comment>username_1: use the `[Authorize]` attribute at the controller level and then `[AllowAnonymous]` for the action ``` [Authorize] Public class mycontroller : Controller { Public ActionResult action1 () { Return View(); } [AllowAnonymous] Public ActionResult action2 () { Return View (); } } ``` Upvotes: -1 <issue_comment>username_2: If anyone is stuck with the same problem, here's how I it. It's all done in the web.config of the application: You start by denying everything with this ``` ``` Then, you can whitelist the URLs that you want like this: ``` ``` ``` ``` So every URL dans does not have a location tag is considered not valid and will raise a 401 exception. You can then do what you want from there. Hope this helps someone :) Upvotes: 2 [selected_answer]
2018/03/21
290
1,085
<issue_start>username_0: Using Ruby on Rails 5.0.3 . I want to set some value in cookie using JavaScript (when button clicked), and get it in Rails. I know how to access session in Rails, which is `session[:some_key]` or `cookies`. But I don't know how to do in JavaScript. (it must be able to accessed from Rails `session` or `cookies`.) How can I do it in JS? Or any other ways to **save some value in JS, and get it later in Rails** ?<issue_comment>username_1: Unfortunately, you can't modify Rails session from the client side, even if it stored in cookies. Because the rails session is encrypted. As a solution, you can use regular cookies, not the Rails session. Check <http://api.rubyonrails.org/v5.1/classes/ActionDispatch/Cookies.html> <https://www.w3schools.com/js/js_cookies.asp> for more information. Upvotes: 2 <issue_comment>username_2: The cookie for the rails app is just some hashed string to ID the server cookie, which has the data. What they said, use Ajax to some controller method you write to update your necessary info into the rails cookie. Upvotes: 0
2018/03/21
570
2,028
<issue_start>username_0: I have created a react-native project XYZApp using `react-native init` which is pushed in GitHub repo. Now when I am cloning the project on a different system. following is the directory structure app/XYZApp Following is the set of commands and steps I am using. ``` cd app brew install node brew install watchman ``` # ``` npm install -g react-native-cli ``` # ``` install android studio and required SDKs ``` # ``` install X-Code ``` # = ``` react-native init MyApp prompt: Directory MyApp already exists. Continue?: (no) I am typing - yes npm install [all dependencies] react-native link ``` Through all the above steps, some new default files are getting created which runs a default app, with some minor changes in those files I am able to run the app. But I know this is not the correct way of doing this. I tried several other methods also, like `npm start` I checked several links but could not find the correct method for the setup after cloning. Most of them are mentioned for `create-react-native-app` method. It will be great if someone can help me regarding this.<issue_comment>username_1: after cloning Don't do this ``` react-native init MyApp prompt: Directory MyApp already exists. Continue?: (no) I am typing - yes npm install [all dependencies] react-native link ``` just go to cloned app directory XYZApp and do ``` npm install ``` and all set to run the app using ``` react-native run-android ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Update 2019 **React Native 0.60.0+**: First you need to install all the node modules by running ``` npm install ``` If you're using libraries with native dependencies like [react-native-gesture-handler](https://github.com/kmagiera/react-native-gesture-handler) these libraries need to be linked correctly. To do so run ``` react-native link ``` For setting up the iOS project correctly you need to install the CocoaPods dependencies: ``` cd ios && pod install ``` Upvotes: 0
2018/03/21
397
1,476
<issue_start>username_0: I'm trying to display a dropdown of distinct Brands, furthermore i'm looking to display a summary of the number of items within that match a WHERE statement. Looking around here i'm only able to find solutions to part of my problem, but not the SELECT WHERE part that needs to be nested... Progress so far... ``` SELECT brand,COUNT(DISTINCT linked_id WHERE done=0) as count FROM products GROUP BY brand ORDER BY brand; ``` This clearly won't run, but does provide some sudo to what i'm looking to achieve. Has anyone done something like this before?<issue_comment>username_1: after cloning Don't do this ``` react-native init MyApp prompt: Directory MyApp already exists. Continue?: (no) I am typing - yes npm install [all dependencies] react-native link ``` just go to cloned app directory XYZApp and do ``` npm install ``` and all set to run the app using ``` react-native run-android ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: Update 2019 **React Native 0.60.0+**: First you need to install all the node modules by running ``` npm install ``` If you're using libraries with native dependencies like [react-native-gesture-handler](https://github.com/kmagiera/react-native-gesture-handler) these libraries need to be linked correctly. To do so run ``` react-native link ``` For setting up the iOS project correctly you need to install the CocoaPods dependencies: ``` cd ios && pod install ``` Upvotes: 0
2018/03/21
1,207
4,428
<issue_start>username_0: I am getting an error: > > Ambiguous resolution: module ".../myModule.js" tries to require > 'react-native', but there are several files providing this module. You > can delete or fix them: > > > .../MyProject/ios/Pods/React/package.json > > > .../MyProject/node\_modules/react-native/package.json > > > I am almost certain that this is due to using Podfiles, specifically, when they install the "React" folder. However, I had to use Podfiles in order to install `react-native-firebase`. With that said, when I delete the React folder under my Pods folder (ios/Pods/React), I can no longer use `react-native-firebase`. There was a fix floating around GitHub, which suggested appending the Podfile with: ``` post_install do |installer| installer.pods_project.targets.each do |target| if target.name == "React" target.remove_from_project end end end ``` But this did not work for me. Has anyone encountered this problem before? If it is relevant, this is the podfile that I am using: ``` platform :ios, '8.0' target 'MyProject2' do pod 'Firebase/Core' pod 'Firebase/Database' pod 'Firebase/Messaging' pod 'RNSVG', :path => '../node_modules/react-native-svg' target 'MyProject2Tests' do inherit! :search_paths # Pods for testing end post_install do |installer| installer.pods_project.targets.each do |target| if target.name == "React" target.remove_from_project end end end end ``` EDIT: When I remove the 'RNSVG' from my Podfile, I get an error stating: "Invariant Violation: Native component for 'RNSVGPath' does not exist". I have both ran react-native link and followed the instructions for manual installation for `react-native-svg`.<issue_comment>username_1: Taking a look at `react-native-svg`, their Podfile specifies React as a dependency. To keep things simple, I would suggest that you use the recommended `react-native link` command to install this library rather than specifying it within the Podfile. Once you've removed `react-native-svg` you will probably want to clear down your `Podfile` folder and re-run `pod install` Upvotes: -1 <issue_comment>username_2: I had to manually link the React pod to `node_modules`: `pod 'React', :path => '../node_modules/react-native'` Upvotes: 1 <issue_comment>username_3: I just finished managing this problem when making my app work for iOS. I used username_1' solution and also... The haste packaging manager was finding instances of my modules both from my root `node_modules` folder and from the `node_modules` folder inside my Build folder. To solve that, create a file called `rn-cli.config.js` in the root of your project: ``` const blacklist = require('metro-config/src/defaults/blacklist'); module.exports = { resolver: { blacklistRE: blacklist([ /Build\/.*/, ]) }, }; ``` Upvotes: 0 <issue_comment>username_4: This problem seems to happen anytime a Pod is added with a React dependency. Once something has a react dependency and the React Pod is not added, it will often attempt to install it, finding an old version of React on CocoaPods (0.11). To avoid this, you need to add the dependency and required subdependencies explicitly, per the documentation for react-native here: [react-native cocoapods docs](https://facebook.github.io/react-native/docs/0.59/integration-with-existing-apps#configuring-cocoapods-dependencies). For instance, when I added the `react-native-community/async-storage` module, I had to add all of this to my podfile which previously had only AppCenter and Firebase related dependencies: ``` pod 'React', :path => '../node_modules/react-native', :subspecs => [ 'Core', 'CxxBridge', # Include this for RN >= 0.47 'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43 'RCTText', 'RCTNetwork', 'RCTWebSocket', # Needed for debugging 'RCTAnimation', # Needed for FlatList and animations running on native UI thread # Add any other subspecs you want to use in your project ] # Explicitly include Yoga if you are using RN >= 0.42.0 pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga' pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec' pod 'RNCAsyncStorage', :path => '../node_modules/@react-native-community/async-storage' ``` Upvotes: 0
2018/03/21
2,153
8,754
<issue_start>username_0: I created a custom dialog preference in my Android application, but I can not figure out how to get the dialog which is displayed to span the complete width of the display. [image of dialog with too much space on left and right side](https://i.stack.imgur.com/fAUzj.png) I found many proposed solutions to get a normal Dialog in full screen mode * [Android get full width for custom Dialog](https://stackoverflow.com/questions/28513616/android-get-full-width-for-custom-dialog) * <https://gist.github.com/koocbor/88db64192638bff09aa4> * <http://blog.jimbaca.com/force-dialog-to-take-up-full-screen-width/> But setting the attributes via getWindow does not work: ``` @Override public Dialog getDialog() { Dialog dialog = super.getDialog(); dialog.getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // or // dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); return dialog; } ``` And applying a full screen theme to my dialogs root element didn't do the job neither: ``` ``` Moreover I'm not able to access the onCreate Method (at least I don't know how) of the Dialog, to set the style there. **Did anyone had the same problem and figured out a solution for this very specific issue?** My layout: ``` ``` My custom preference class ``` public class WheelCircumferencePreference extends android.preference.DialogPreference { private static String TAG = "CustomSwitchPreference"; private int mWheelCircumference; public static int WHEEL_CIRCUMFERENCE_DEFAULT = 2125; private int mDialogLayoutResId = R.layout.pref_dialog_wheelcircumference; public WheelCircumferencePreference(Context context) { this(context, null); } public WheelCircumferencePreference(Context context, AttributeSet attrs) { this(context, attrs, R.attr.dialogPreferenceStyle); } public WheelCircumferencePreference(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setLayoutResource(R.layout.custom_preference); setDialogLayoutResource(mDialogLayoutResId); setPositiveButtonText(getContext().getString(R.string.dialog_save)); setNegativeButtonText(getContext().getString(R.string.dialog_cancel)); } @Override protected Object onGetDefaultValue(TypedArray a, int index) { // Default value from attribute. Fallback value is set to WHEEL_CIRCUMFERENCE_DEFAULT. return a.getInteger(index, WHEEL_CIRCUMFERENCE_DEFAULT); } @Override protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) { would load value from shared preferences if (restorePersistedValue) { mWheelCircumference = getPersistedInt(WHEEL_CIRCUMFERENCE_DEFAULT); } else { mWheelCircumference = (Integer) defaultValue; persistInt(mWheelCircumference); } } private EditText mWheelCircumferenceEt; @Override protected void onBindDialogView(View view) { mWheelCircumferenceEt = view.findViewById(R.id.pref_dialog_wheelcircumference_et); if (mWheelCircumferenceEt == null) { throw new IllegalStateException("preference dialog view must contain" + " a EditText with id 'pref_dialog_wheelcircumference_et'"); } mWheelCircumferenceEt.setText(Integer.toString(mWheelCircumference)); super.onBindDialogView(view); } @Override public Dialog getDialog() { //Dialog dialog = super.getDialog(); // WindowManager.LayoutParams p = getDialog().getWindow().getAttributes(); //p.height = LinearLayout.LayoutParams.WRAP_CONTENT; //dialog.getWindow().setAttributes(p); return dialog; } @Override protected void onDialogClosed(boolean positiveResult) { if (positiveResult) { String circumferenceText = mWheelCircumferenceEt.getText().toString(); try { mWheelCircumference = Integer.parseInt(circumferenceText); } catch (Exception e) { NLog.e(TAG, "onDialogClosed - ", e); mWheelCircumference = WheelCircumferencePreference.WHEEL_CIRCUMFERENCE_DEFAULT; } persistInt(mWheelCircumference); } } ``` **Edit:** Actually I only want the dialog to span over the full width of the screen, not the height. If I would use a additional PreferenceFragment (as the DialogPreference is already embedded in a PreferenceFragment ) the "Dialog" (aka Fragment) would take the complete width and height (i guess). I already implemented a solution without a DialogPrefrence, that works but is not exactly elegant * using just a normal EditTextPreference * adding an onPreferenceClickListener to this preference in my SettingsFragment Code + the ClickListener displays a simple Dialog Example: ``` Preference preference = findPreference(EXAMPLE_PREFRENCE); if (preference != null) { preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { // showDialog(); } }); ``` But as I have a lot of preferences which will display dialogs the code for the dialog creation and display bloads the SettingsFragment and makes it nearly unreadable. Therefore I thought it would be a nice solution to put the responsibility of displaying the dialog and handling the preference values to the Preference and the XML layout. Unfortunately I got stuck with the "full width issue" mentioned above. Note: fixed the code of getDialog as I tested different versions (also in combination with the xml theme set)<issue_comment>username_1: Try this in the onResume of your dialog. ``` // Store access variables for window and blank point Window window = getDialog().getWindow(); Point size = new Point(); // Store dimensions of the screen in `size` Display display = window.getWindowManager().getDefaultDisplay(); display.getSize(size); // Set the width of the dialog proportional to 75% of the screen width and height window.setLayout((int) (size.x * 0.75), (int) (size.y * 0.75)); window.setGravity(Gravity.CENTER); // Call super onResume after sizing ``` Adjust accordingly for 100%. It works great for a dialogFragment. Haven't tried it for your case though. Upvotes: 0 <issue_comment>username_2: Wait, you're not looking for the bog-standard 'Pref settings user options appear in a dialog' thing are you? That's almost definitely already done in AndroidStudio's `add activity...> Settings Activity` in boiler plate, check it out, or look for sample settings apps --- Anyway, I do actually have a fullscreen dialog in my app, although it purposely doesn't fill the full screen, and I actually use an activity with some fragments now instead. Personally I think this is what your problem is, I remember having this exact issue when I first needed a dialog like this. You should just use activities and have up navigation (if you want a full screen "popup" type thing you could use the Navigation pattern that makes the home/up button an 'X' instead of a '<'); Or anything else, you don't need to have a dialog explicitly, and if you do then extend activity or dialog and get what you want. Here's my activity stuff in case it's any use my theme: ``` <item name="windowActionBar">true</item> <item name="windowNoTitle">true</item> ``` my onCreate gist: ``` @Override public void onCreate(@Nullable Bundle savedInstanceState) { ... requestWindowFeature(Window.FEATURE_NO_TITLE); ... super.onCreate(savedInstanceState); setContentView(getConcreteContentView()); ButterKnife.bind(this); setUpUIComponents(); ... } ``` my general layout gist: ``` ``` Bon Chance! Upvotes: 0 <issue_comment>username_3: Finally I did find a solution for this problem: Fetch the AlertDialog of the Preference in showDialog method ``` @Override protected void showDialog(Bundle state) { super.showDialog(state); CustomDialogPreference.makeDialogFullScreen((AlertDialog) getDialog()); } ``` make it span the complete width: ``` public static void makeDialogFullScreen(AlertDialog d) { NLog.d(TAG, "makeDialogFullScreen enter "); if (d != null) { ViewGroup.LayoutParams params = d.getWindow().getAttributes(); if (params != null) { params.width = WindowManager.LayoutParams.MATCH_PARENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } } } ``` Upvotes: 2 [selected_answer]
2018/03/21
1,088
4,426
<issue_start>username_0: I have a design question im not too sure on. Say i have this "policy" sort of like a someone have car insurance or something. There are tons of different kinds of policies that pop up all the time, so like earthquake, or trucking, or like drone, etc. I want this to be generic so they all sort of fit into this object. I was thinking of storing most of the details in a string hashmap. ``` public class Policy { static final long serialVersionUID = 20130901L; private String policynumber; private int policyId; private String pendingDocType; private int transactionTypeId; private List lobs; private List markets; private Insured insured; private Agent agent; private Map locations; private Map details; } ``` Then for each different type, i create a wrapper class that extends policy with methods for accessing fields according the the type that it is. So if its a drone, i would have methods like ``` getAnnualFlightDistance() { return details.get("flightdistance"); } getAnnualPremium() { // Some method to calculate the current money spent on drone } ``` But just have helper methods around the main Policy class. I would make them member variables for each field attached to it, but they're always changing variables a new things being added, i thought having just like a bin for the terms would allow for a constant evolving object.<issue_comment>username_1: Try this in the onResume of your dialog. ``` // Store access variables for window and blank point Window window = getDialog().getWindow(); Point size = new Point(); // Store dimensions of the screen in `size` Display display = window.getWindowManager().getDefaultDisplay(); display.getSize(size); // Set the width of the dialog proportional to 75% of the screen width and height window.setLayout((int) (size.x * 0.75), (int) (size.y * 0.75)); window.setGravity(Gravity.CENTER); // Call super onResume after sizing ``` Adjust accordingly for 100%. It works great for a dialogFragment. Haven't tried it for your case though. Upvotes: 0 <issue_comment>username_2: Wait, you're not looking for the bog-standard 'Pref settings user options appear in a dialog' thing are you? That's almost definitely already done in AndroidStudio's `add activity...> Settings Activity` in boiler plate, check it out, or look for sample settings apps --- Anyway, I do actually have a fullscreen dialog in my app, although it purposely doesn't fill the full screen, and I actually use an activity with some fragments now instead. Personally I think this is what your problem is, I remember having this exact issue when I first needed a dialog like this. You should just use activities and have up navigation (if you want a full screen "popup" type thing you could use the Navigation pattern that makes the home/up button an 'X' instead of a '<'); Or anything else, you don't need to have a dialog explicitly, and if you do then extend activity or dialog and get what you want. Here's my activity stuff in case it's any use my theme: ``` <item name="windowActionBar">true</item> <item name="windowNoTitle">true</item> ``` my onCreate gist: ``` @Override public void onCreate(@Nullable Bundle savedInstanceState) { ... requestWindowFeature(Window.FEATURE_NO_TITLE); ... super.onCreate(savedInstanceState); setContentView(getConcreteContentView()); ButterKnife.bind(this); setUpUIComponents(); ... } ``` my general layout gist: ``` ``` Bon Chance! Upvotes: 0 <issue_comment>username_3: Finally I did find a solution for this problem: Fetch the AlertDialog of the Preference in showDialog method ``` @Override protected void showDialog(Bundle state) { super.showDialog(state); CustomDialogPreference.makeDialogFullScreen((AlertDialog) getDialog()); } ``` make it span the complete width: ``` public static void makeDialogFullScreen(AlertDialog d) { NLog.d(TAG, "makeDialogFullScreen enter "); if (d != null) { ViewGroup.LayoutParams params = d.getWindow().getAttributes(); if (params != null) { params.width = WindowManager.LayoutParams.MATCH_PARENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } } } ``` Upvotes: 2 [selected_answer]
2018/03/21
1,454
5,759
<issue_start>username_0: I'm trying to call a DAO method in my Java EE project to add data to a table in MySQL. **Here is the how the code looks:** ```java @Override String execute(HttpServletRequest request, HttpServletResponse response) throws LoginSampleException { int height = Integer.parseInt(request.getParameter("height")); int length = Integer.parseInt(request.getParameter("length")); int width = Integer.parseInt(request.getParameter("width")); LegoHouseAlgorithm lego = new LegoHouseAlgorithm(); ArrayList bricks = lego.calc(height, length, width); request.setAttribute("longbrick", Integer.toString(bricks.get(0))); request.setAttribute("mediumbrick", Integer.toString(bricks.get(1))); request.setAttribute("shortbrick", Integer.toString(bricks.get(2))); request.setAttribute("wall3", Integer.toString(bricks.get(3))); request.setAttribute("wall4", Integer.toString(bricks.get(4))); request.setAttribute("wall5", Integer.toString(bricks.get(5))); int finalLongBrick = (bricks.get(0) + bricks.get(3)) \* 2; int finalMediumBrick = (bricks.get(1) + bricks.get(4)) \* 2; int finalShortBrick = (bricks.get(2) + bricks.get(5)) \* 2; request.setAttribute("finallongbrick", finalLongBrick); request.setAttribute("finalmediumbrick", finalMediumBrick); request.setAttribute("finalshortbrick", finalShortBrick); try { LogicFacade.makeOrder(height, length, width); } catch (SQLException | ClassNotFoundException ex) { Logger.getLogger(Order.class.getName()).log(Level.SEVERE, null, ex); } return "order"; ``` **`LogicFacade` class:** ```java public static OrderSample makeOrder(int height, int length, int width) throws SQLException, ClassNotFoundException, LoginSampleException{ OrderSample order = new OrderSample(height, width, length); UserMapper.createOrder(order); return order; } public static void createOrder (OrderSample order) throws SQLException, ClassNotFoundException, LoginSampleException{ try{ Connection con = Connector.connection(); String SQL = "INSERT INTO orders (height, length, width) VALUES (?, ?, ?)"; PreparedStatement ps = con.prepareStatement(SQL); ps.setInt(order.getHeigh(), 1); ps.setInt(order.getLength(), 2); ps.setInt(order.getWidth(), 3); ps.executeUpdate(); ResultSet rs = ps.getGeneratedKeys(); rs.next(); int id = rs.getInt(1); order.setId(id); } catch ( ClassNotFoundException | SQLException ex ) { throw new LoginSampleException(ex.getMessage()); } } ``` whatever parameters I type in my HTML form I get the error: ```java Parameter index out of range ((inserted number) > number of parameters, which is 3). ```<issue_comment>username_1: Try this in the onResume of your dialog. ``` // Store access variables for window and blank point Window window = getDialog().getWindow(); Point size = new Point(); // Store dimensions of the screen in `size` Display display = window.getWindowManager().getDefaultDisplay(); display.getSize(size); // Set the width of the dialog proportional to 75% of the screen width and height window.setLayout((int) (size.x * 0.75), (int) (size.y * 0.75)); window.setGravity(Gravity.CENTER); // Call super onResume after sizing ``` Adjust accordingly for 100%. It works great for a dialogFragment. Haven't tried it for your case though. Upvotes: 0 <issue_comment>username_2: Wait, you're not looking for the bog-standard 'Pref settings user options appear in a dialog' thing are you? That's almost definitely already done in AndroidStudio's `add activity...> Settings Activity` in boiler plate, check it out, or look for sample settings apps --- Anyway, I do actually have a fullscreen dialog in my app, although it purposely doesn't fill the full screen, and I actually use an activity with some fragments now instead. Personally I think this is what your problem is, I remember having this exact issue when I first needed a dialog like this. You should just use activities and have up navigation (if you want a full screen "popup" type thing you could use the Navigation pattern that makes the home/up button an 'X' instead of a '<'); Or anything else, you don't need to have a dialog explicitly, and if you do then extend activity or dialog and get what you want. Here's my activity stuff in case it's any use my theme: ``` <item name="windowActionBar">true</item> <item name="windowNoTitle">true</item> ``` my onCreate gist: ``` @Override public void onCreate(@Nullable Bundle savedInstanceState) { ... requestWindowFeature(Window.FEATURE_NO_TITLE); ... super.onCreate(savedInstanceState); setContentView(getConcreteContentView()); ButterKnife.bind(this); setUpUIComponents(); ... } ``` my general layout gist: ``` ``` Bon Chance! Upvotes: 0 <issue_comment>username_3: Finally I did find a solution for this problem: Fetch the AlertDialog of the Preference in showDialog method ``` @Override protected void showDialog(Bundle state) { super.showDialog(state); CustomDialogPreference.makeDialogFullScreen((AlertDialog) getDialog()); } ``` make it span the complete width: ``` public static void makeDialogFullScreen(AlertDialog d) { NLog.d(TAG, "makeDialogFullScreen enter "); if (d != null) { ViewGroup.LayoutParams params = d.getWindow().getAttributes(); if (params != null) { params.width = WindowManager.LayoutParams.MATCH_PARENT; params.height = WindowManager.LayoutParams.WRAP_CONTENT; d.getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } } } ``` Upvotes: 2 [selected_answer]
2018/03/21
973
2,919
<issue_start>username_0: I am trying to concatenate scala list in loop using below code. ``` var names: List[String] = Nil val cluster_id = List("149095311_0", "149095311_1") for (id <- cluster_id) { val influencers_name = searchIndex(s"id : $id", "id", "influencers", searcher) println("In Loop " + influencers_name) names :::= influencers_name } for(n <- names) println("List element -> " + n) ``` But when I iterate over final list it give me individual list's instead of individual elements of concatenated List. Below is the O/P of above code: ``` In Loop List(kroger 10TV DispatchAlerts) In Loop List(kroger seanhannity SenTedCruz) List element -> kroger seanhannity SenTedCruz List element -> kroger 10TV DispatchAlerts ```<issue_comment>username_1: It looks like the problem is in searchIndex method that is retreiving a List[String] with a single String that contain all the values separated by a space, fix that method to make sure that it retrieves a List with one elemente per value. To check if this is right try this, this is just a workaround, you should fix searchIndex ``` var names: List[String] = Nil val cluster_id = List("149095311_0", "149095311_1") for (id <- cluster_id) { val influencers_name = searchIndex(s"id : $id", "id", "influencers", searcher).flatMap(_.split(' ')) ("In Loop " + influencers_name) names = influencers_name ::: names } for(n <- names) println("List element -> " + n) ``` Upvotes: 0 <issue_comment>username_2: The reason is, When you do names ::: List("anything") -> it does not add anything to names. Instead, it creates a new collection. For example, ``` scala> var names: List[String] = Nil names: List[String] = List() scala> names ::: List("mahesh") res0: List[String] = List(mahesh) You can achive that scala> names ::: List("chand") res1: List[String] = List(chand) scala> res0 ::: List("chand") res2: List[String] = List(mahesh, chand) ``` When I added "Mahesh" to it, it has created new collection naming res0. When I added again different string, here "chand" it has created another collection. But when I added "chand" to the created collection, it has concatenated to correct collection, You can achive What you want to do, ``` scala> for(i <- List("a" ,"b" )){ | names = i :: names } scala> names res11: List[String] = List(b, a) ``` Upvotes: 0 <issue_comment>username_3: Your code isn't very functional in that you are mutating variables. The following is more elegant: ``` def searchIndex(s: String): List[String] = { if (s == "149095311_0") List("kroger 10TV DispatchAlerts") else List("<NAME>") } val cluster_id = List("149095311_0", "149095311_1") val names = cluster_id.foldLeft(List[String]()) { (acc, id) => acc ++ searchIndex(id) } for(n <- names) println("List element -> " + n) ``` Where '++' is used to concatenate the elements of two lists. Upvotes: 2 [selected_answer]
2018/03/21
562
1,793
<issue_start>username_0: I am trying to load the node from csv in Neo4j, however, every time I try to do this I get such an error: ``` Neo.ClientError.Statement.ExternalResourceFailed: Couldn't load the external resource at: file:/var/lib/neo4j/import/events.csv ``` My event.csv file is in `/var/lib/neo4j/import` directory with 777 permissions. The query I try to run looks like this: ``` USING PERIODIC COMMIT 500 LOAD CSV WITH HEADERS FROM "file:///events.csv" AS line CREATE (e:Event { event_id: toInteger(line.event_id), created: line.created, description: line.description }) ``` I set up Neo4j using the latest version of docker image. What might be wrong with file permissions or file location?<issue_comment>username_1: Docker container cannot get access to files outside on the host machine, unless you mount those files to the container. Solution is to bind-mount the directory to your container when calling the `docker run` command: ``` docker run -v /var/lib/neo4j/import:/var/lib/neo4j/import ... ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: In addition to mounting the "dataimport" volume when running the container, make sure you have the following configuration in the neo4j.conf file in conf dir: ``` server.directories.import=/var/lib/neo4j/import dbms.security.allow_csv_import_from_file_urls=true ``` This is my docker run command: ``` docker run \ --restart always \ --detach \ --publish=7474:7474 --publish=7687:7687 \ --env NEO4J_PLUGINS='["apoc", "graph-data-science", "bloom"]' \ --volume=/opt/neo4j/data:/data \ --volume=/opt/neo4j/logs:/logs \ --volume=/opt/neo4j/conf:/conf \ --volume=/opt/neo4j/import:/var/lib/neo4j/import \ --env NEO4J_AUTH=neo4j/my_password\ neo4j:5.9.0 ``` Upvotes: 0
2018/03/21
546
2,164
<issue_start>username_0: My python3 lambda functions process records from dynamodb. I am printing every step of my lambda execution in cloudwatch. Now I am at a stage of deploying and monitoring my lambdas in production. Is there a way I can know which records are executed by lambda as a whole in consolidated way? I am also using X-ray to understand how much time and errors that my lambdas are taking. Besides, measuring the duration, invocation, errors. I want a way to know how many records are executed? thanks.<issue_comment>username_1: You could use [CloudWatchLogs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) for logging in the custom log group and log stream. You will be able to change in the configuration names group/stream during the deployment to different stages. Check out how to do it with boto3 - [Client.put\_log\_events](http://boto3.readthedocs.io/en/latest/reference/services/logs.html#CloudWatchLogs.Client.put_log_events) You could check my sample for NodeJS - [there](https://stackoverflow.com/a/48807502/182344). The code is much simpler and graceful for python. **PS:** Drop me a comment if you have any issue with converting. Upvotes: 3 [selected_answer]<issue_comment>username_2: While printing every line to log might help you to debug and troubleshoot your code, this is a very manual and not scaleable option. In addition, you would lose your mind going through endless logs. In the serverless world (and specifically in AWS, where you have Lambda, DynamoDB, SQS, SNS, API Gateway, and lots of other resources), you should use the right tools that will give you visibility into your architecture, allow you to troubleshoot issues quickly, and will identify serverless specific issues (timeouts, out of memory, ..). One thing you can try out is to [stream out all your logs](https://github.com/gilt/cloudwatch-elk) from CloudWatch to an external service such as ELK. It will allow you to easily explore them. Otherwise, I'm recommending to use a dedicated solution for serverless - there are several out there (our own [Epsagon](https://epsagon.com), IOpipe, Dashbird). Upvotes: 0
2018/03/21
940
2,830
<issue_start>username_0: I am trying to upload a csv file from Angular to Asp.NET Core webapi. But getting empty object at the web abi although Fiddler shows something went over the network. I am using Kendo UI to upload the file. Can you please tell me how to resolve this ? I tried [FromBody] and [FromForm] but no difference. ``` [HttpPost] [Route(ApiRoutes.EodVariationMargin)] public async Task UploadPlugAsync(object plugs) { var content = JsonConvert.SerializeObject(plugs); \_logger.LogInformation(content); return Ok(); } Request Count: 1 Bytes Sent: 1,470 (headers:539; body:931) Bytes Received: 198 (headers:198; body:0) ACTUAL PERFORMANCE -------------- ClientConnected: 11:34:36.511 ClientBeginRequest: 11:34:44.561 GotRequestHeaders: 11:34:44.561 ClientDoneRequest: 11:34:44.566 Determine Gateway: 0ms DNS Lookup: 0ms TCP/IP Connect: 0ms HTTPS Handshake: 0ms ServerConnected: 11:34:36.512 FiddlerBeginRequest: 11:34:44.566 ServerGotRequest: 11:34:44.566 ServerBeginResponse: 11:35:15.629 GotResponseHeaders: 11:35:15.629 ServerDoneResponse: 11:35:15.629 ClientBeginResponse: 11:35:15.629 ClientDoneResponse: 11:35:15.630 Overall Elapsed: 0:00:31.069 RESPONSE BYTES (by Content-Type) -------------- ~headers~: 198 ```<issue_comment>username_1: I am using this and it works: ``` [Route("API/files")] public class FileController : Controller { [HttpPost("Upload")] public IActionResult SaveUploaded() { List result = new List(); var files = this.Request.Form.Files; foreach (var file in files) { using (FileStream fs = System.IO.File.Create("Destination")) { file.CopyTo(fs); fs.Flush(); } result.Add(file.FileName); } return result.ToJson(); } } ``` And Angular html: ``` ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You cannot bind to an action param of type `object`. Rather, I suppose you *can* but it won't do anything for you because `object` has no properties. Hence, the modelbinder will simply discard everything that's posted. If you're trying to accept an upload in that param, then it should be of type `IFormFile`. If you're trying to accept a JSON payload, then it should be an actual *class* that you create to represent that payload. For example, if you were sending JSON like: ``` { "foo": "bar" } ``` Then, you need a class like: ``` public class MyDTO { public string Foo { get; set; } } ``` If you're trying to send an upload as part of your JSON payload, then your DTO class should have a `byte[]` property named after the key of the file upload, and your upload data should be sent as Base 64. For example: ``` { // other stuff "file": "{base64 encoded byte array}" } ``` With a DTO like: ``` public class MyDTO { // other properties public byte[] File { get; set; } } ``` Upvotes: 1
2018/03/21
2,539
12,116
<issue_start>username_0: I need to get data frame from a json response with each content's `id`,`likeCount` and `displayName`. Everything else works fine except the `displayname`. It gives an error: ``` KeyError: 'author' ``` My code I use: ``` df=pd.DataFrame([]) for i in json_data['list']: df=df.append(pd.DataFrame({'Content_id':[i['contentID']],'subject':[i['subject']],'published':[i['published']],'updated':[i['updated']],'viewCount':i['viewCount'],'type':i['type'],'name':[i['author']['displayName']]},index=[0]),ignore_index=True) print(df.head()) ``` ```html { "itemsPerPage": 100, "links": { "next": "https:" }, "list": [ { "id": "77248", "resources": { "entitlements": { "allowed": [ "GET" ], "ref": "https:" }, "outcomeTypes": { "allowed": [ "GET" ], "ref": "https:" }, "childOutcomeTypes": { "allowed": [ "GET" ], "ref": "https:" }, "followingIn": { "allowed": [ "POST", "GET" ], "ref": "https:" }, "editHTML": { "allowed": [ "GET" ], "ref": "https:" }, "attachments": { "allowed": [ "POST", "GET" ], "ref": "https:" }, "comments": { "allowed": [ "POST", "GET" ], "ref": "https:" }, "read": { "allowed": [ "DELETE", "POST" ], "ref": "https:" }, "followers": { "allowed": [ "GET" ], "ref": "https" }, "versions": { "allowed": [ "GET" ], "ref": "https:" }, "outcomes": { "allowed": [ "POST", "GET" ], "ref": "https" }, "self": { "allowed": [ "GET", "PUT" ], "ref": "https:" }, "html": { "allowed": [ "GET" ], "ref": "https:" }, "extprops": { "allowed": [ "DELETE", "POST", "GET" ], "ref": "https:" }, "likes": { "allowed": [ "POST", "GET" ], "ref": "https:" } }, "followerCount": 1, "followed": false, "likeCount": 0, "published": "2018-03-20T17:44:07.623+0000", "tags": [], "updated": "2018-03-20T17:44:07.639+0000", "iconCss": "jive-icon-document", "parentPlace": { "id": "1063", "html": "https:", "name": "<NAME>", "type": "group", "uri": "https:" }, "contentID": "1720297", "author": { "id": "361666", "resources": { "reports": { "allowed": [ "GET" ], "ref": "https:" }, "followingIn": { "allowed": [ "POST", "GET" ], "ref": "https:" }, "images": { "allowed": [ "GET" ], "ref": "https:" }, "activity": { "allowed": [ "GET" ], "ref": "https:" }, "manager": { "allowed": [ "GET" ], "ref": "https:" }, "social": { "allowed": [ "GET" ], "ref": "https:" }, "recognition": { "allowed": [ "GET" ], "ref": "https:" }, "trendingContent": { "allowed": [ "GET" ], "ref": "https:" }, "trendingPlaces": { "allowed": [ "GET" ], "ref": "https:" }, "avatar": { "allowed": [ "GET" ], "ref": "https:" }, "followers": { "allowed": [ "GET" ], "ref": "https:" }, "colleagues": { "allowed": [ "GET" ], "ref": "https" }, "following": { "allowed": [ "GET" ], "ref": "https:" }, "members": { "allowed": [ "GET" ], "ref": "https:" }, "self": { "allowed": [ "GET" ], "ref": "https:" }, "html": { "allowed": [ "GET" ], "ref": "https:" }, "extprops": { "allowed": [ "GET" ], "ref": "https:" } }, "displayName": "R S", "emails": [ { "jive_label": "Email", "primary": true, "type": "work", "value": "<EMAIL>", "jive_displayOrder": 2, "jive_showSummaryLabel": false } ], "jive": { "enabled": true, "level": { "description": "Level 2", "imageURI": "https:", "name": "Novice", "points": 154 }, "externalContributor": false, "username": "522164052a", "visible": true }, "name": { "familyName": "S", "formatted": "R S", "givenName": "R" }, "type": "person" }, "content": { "text": "test zebra madagascar ", "editable": false, "type": "text/html" }, "parent": "https:", "favoriteCount": 0, "replyCount": 0, "status": "published", "subject": "Zebra", "viewCount": 2, "visibleToExternalContributors": false, "parentVisible": true, "parentContentVisible": true, "lastActivity": 1521567847639, "authorship": "open", "categories": [], "visibility": "place", "outcomeTypes": [ { "id": "3", "name": "pending", "confirmUnmark": false, "shareable": true, "confirmExclusion": false, "noteRequired": true, "urlAllowed": false, "generalNote": false }, { "id": "6", "name": "success", "communityAudience": "true", "confirmUnmark": false, "shareable": false, "confirmExclusion": false, "noteRequired": true, "urlAllowed": false, "generalNote": true }, { "id": "2", "name": "finalized", "confirmUnmark": true, "shareable": false, "confirmExclusion": true, "noteRequired": false, "urlAllowed": false, "generalNote": false }, { "id": "9", "name": "wip", "confirmContentEdit": "true", "confirmUnmark": true, "shareable": false, "confirmExclusion": true, "noteRequired": false, "urlAllowed": false, "generalNote": false }, { "id": "7", "name": "outdated", "confirmUnmark": false, "shareable": false, "confirmExclusion": false, "noteRequired": false, "urlAllowed": true, "generalNote": false } ], "attachments": [], "restrictComments": false, "type": "document", "lastActivityDate": "2018-03-20T17:44:07.639+0000" } ], "startIndex":0 ``` My desired output is, [![enter image description here](https://i.stack.imgur.com/N0Jkd.jpg)](https://i.stack.imgur.com/N0Jkd.jpg)<issue_comment>username_1: I am using this and it works: ``` [Route("API/files")] public class FileController : Controller { [HttpPost("Upload")] public IActionResult SaveUploaded() { List result = new List(); var files = this.Request.Form.Files; foreach (var file in files) { using (FileStream fs = System.IO.File.Create("Destination")) { file.CopyTo(fs); fs.Flush(); } result.Add(file.FileName); } return result.ToJson(); } } ``` And Angular html: ``` ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You cannot bind to an action param of type `object`. Rather, I suppose you *can* but it won't do anything for you because `object` has no properties. Hence, the modelbinder will simply discard everything that's posted. If you're trying to accept an upload in that param, then it should be of type `IFormFile`. If you're trying to accept a JSON payload, then it should be an actual *class* that you create to represent that payload. For example, if you were sending JSON like: ``` { "foo": "bar" } ``` Then, you need a class like: ``` public class MyDTO { public string Foo { get; set; } } ``` If you're trying to send an upload as part of your JSON payload, then your DTO class should have a `byte[]` property named after the key of the file upload, and your upload data should be sent as Base 64. For example: ``` { // other stuff "file": "{base64 encoded byte array}" } ``` With a DTO like: ``` public class MyDTO { // other properties public byte[] File { get; set; } } ``` Upvotes: 1
2018/03/21
505
1,449
<issue_start>username_0: I am trying to visualise an image of a number `5`. Initially with code: ``` image(matrix(data[,11552], nrow = 28, byrow = TRUE), col = gray(0:255/255)) ``` it looks like the following image: [![enter image description here](https://i.stack.imgur.com/mD0os.png)](https://i.stack.imgur.com/mD0os.png) When I take a transpose of the matrix using the code: ``` image(t(matrix(data[,11552], nrow = 28, byrow = TRUE)), col = gray(0:255/255)) ``` , it looks like: [![enter image description here](https://i.stack.imgur.com/1jQmt.png)](https://i.stack.imgur.com/1jQmt.png) As you could see, I still cannot get an upright `5`. How could I rotate the image further so that I get `5` in an upright position? The dimension of `data` is given as : ``` [1] 784 11552 ```<issue_comment>username_1: You could try reversing the data (with `rev()`) instead of transposing it? Just a thought, as `t()` flips horizontal and vertical, so that `t(t(data))` = `data`. Upvotes: 0 <issue_comment>username_2: Is the following what you are asking for? ``` windows() image(volcano) windows() image(volcano[nrow(volcano):1, ncol(volcano):1]) ``` Note: I am running this on Windows. **EDIT.** The code above flips the image both horizontally and vertically. If all what is needed is to display the image upside down, just reverse the columns index. ``` windows() image(volcano[, ncol(volcano):1]) ``` Upvotes: 2 [selected_answer]
2018/03/21
377
1,220
<issue_start>username_0: There is a way to check if the string in the column contains another string: ``` df["column"].str.contains("mystring") ``` But I'm looking for the opposite, the column string to be contained in another string, without doing an apply function which I guess is slower than the vectorised `.contains`: ``` df["column"].apply(lambda x: x in "mystring", axis=1) ``` Update with data: ``` mystring = "abc" df = pd.DataFrame({"A": ["ab", "az"]}) df A 0 ab 1 az ``` I would like to show only "ab" because it is contained in mystring.<issue_comment>username_1: You could try reversing the data (with `rev()`) instead of transposing it? Just a thought, as `t()` flips horizontal and vertical, so that `t(t(data))` = `data`. Upvotes: 0 <issue_comment>username_2: Is the following what you are asking for? ``` windows() image(volcano) windows() image(volcano[nrow(volcano):1, ncol(volcano):1]) ``` Note: I am running this on Windows. **EDIT.** The code above flips the image both horizontally and vertically. If all what is needed is to display the image upside down, just reverse the columns index. ``` windows() image(volcano[, ncol(volcano):1]) ``` Upvotes: 2 [selected_answer]
2018/03/21
730
3,054
<issue_start>username_0: I'm using `NumberFormat` in my app to get the currency formatted Strings. Like if a user inputs **12.25** in the field then it will be changed to **$12.25** based on locale. Here the Locale is **en-US**. Now I want to get the 12.25 value as double form the formatted string. To do that I have used: ``` NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue(); ``` Above line giving me the result of 12.25 which is my requirement. But suppose a user changed his locale to something else **en-UK**. Now for that locale above statement is giving me parseException. Because for the locale **en-UK**, currency string **$12.25** is not parsable. So is there any way to get the double value from currency formatted string irrespective of what the locale is?<issue_comment>username_1: What about ``` new Double(NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue()); ``` and also you could use `Double.valueOf()` creates a Double object so .doubleValue() should not be necessary. also `Double.parseDouble(NumberFormat.getCurrencyInstance().parse("$12.25"));` could work Upvotes: 0 <issue_comment>username_2: I don't know either the below solution is perfect or not but it is working according to my requirement. ``` try { return NumberFormat.getCurrencyInstance().parse(currency).doubleValue(); } catch (ParseException e) { e.printStackTrace(); // Currency string is not parsable // might be different locale String cleanString = currency.replaceAll("\\D", ""); try { double money = Double.parseDouble(cleanString); return money / 100; } catch (Exception ex) { ex.printStackTrace(); } } return 0; ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Here's a little algorithm that may help you : ``` public static void main(String[] args) { String cash = "R$1,000.75"; //The loop below will work for ANY currency as long as it does not start with a digit boolean continueLoop = true; char[] cashArray = cash.toCharArray(); int cpt = 0; while(continueLoop){ try { double d = Double.parseDouble(cashArray[cpt]+""); continueLoop = false; }catch(NumberFormatException nfe){ cpt += 1; } } System.out.println(cpt); //From here you can do whatever you want.... String extracted = cash.substring(cpt); NumberFormat format = NumberFormat.getInstance(Locale.US); //YOUR REQUIREMENTS !!!! lol try { Number youValue = format.parse(extracted); System.out.println(youValue.doubleValue()); } catch (ParseException ex) { //handle your parse error here } } ``` You should get as result here in the output: 2 1000.75 Upvotes: 0
2018/03/21
587
2,553
<issue_start>username_0: I have googled a lot but cannot find a solution on this problem. I have a relative path like 'external/user/login/example.php' and I need in that case to bypass the angular routing to get my\_env + relative\_url. Is that possible with angular? Thanks in advance.<issue_comment>username_1: What about ``` new Double(NumberFormat.getCurrencyInstance().parse("$12.25").doubleValue()); ``` and also you could use `Double.valueOf()` creates a Double object so .doubleValue() should not be necessary. also `Double.parseDouble(NumberFormat.getCurrencyInstance().parse("$12.25"));` could work Upvotes: 0 <issue_comment>username_2: I don't know either the below solution is perfect or not but it is working according to my requirement. ``` try { return NumberFormat.getCurrencyInstance().parse(currency).doubleValue(); } catch (ParseException e) { e.printStackTrace(); // Currency string is not parsable // might be different locale String cleanString = currency.replaceAll("\\D", ""); try { double money = Double.parseDouble(cleanString); return money / 100; } catch (Exception ex) { ex.printStackTrace(); } } return 0; ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: Here's a little algorithm that may help you : ``` public static void main(String[] args) { String cash = "R$1,000.75"; //The loop below will work for ANY currency as long as it does not start with a digit boolean continueLoop = true; char[] cashArray = cash.toCharArray(); int cpt = 0; while(continueLoop){ try { double d = Double.parseDouble(cashArray[cpt]+""); continueLoop = false; }catch(NumberFormatException nfe){ cpt += 1; } } System.out.println(cpt); //From here you can do whatever you want.... String extracted = cash.substring(cpt); NumberFormat format = NumberFormat.getInstance(Locale.US); //YOUR REQUIREMENTS !!!! lol try { Number youValue = format.parse(extracted); System.out.println(youValue.doubleValue()); } catch (ParseException ex) { //handle your parse error here } } ``` You should get as result here in the output: 2 1000.75 Upvotes: 0
2018/03/21
873
3,353
<issue_start>username_0: To change the text in [Bootbox](http://bootboxjs.com/) dialog, I use and then use jQuery as follow: `$("#someID").text("The new Text");` The problem I am facing is how to change the dialog color? Inside my dialog I have the following (to set the dialog color): ``` className: "modal-danger nonumpad", ``` I want to change the class name to `modal-success nonumpad` when an action takes place. Here is my code: ``` callDialog = bootbox.dialog({ className: "modal-danger nonumpad", // the class I want to change closeButton: false, animate: true, title: 'Making Call', message: ' Waiting for Reply... ', onEscape: null, buttons: { hangup: { label: " Cancel ", className: "btn-warning btn-lg pull-left", callback: function(){ $("#dynamicMsg").text("This is dynamic msg"); return false; } } } }); callDialog.init(function(){ peer.on('connection', function(conn) { conn.on('data', function(data){ // Will print 'hi!' call = data; console.log(call); if(call == "ACCEPT"){ $("#test").text("This is dynamic msg"); $("#hangup").text("Hangup"); } else { } }); }); }); ``` How can I change the `className` inside the `init()` function? **NOTE:** doesn't work.<issue_comment>username_1: Can you try: ``` $("#someID").removeClass('modal-danger').addClass('modal-success'); ``` The someID will have to be the ID of your dialog. Or, if you have multiple or it's dynamic, reference a class name instead. ``` $(".someClass").removeClass('modal-danger').addClass('modal-success'); ``` Upvotes: 0 <issue_comment>username_2: Since you have a reference to your dialog, something like this should work, using [toggleClass](http://api.jquery.com/toggleclass/): ``` callDialog.find('.modal-danger').toggleClass('modal-danger modal-success'); ``` This will find the child element with the class `modal-danger`, and then remove it while adding the class `modal-success`. Upvotes: 1 <issue_comment>username_3: > > can you please guide what to replace someID with? because the way i am > creating the the dialog is different as it is shown in the question > with no ID > > > Answering your comment question, your should replace it with whatever individual selector you have for the element you want to change. If is just one element you sould think about giving it an ID. Depending on where you are calling that, you can define your selector by the `event.currentTarget`, or if at that moment there is only this element with those classes `"modal-danger nonumpad"`, you can use it as a selector too. Upvotes: 0 <issue_comment>username_4: Try this: `$(callDialog).removeClass('modal-danger').addClass('modal-success');` The `$(callDialog)` selects the variable that the bootbox dialog object was assigned to and turns it to a [JQuery Object](http://api.jquery.com/jquery/). The `.removeClass('modal-danger')` is a [JQuery method](https://api.jquery.com/removeclass/) to remove the class passed as a parameter from the selected object. The `.addClass('modal-success')` is also a [JQuery method](https://api.jquery.com/addclass/) used to add the class passed as a parameter to the selected object. Upvotes: -1
2018/03/21
833
2,624
<issue_start>username_0: this is something I cannot understand: ``` #include #include typedef struct point{ char name[10]; int y; } point\_t; std::string print(const char\* str, size\_t size) { return std::string(str, size); } std::ostream& operator << (std::ostream &o,const point\_t &a){ o << print(a.name, sizeof(a.name)) << ", " << a.y; } int main(){ point\_t p = { {'0','1','2','3','4','5','6','7','8','9'}, 4 }; std::cout << "we have" << p << std::endl; return 0; } ``` There is a segfault, which valgrinds shows on at ``` std::basic_ostream >& std::endl >(std::basic\_ostream >&) (in /usr/lib64/libstdc++.so.6.0.13) ``` which I cannot understand, because I can pring the string character by character and the segfault does not happen (for example << a.name[0] << a.name[1] << ... << a.name[9]) Any help appreciated.<issue_comment>username_1: When I compile your code, I get this warning: ``` ..\main.cpp: In function 'std::ostream& operator<<(std::ostream&, const point_t&)': ..\main.cpp:15:1: warning: no return statement in function returning non-void [-Wreturn-type] ``` This means you forgot to return the `ostream` in your stream insertion operator, causing undefined behavior. Fix it by adding the `return`: ``` std::ostream& operator << (std::ostream &o,const point_t &a){ o << print(a.name, sizeof(a.name)) << ", " << a.y; return o; } ``` I recommend always compiling with a high warning level and then striving for warning-free compiles. When the compiler is trying to help you, don't ignore it. As @username_2 noted, you should also `#include` . Your standard library implementation might be getting that included from another header, but you shouldn't depend on that. Also, nothing you show here requires the `#include` . Upvotes: 3 [selected_answer]<issue_comment>username_2: You code does not compile with my compiler (VS2017). I fixed it to this: ``` #include #include typedef struct point { char name[10]; int y; } point\_t; std::string print(const char\* str, size\_t size) { return std::string(str, size); } std::ostream& operator << (std::ostream &o, const point\_t &a) { o << print(a.name, sizeof(a.name)) << ", " << a.y; return o; } int main() { point\_t p = { { '0','1','2','3','4','5','6','7','8','9' }, 4 }; std::cout << "we have" << p << std::endl; return 0; } ``` Note the `return` statement for your operator and the include for `string`. I don't have any problems with the fixed version. If your compiler did compile your version, I'd suggest you turn up the warning level or get a compiler that notifies you of errors. Upvotes: 2
2018/03/21
618
2,097
<issue_start>username_0: I want to call a function with a `double` parameter and an `int` precision. This function would have to round that number with the precision number as decimals. Example: `function(1.23432, 4)` would have to round that number up with 4 decimals (`1.2343`). Could anyone help me out with this?<issue_comment>username_1: When I compile your code, I get this warning: ``` ..\main.cpp: In function 'std::ostream& operator<<(std::ostream&, const point_t&)': ..\main.cpp:15:1: warning: no return statement in function returning non-void [-Wreturn-type] ``` This means you forgot to return the `ostream` in your stream insertion operator, causing undefined behavior. Fix it by adding the `return`: ``` std::ostream& operator << (std::ostream &o,const point_t &a){ o << print(a.name, sizeof(a.name)) << ", " << a.y; return o; } ``` I recommend always compiling with a high warning level and then striving for warning-free compiles. When the compiler is trying to help you, don't ignore it. As @username_2 noted, you should also `#include` . Your standard library implementation might be getting that included from another header, but you shouldn't depend on that. Also, nothing you show here requires the `#include` . Upvotes: 3 [selected_answer]<issue_comment>username_2: You code does not compile with my compiler (VS2017). I fixed it to this: ``` #include #include typedef struct point { char name[10]; int y; } point\_t; std::string print(const char\* str, size\_t size) { return std::string(str, size); } std::ostream& operator << (std::ostream &o, const point\_t &a) { o << print(a.name, sizeof(a.name)) << ", " << a.y; return o; } int main() { point\_t p = { { '0','1','2','3','4','5','6','7','8','9' }, 4 }; std::cout << "we have" << p << std::endl; return 0; } ``` Note the `return` statement for your operator and the include for `string`. I don't have any problems with the fixed version. If your compiler did compile your version, I'd suggest you turn up the warning level or get a compiler that notifies you of errors. Upvotes: 2
2018/03/21
647
2,175
<issue_start>username_0: I found a exactly question like this over here but that is for C#. I need one for javascript. I dont want to have to enter the last value "NA" since its never going to be called if code is programmed properly. Is there such a work around so that I dont have to enter anything, by anything I mean not even **" "**. ``` (col_1 === 0)? 0 :(col_1 >= 1)? col_1-1:"NA"; ```<issue_comment>username_1: When I compile your code, I get this warning: ``` ..\main.cpp: In function 'std::ostream& operator<<(std::ostream&, const point_t&)': ..\main.cpp:15:1: warning: no return statement in function returning non-void [-Wreturn-type] ``` This means you forgot to return the `ostream` in your stream insertion operator, causing undefined behavior. Fix it by adding the `return`: ``` std::ostream& operator << (std::ostream &o,const point_t &a){ o << print(a.name, sizeof(a.name)) << ", " << a.y; return o; } ``` I recommend always compiling with a high warning level and then striving for warning-free compiles. When the compiler is trying to help you, don't ignore it. As @username_2 noted, you should also `#include` . Your standard library implementation might be getting that included from another header, but you shouldn't depend on that. Also, nothing you show here requires the `#include` . Upvotes: 3 [selected_answer]<issue_comment>username_2: You code does not compile with my compiler (VS2017). I fixed it to this: ``` #include #include typedef struct point { char name[10]; int y; } point\_t; std::string print(const char\* str, size\_t size) { return std::string(str, size); } std::ostream& operator << (std::ostream &o, const point\_t &a) { o << print(a.name, sizeof(a.name)) << ", " << a.y; return o; } int main() { point\_t p = { { '0','1','2','3','4','5','6','7','8','9' }, 4 }; std::cout << "we have" << p << std::endl; return 0; } ``` Note the `return` statement for your operator and the include for `string`. I don't have any problems with the fixed version. If your compiler did compile your version, I'd suggest you turn up the warning level or get a compiler that notifies you of errors. Upvotes: 2
2018/03/21
857
2,580
<issue_start>username_0: I am developing a Python program in order to find the etymology of words in a text. I have found out there are basically two options: parsing an online dictionary that provides etymology or using an API. I found this reply here but I don't seem to understand how to link the Oxford API with my Python program. Can anyone explain me how to look up a word in an english dictionary? Thank you in advance. Link to the question [here](https://stackoverflow.com/questions/21395011/python-module-with-access-to-english-dictionaries-including-definitions-of-words) > > Note that while WordNet does not have all English words, what about the Oxford English Dictionary? (<http://developer.oxforddictionaries.com/>). Depending on the scope of your project, it could be a killer API. > Have you tried looking at Grady Ward's Moby? [link] (<http://icon.shef.ac.uk/Moby/>). > You could add it as a lexicon in NLTK (see notes on "Loading your own corpus" in Section 2.1). > > > ```html from nltk.corpus import PlaintextCorpusReader corpus_root = '/usr/share/dict' wordlists = PlaintextCorpusReader(corpus_root, '.*') ``` ```html from nltk.corpus import BracketParseCorpusReader corpus_root = r"C:\corpora\penntreebank\parsed\mrg\wsj" file_pattern = r".*/wsj_.*\.mrg" ptb = BracketParseCorpusReader(corpus_root, file_pattern) ```<issue_comment>username_1: Using [`PyDictionary`](https://pypi.python.org/pypi/PyDictionary/1.3.4) May be a Good Option Upvotes: 1 <issue_comment>username_2: You could use the opensource [`ety`](https://github.com/jmsv/ety-python) package. *Disclosure: I'm a contributor to the project* It's based on the data used in the research "[Etymological Wordnet: Tracing the History of Words](http://www1.icsi.berkeley.edu/~demelo/etymwn/)", which has already been pre-scraped from [Wiktionary](https://www.wiktionary.org/). Some examples: ``` >>> import ety >>> ety.origins("potato") [Word(batata, language=Taino)] >>> ety.origins('drink', recursive=True) [Word(drync, language=Old English (ca. 450-1100)), Word(drinken, language=Middle English (1100-1500)), Word(drincan, language=Old English (ca. 450-1100))] >>> print(ety.tree('aerodynamically')) aerodynamically (English) ├── -ally (English) └── aerodynamic (English) ├── aero- (English) │ └── ἀήρ (Ancient Greek (to 1453)) └── dynamic (English) └── dynamique (French) └── δυναμικός (Ancient Greek (to 1453)) └── δύναμις (Ancient Greek (to 1453)) └── δύναμαι (Ancient Greek (to 1453)) ``` Upvotes: 2
2018/03/21
1,295
4,985
<issue_start>username_0: I am new in Scala world and now I am reading the book called "Scala in Action" (by <NAME>), namely the part called "Mutable object need to be invariant" on page 97 and I don't understand the following part which is taken directly from the mentioned book. --- Assume ListBuffer is covariant and the following code snippet works without any compilation problem: ``` scala> val mxs: ListBuffer[String] = ListBuffer("pants") mxs: scala.collection.mutable.ListBuffer[String] = ListBuffer(pants) scala> val everything: ListBuffer[Any] = mxs scala> everything += 1 res4: everything.type = ListBuffer(1, pants) ``` Can you spot the problem? Because everything is of the type Any, you can store an integer value into a collection of strings. This is a disaster waiting to happen. To avoid these kinds of problems, it’s always a good idea to make mutable objects invariant. --- I would have the following questions.. 1) What type of `everything` is in reality? `String` or `Any`? The declaration is "`val everything: ListBuffer[Any]`" and hence I would expect `Any` and because everything should be type of `Any` then I don't see any problems to have `Integer` and `String` in one `ListBuffer[Any]`. How can I store integer value into collection of strings how they write??? Why disaster??? Why should I use List (which is immutable) instead of ListBuffer (which is mutable)? I see no difference. I found a lot of answers that mutably collections should have type invariant and that immutable collections should have covariant type but why? 2) What does the last part "`res4: everything.type = ListBuffer(1, pants)`" mean? What does "everything.type" mean? I guess that `everything` does not have any method/function or variable called `type`.. Why is there no ListBuffer[Any] or ListBuffer[String]? Thanks a lot, Andrew<issue_comment>username_1: **1** This doesn't look like a single question, so I have to subdivide it further: 1. "In reality" `everything` is `ListBuffer[_]`, with erased parameter type. Depending on the JVM, it holds either 32 or 64 bit references to some objects. The types `ListBuffer[String]` and `ListBuffer[Any]` is what the compiler knows about it at compile time. If it "knows" two contradictory things, then it's obviously very bad. 2. *"I don't see any problems to have Integer and String in one ListBuffer[Any]"*. There is no problem to have `Int` and `String` in `ListBuffer[Any]`, because `ListBuffer` is invariant. However, in your hypothetical example, `ListBuffer` is covariant, so you are storing an `Int` in a `ListBuffer[String]`. If someone later gets an `Int` from a `ListBuffer[String]`, and tries to interpret it as `String`, then it's obviously very bad. 3. *"How can I store integer value into collection of strings how they write?"* Why would you want to do something that is obviously very bad, as explained above? 4. *"Why disaster???"* It wouldn't be a major disaster. Java has been living with covariant arrays forever. It's does not lead to cataclysms, it's just bad and annoying. 5. *"Why should I use List (which is immutable) instead of ListBuffer (which is mutable)?"* There is no absolute imperative that tells you to always use `List` and to never use `ListBuffer`. Use both when it is appropriate. In 99.999% of cases, `List` is of course more appropriate, because you use `List`s to represent data way more often than you design complicated algorithms that require local mutable state of a `ListBuffer`. 6. *"I found a lot of answers that mutably collections should have type invariant and that immutable collections should have covariant type but why?"*. This is wrong, you are over-simplifying. For example, intensional immutable sets should be neither covariant, nor invariant, but *contravariant*. You should use covariance, contravariance, and invariance when it's appropriate. [This little silly illustration has proven unreasonably effective for explaining the difference](https://stackoverflow.com/a/48858344/2707792), maybe you too find it useful. **2** This is a [singleton type](https://www.scala-lang.org/files/archive/spec/2.12/03-types.html#singleton-types), just like in the following example: ``` scala> val x = "hello" x: String = hello scala> val y: x.type = x y: x.type = hello ``` Here is a [longer discussion about the motivation](http://docs.scala-lang.org/sips/pending/42.type.html) for this. Upvotes: 3 <issue_comment>username_2: I agree with most of what @Andrey is saying I would just add that covariance and contravariance belong exclusively to immutable structures, the exercisce that the books proposes is just a example so people can understand but it is not possible to implement a mutable structure that is covariant, you won't be able to make it compile. As an exercise you could try to implement a `MutableList[+A]`, you'll find out that there is not way to do this without tricking the compiler putting `asInstanceOf` everywhere Upvotes: 0
2018/03/21
870
2,722
<issue_start>username_0: I have two lists. ``` List list1 = new ArrayList<>(Arrays.asList(1, 2, 2)); List list2 = new ArrayList<>(Arrays.asList(2, 3, 4)); ``` I want to remove the elements contained in `list2` from `list1`, precisely as many times as they are contained in `list2`. In the example above: when we remove elements in list 1 which exist in list 2, we should get as result `[1, 2]` (only one occurrence of `2` should be removed from `list1` because `list2` contains only one instance of `2`). I tried with `list1.removeAll(list2);` but I got as result list containing only `[1]`. What is the best way to achieve this? Iterate through both lists simultaneous seems a bit ugly for me.<issue_comment>username_1: How about: ``` list2.forEach(i -> { list1.remove(i); //removes only first occurrence - if found }); ``` `list1` now contains ``` [1, 2] ``` Upvotes: 2 <issue_comment>username_2: If I understand correctly, you only want to remove a single `2` element from `list1` rather than all of them. You can iterate over `list2` and attempt to remove each element from `list1`. Keep in mind that there are more efficient methods than this if `list2` cannot contain duplicates. ``` var list1 = new ArrayList<>(List.of(1, 2, 2)); var list2 = List.of(2, 3, 4); list2.forEach(list1::remove); ``` `list1` now contains the following: ``` [1, 2] ``` See [username_1's answer](https://stackoverflow.com/a/49411110/7294647) for the same solution, but using a lambda rather than a method reference. Upvotes: 4 [selected_answer]<issue_comment>username_3: Given ``` List a = new ArrayList<>(Arrays.asList(1, 2, 2)); List b = Arrays.asList(2, 3, 4); ``` Use one of the following variants to get the desired result: **1. Plain java** ``` b.forEach((i)->a.remove(i)); ``` `a` now contains ``` [1, 2] ``` Give credit at original post: [add **+1**](https://stackoverflow.com/a/49411110/1485527): **2. Apache Commons** In [apache commons](https://mvnrepository.com/artifact/org.apache.commons/commons-collections4/4.1) there is a `subtract` method ``` Collection result = CollectionUtils.subtract(a, b); ``` `result` now contains ``` [1, 2] ``` Here is [how they implemented it](https://github.com/apache/commons-collections/blob/master/src/main/java/org/apache/commons/collections4/CollectionUtils.java#L302) **3. Guava** Since guava doesn't offer a `subtract` method you may find [this advice from the google implementors](https://github.com/google/guava/wiki/ApacheCommonCollectionsEquivalents) helpful > > "create an ArrayList containing a and then call remove on it for each element in b." > > > Which basically renders to what was already mentioned under **1.** Upvotes: 0
2018/03/21
733
2,595
<issue_start>username_0: As stated by [this blog](http://benjiweber.co.uk/blog/2018/03/03/representing-the-impractical-and-impossible-with-jdk-10-var/), we are now able to write the following using local type inference (something, to my knowledge, that was previously impossible without introducing more code): ``` public static void main(String... args) { var duck = (Quacks & Waddles) Mixin::create; duck.quack(); duck.waddle(); } interface Quacks extends Mixin { default void quack() { System.out.println("Quack"); } } interface Waddles extends Mixin { default void waddle() { System.out.println("Waddle"); } } interface Mixin { void __noop__(); static void create() {} } ``` This question may be either too broad or primarily opinion-based, but do there exist any useful applications when taking advantage of intersection types like this?<issue_comment>username_1: You can sort of do that in java-8 too: ``` static class ICanDoBoth implements Quacks, Waddles { // implement void __noop__(); here... } public static void both(Object b) { // my point here is that you can't declare such a type 'x' Optional.of((Quacks & Waddles) b) .ifPresent(x -> { x.quack(); x.waddle(); }); } ``` And call it via: `both(new ICanDoBoth());` Thing is you can't declare a variable of an intersection type (well, unless `var` or a variable that is inferred by the compiler with `Optional.of()`). Practically there are some hints [here](https://stackoverflow.com/questions/43987285/implied-anonymous-types-inside-lambdas), but I've never used a variable of a intersection type in something very useful... Upvotes: 2 <issue_comment>username_2: Dealing with partially unknown types is possible since Java 5, so it’s quite easy to backport your example to Java 8: ``` public static void main(String... args) { use((Quacks & Waddles)Mixin::create); } private static void use(Duck duck) { duck.quack(); duck.waddle(); } interface Quacks extends Mixin { default void quack() { System.out.println("Quack"); } } interface Waddles extends Mixin { default void waddle() { System.out.println("Waddle"); } } interface Mixin { void \_\_noop\_\_(); static void create() {} } ``` So the possibility to do the same using `var` in Java 10 allows, well, to do the same as before, but with slightly less source code. And being able to do the same things as before but with less boilerplate code is exactly what `var` is about, whether you use intersection types or not. Upvotes: 3
2018/03/21
555
1,627
<issue_start>username_0: I have a dataframe like this: ``` col1 col2 0 maria apple 1 eugene apple 2 eugene banana 3 maria apple 4 maria pear 5 eugene banana 6 maria apple ``` I want to group by person to see what is the most common fruit for that person, something like this: ``` col1 col2 col3 0 maria apple 3 1 eugene banana 2 ``` **edit** What I accomplished so far was: ``` col1 col2 maria apple 2 pear 1 eugene banana 2 apple 1 ``` with ``` df.groupby('col1')['col2'].value_counts() ``` but I couldn't figure it out how to get only the max values, since its a series, not a dataframe<issue_comment>username_1: IIUC: ``` df.groupby('col1')['col2'].apply(lambda x: x.value_counts().head(1)) ``` Output: ``` col1 eugene banana 2 maria apple 3 Name: col2, dtype: int64 ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: `mode` from `scipy` ``` from scipy import stats df.groupby('col1').col2.apply(stats.mode) Out[530]: col1 eugene ([banana], [2]) maria ([apple], [3]) Name: col2, dtype: object ``` Upvotes: 0 <issue_comment>username_3: First use `groupby()` on your `col1`, obtain frequencies using `value_counts()`, then sort values in a descending order with the `sort_values()` function ``` a = pd.DataFrame({"col1": ["maria","eugene","eugene","maria","maria","eugene","maria"], "col2": ["apple", "apple","banana","apple","pear","banana","apple"]}) a.groupby(["col1"])["col2"].value_counts().sort_values(ascending=False) ``` Upvotes: 0
2018/03/21
517
1,679
<issue_start>username_0: I'm new to JS and I want to know how to print a var inside a string , i found that the way should be : ``` var user = { name: "Mike", sayHi:() => { console.log('Hi, I\'m ${name}'); } }; user.sayHi() ``` but I get : `Hi, I'm ${name}`<issue_comment>username_1: When you want to use variables in string, you should wrap them in back ticks ` instead of double or single quotes. So follow below example: ``` console.log(`Hi, I'm ${name}`); ``` Upvotes: 3 <issue_comment>username_2: [Template literals](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals) use backticks `` instead of regular quotes ''. Upvotes: 4 [selected_answer]<issue_comment>username_3: You have to use backtick (``) instead of quotes ('') to evaluate the expression. ```js var user = { name: "Mike", sayHi:() => { console.log(`Hi, I\'m ${user.name}`); } }; user.sayHi() ``` For more on [Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) Upvotes: 2 <issue_comment>username_4: It should be ``` console.log(`Hi, I'm ${name}`); ``` To do string templating you need to use ` backquote. Single quote ' means just standard string EDIT: As pointed by @peteb in the comments escaping single quote is not required in template string Upvotes: 1 <issue_comment>username_5: It should be ``` console.log('Hi, I\'m ' + name); ``` Upvotes: 0 <issue_comment>username_6: It should be a back tick not single quote. Please find below, ```js var user = { name: "Mike", sayHi:() => { console.log(`Hi, I\'m ${name}`); } }; user.sayHi() ``` Upvotes: 1
2018/03/21
189
657
<issue_start>username_0: The query checks the value of a parameter **foo** which is passed by a dropdown inside a program. If that paramater contains a certain value, an attribute should only contain null values. Can I manage that without pl/SQL? ``` select * from table t where case when $foo$ = 'yes' then t.something is null end ```<issue_comment>username_1: Do you mean this logic? ``` select something from table t where ($foo$ = 'yes' and t.something is null) or ($foo != 'yes') ``` Upvotes: 2 [selected_answer]<issue_comment>username_2: Just use `nvl` function : ``` select * from mytable t where nvl($foo$,'yes') = 'yes'; ``` Upvotes: 0
2018/03/21
542
1,904
<issue_start>username_0: I'm trying to figure out following code and am not sure what the std::async part is doing: ``` std::vector RunParallel( std::vector> args) { std::vector> results(args.size()); for( int iter\_job = 0; iter\_job < args.size(); ++iter\_job ) { int arg1 = args[iter\_job][0]; int arg2 = args[iter\_job][1]; results[iter\_job]= std::async(std::launch::async, [&] { return (foo(arg1,arg2)); }); } std::vector returnValues; for(int iter\_job =0; iter\_job ``` I don't understand what the return is doing in the std::async call. Somehow this code is leading to strange results and I wonder if it has to do with the return call in the middle of the first for loop.<issue_comment>username_1: `[&]{ return (foo(arg1,arg2)); }` is a *lambda expression* that produces a *closure* taking no arguments and returning `foo(arg1, arg2)` upon invocation. `arg1` and `arg2` are captured by reference in the closure. This means that as soon as an iteration of the `for` loop ends, the closure will hold **dangling references**. This is likely the cause of your problem. Capture `arg1` and `arg2` by value instead: ``` [arg1, arg2]{ return foo(arg1, arg2); } ``` Using the default `&` or `=` captures is usually a bad idea as they can introduce subtle bugs. Prefer listing your captures explicitly unless you have a good reason to not do so. Upvotes: 3 [selected_answer]<issue_comment>username_2: There's no `return` in the for loop - the `return` is in the function that you're passing to `async`. The problem is that the function is capturing `arg1` and `arg2` by reference, and when it's called some time in the future those objects no longer exist, so attempting to access them is undefined. Replace the capture list `[&]` with `[arg1, arg2]` to capture them by value instead. (And throw in an empty parameter list for good measure: `[arg1, arg2]() { ... }`.) Upvotes: 1
2018/03/21
757
2,864
<issue_start>username_0: I have two `textFormField` widgets. Once the user has completed the first text field I would like to focus on the next `textField`. Is there a way to do this in Flutter? Currently, the done button just closes the keyboard. I was guessing the `focusNode` class might be the answer to this but not really sure how that works does anyone have any good examples of focusNode class? Thanks in advance.<issue_comment>username_1: Yes, [FocusNode](https://docs.flutter.io/flutter/widgets/FocusNode-class.html) and the `onFieldSubmitted` from a [TextFormField](https://docs.flutter.io/flutter/material/TextFormField-class.html) are probably the way to go. > > FocusScope.of(context).requestFocus(focusNode); > > > Here is an example that may help: ``` FocusNode textSecondFocusNode = new FocusNode(); TextFormField textFirst = new TextFormField( onFieldSubmitted: (String value) { FocusScope.of(context).requestFocus(textSecondFocusNode); }, ); TextFormField textSecond = new TextFormField( focusNode: textSecondFocusNode, ); // render textFirst and textSecond where you want ``` You may also want to trigger `FocusScope.of()` from a button rather than onFieldSubmitted, but hopefully the above example gives you enough context to construct an appropriate solution for your use case. Upvotes: 7 [selected_answer]<issue_comment>username_2: There's a similar method like in Android. Add ``` textInputAction ``` parameter to the TextFormField Widget, then add the property as; ``` TextInputAction.next ``` Upvotes: 3 <issue_comment>username_3: **Screenshot:** [![enter image description here](https://i.stack.imgur.com/5KpgR.gif)](https://i.stack.imgur.com/5KpgR.gif) --- **No need to use `FocusNode`** ``` @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(), body: Column( children: [ TextField( decoration: InputDecoration(hintText: '<NAME>'), textInputAction: TextInputAction.next, onEditingComplete: () => FocusScope.of(context).nextFocus(), ), TextField( decoration: InputDecoration(hintText: '<NAME>'), textInputAction: TextInputAction.done, onSubmitted: (_) => FocusScope.of(context).unfocus(), ), ], ), ); } ``` Upvotes: 5 <issue_comment>username_4: This is how I did it: ``` var _focusNodes = List.generate(6, (index) => FocusNode())); ``` And in the TextFormField: ``` TextFormField( focusNode: _focusNodes[i], maxLines: 1, textInputAction: TextInputAction.next, onChanged: (text) { if (i < _controllers.length) { if (text.isEmpty) _focusNodes[i - 1].requestFocus(); else _focusNodes[i + 1].requestFocus(); } }, ), ``` Upvotes: 3
2018/03/21
882
2,561
<issue_start>username_0: Let say I have a list with `len(list) == 5` Can I be sure `list[4]` exists? Or maybe an item could get deleted and then the list would have indices 0,1,2,3,5 which would have length 5 but without index 4?<issue_comment>username_1: Yes, if `len(lst) == x` then all indices up to `x - 1` exist. Look at what happen if you delete an item. ``` lst = [1, 2, 3] len(lst) # 3 del lst[1] len(lst) # 2 ``` After deletion, the length was decremented. Upvotes: 0 <issue_comment>username_2: When you delete an item at a specific index, the rest of the data will shift back to take that place. ``` >>> l = ['a', 'b', 'c', 'd', 'e', 'f'] >>> len(l) 6 >>> l[4] 'e' >>> del l[4] >>> len(l) 5 >>> l[4] 'f' ``` Upvotes: 0 <issue_comment>username_3: When an element from a list is deleted, the index's shift down one. An index is just an element located in a list. if you have a list of 1,2,3,4,5 and you delete `list[3]` then you now have 1,2,3,5 and now `list[3] == 5` Upvotes: 0 <issue_comment>username_4: > > *Can I be sure list[4] exists?* > > > Yes you can. If `len(list)` returns 5, then you are 100% sure that there are 5 elements in your list. > > Or maybe an item could get deleted and then the list would have indices 0,1,2,3,5 which would have length 5 but without index 4? > > > Again, if `len(list)` returns 5, then you have 5 elements in your list. And because lists are zero-based in python, then list[4] will be the last element of your list Here is a quote from the [python documentation](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations): > > Operation: s[i] > > > Result: ith item of s > > > Notes: origin 0 > > > You can also try it in the REPL (python language shell), as Jim showed in his [answer](https://stackoverflow.com/a/49411090/5609328). If you create a list of 5 elements, `len` will return you `5`. If you delete any element in the list, such as the 4th one, then `len` will now return you `4`, and you will access the last element (which was the 5th element before the deletion) by using `list[4]`. Upvotes: 2 [selected_answer]<issue_comment>username_5: A list in Python is a list implemented with an array, it is not just an array. If you take some lessons on data structures you can learn more about this, but the consequence of this is that a deletion of an entry of a list will be resolved by changing all the indices of the items coming after the removed item. Like this ``` >>> x = [0, 1, 2, 3] >>> del x[2] >>> x [0, 2, 3] >>> x[2] 3 ``` Upvotes: 0
2018/03/21
1,282
4,829
<issue_start>username_0: I modified a combobox style and the style is listed below. It works fine, however, the style applies to all comboboxes in my project. In other words, when I pull a combobox from the toolbox, it is automatically styled. What I'd like to do is only style certain comboboxes with the style - not all. Of course I would have to apply the style to each control using a key name. My question is, how can the style be modified so I can refer to it by a key name "myComboBox". Thanks for your help. STYLE IN MY RESOURCE DICTIONARY: ``` <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/> <Setter Property="ScrollViewer.CanContentScroll" Value="true"/> <Setter Property="MinWidth" Value="0"/> <Setter Property="MinHeight" Value="20"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ComboBox}"> <Grid> <ToggleButton Name="ToggleButton" Template="{StaticResource ComboBoxToggleButton}" Grid.Column="2" Focusable="false" IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"> </ToggleButton> <ContentPresenter Name="ContentSite" IsHitTestVisible="False" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" Margin="1,0,11,0" VerticalAlignment="Stretch" HorizontalAlignment="Left" /> <TextBox x:Name="PART\_EditableTextBox" Style="{x:Null}" Template="{StaticResource ComboBoxTextBox}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="1,0,11,0" Focusable="True" Background="Transparent" Visibility="Hidden" IsReadOnly="{TemplateBinding IsReadOnly}"/> <Popup Name="Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}" AllowsTransparency="True" Focusable="False" PopupAnimation="Slide"> <Grid Name="DropDown" SnapsToDevicePixels="True" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"> <Border x:Name="DropDownBorder" Background="Black" BorderThickness="1" BorderBrush="#888888"/> <ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True"> <StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" /> </ScrollViewer> </Grid> </Popup> </Grid> <ControlTemplate.Triggers> <Trigger Property="HasItems" Value="false"> <Setter TargetName="DropDownBorder" Property="MinHeight" Value="95"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="#888888"/> </Trigger> <Trigger Property="IsGrouping" Value="true"> <Setter Property="ScrollViewer.CanContentScroll" Value="false"/> </Trigger> <Trigger SourceName="Popup" Property="Popup.AllowsTransparency" Value="true"> <Setter TargetName="DropDownBorder" Property="CornerRadius" Value="0"/> <Setter TargetName="DropDownBorder" Property="Margin" Value="0,0,0,0"/> </Trigger> <Trigger Property="IsEditable" Value="true"> <Setter Property="IsTabStop" Value="false"/> <Setter TargetName="PART\_EditableTextBox" Property="Visibility" Value="Visible"/> <Setter TargetName="ContentSite" Property="Visibility" Value="Hidden"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> <Style.Triggers> </Style.Triggers> <Setter Property="SnapsToDevicePixels" Value="true"/> <Setter Property="OverridesDefaultStyle" Value="true"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ComboBoxItem}"> <Border Name="Border" Padding="0" SnapsToDevicePixels="true"> <ContentPresenter /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsHighlighted" Value="true"> <Setter TargetName="Border" Property="Background" Value="#888888"/> </Trigger> <Trigger Property="IsEnabled" Value="false"> <Setter Property="Foreground" Value="#888888"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> ```<issue_comment>username_1: Give the `Style` a unique `x:Key`: Upvotes: 0 <issue_comment>username_2: Your problem is the key you're using. This: x:Key="{x:Type ComboBox}" Change that to some other string that doesn't involve any curly braces or x:type. Upvotes: 0 <issue_comment>username_3: When you assign a `x:Key` like that it create an [implicit style](https://learn.microsoft.com/en-us/dotnet/framework/wpf/controls/styling-and-templating#relationship-of-the-targettype-property-and-the-xkey-attribute). What you are wanting is an explicit style. What you need to do is change this line Upvotes: 3 [selected_answer]
2018/03/21
577
2,002
<issue_start>username_0: Assume the following code snippet: ``` .... .... some stuff a change more stuff more changes more stuff } } } } final changes ``` I need to add something right before the last , what's stated as `final changes`. How can I tell sed to match that one? `final changes` doesn't exist, the last lines of the script are like four or five `}`, so it would be the scenario, I'd need to match multiple lines. All the other changes were replaced by matching the line, then replacing with the `line + the changes`. But I don't know how to match the multi line to replace with `final changes` . I tried to use the same tactic I use for replacing with multiple lines, but it didn't work, keep reporting `unterminated substitute pattern`. ``` sed 's|\ |lalalalala\ \ |' file.hmtl ``` I've read this question [Sed regexp multiline - replace HTML](https://stackoverflow.com/questions/11043363/sed-regexp-multiline-replace-html) but it doesn't suit my particular case because it matches everything between the search options. I need to match something, then add something before the first search operator.<issue_comment>username_1: `sed`, `grep`, `awk` etc. are NOT for XML/HTML processing. Use a proper XML/HTML parsers. **`xmlstarlet`** is one of them. Sample `file.html`: ``` .... .... var data = [0, 1, 2]; console.log(data); ``` --- The command: ``` xmlstarlet ed -O -P -u '//body/script' -v 'alert("success")' file.htm ``` The output: ``` .... .... alert("success") ``` <http://xmlstar.sourceforge.net/doc/UG/xmlstarlet-ug.html> Upvotes: 1 <issue_comment>username_2: Finally got this following xara's answer in <https://unix.stackexchange.com/questions/26284/how-can-i-use-sed-to-replace-a-multi-line-string> In summary, instead of trying to do magic with sed, replace the newlines with a character which sed understands (like `\r`), do the replace and then replace the character with newline again. Upvotes: 1 [selected_answer]
2018/03/21
1,598
4,949
<issue_start>username_0: I have tried to implement solution to dynamical expansion of array as user is entering new data in main as shown: ``` ComplexNumber** nizKompl = new ComplexNumber*[1]; bool unos = true; while(unos){ cout << "Unesite novi kompleksni broj(realni imaginarni): "; if(cin >> re >> im){ nizKompl[brojUnesenih] = new ComplexNumber(re,im); ++brojUnesenih; ComplexNumber** nizTemp = new ComplexNumber*[brojUnesenih+1]; copy(nizKompl, nizKompl+brojUnesenih, nizTemp); for(int i=0; i ``` ComplexNumber is custom type. ComplexNumber works fine but I am having problem with double free or corruption error as I am entering new data and creating new ComplexNumbers in program. Is there some better way to achieve this? **I need to use my own dynamical array instead of std::vector** because It is for educational purpose. As I understand double free error occurs when you try to free memory which is already free'd. But It seems that I just can't resolve the issue, as I can see no double free should happen. Is something happening in memory of which I have no knowledge? Is it problem with std::copy as I am copying array of pointers of pointers? I would really appreciate any help or suggestion. Thank you!<issue_comment>username_1: Use `std::vector` and use push\_back to allocate memory dynamically. Your code will look something like this: ``` std::vector nizKompl; while(true) { cout << "Unesite novi kompleksni broj(realni imaginarni): "; if(cin >> re >> im){ nizKompl.push\_back({re,im}); } else { cout << endl << endl; break; } } ``` Upvotes: 2 <issue_comment>username_2: If you really need not to use `std::vector` (for educational reasons), then your problem is here: ``` for(int i=0; i ``` you just copied those *pointers* to your new, slightly bigger array. If you delete the objects they point to, your new array is full of unusable dangling pointers. The proximate fixes are: 1. just don't delete these objects. Consider ownership transferred to the new array and keep them alive. Delete the three lines quoted above. 2. **OR** if you really want to delete the originals, you need to copy them first - this means a deep copy of the object rather than a shallow copy of the pointer, so your new array should be populated like ``` // shallow copy: // copy(nizKompl, nizKompl+brojUnesenih, nizTemp); // deep copy: transform(nizKompl, nizKompl+brojUnesenih, nizTemp, clone); ``` with the function ``` ComplexNumber* clone(ComplexNumber *original) { return new ComplexNumber(*original); } ``` NB. I can't think of any good reason to do this, it's just wasteful. Upvotes: 4 [selected_answer]<issue_comment>username_3: As already mentioned, using `std::vector` would be the right approach. But wrt your exact question: ``` for(int i=0; i ``` This is what causes the double delete, since you copy the same pointers to your new array and also delete them. When entering the first number, you'll create an array of size one and create an object. On the second number, you'll allocate a new array of size two, copy the first element over to the new array, but also delete it. And once you add the third element, you'll create a new array of size three, copy the first two pointers and again try to delete them, but the first pointer was already deleted. Upvotes: 2 <issue_comment>username_4: It is unclear why you are not using the standard class `std::vector` and using pointers instead of objects themselves. Nevertheless it seems you mean something like the following ``` #include #include #include struct ComplexNumber { ComplexNumber() : ComplexNumber( 0, 0 ) {} ComplexNumber( int re, int im ) : re( re ), im( im ) {} int re; int im; }; int main() { ComplexNumber \*\*nizKompl = nullptr; size\_t brojUnesenih = 0; bool unos; do { std::cout << "Unesite novi kompleksni broj(realni imaginarni): "; int re, im; if( ( unos = !!( std::cin >> re >> im ) ) ) { ComplexNumber \*\*nizTemp = new ComplexNumber \* [brojUnesenih + 1]; std::copy( nizKompl, nizKompl + brojUnesenih, nizTemp ); nizTemp[brojUnesenih] = new ComplexNumber( re, im ); ++brojUnesenih; delete [] nizKompl; nizKompl = nizTemp; } } while ( unos ); for ( size\_t i = 0; i < brojUnesenih; i++ ) { std::cout << "{ " << nizKompl[i]->re << ", " << nizKompl[i]->im << " } "; } std::cout << std::endl; if ( nizKompl ) { std::for\_each( nizKompl, nizKompl + brojUnesenih, std::default\_delete() ); } delete [] nizKompl; return 0; } ``` The program output might look like ``` Unesite novi kompleksni broj(realni imaginarni): 1 1 Unesite novi kompleksni broj(realni imaginarni): 2 2 Unesite novi kompleksni broj(realni imaginarni): 3 3 Unesite novi kompleksni broj(realni imaginarni): 4 4 Unesite novi kompleksni broj(realni imaginarni): 5 5 Unesite novi kompleksni broj(realni imaginarni): a { 1, 1 } { 2, 2 } { 3, 3 } { 4, 4 } { 5, 5 } ``` Upvotes: 1
2018/03/21
1,454
4,298
<issue_start>username_0: i have 2 codes that do the same thing 1 runs in 0.3 sec and 1 in 8 sec i have a table with 10000 recorders, and i update all the record also id column is indexed why there is such a time difference if they both do the same this ? the first code( 0.3 sec): ``` UPDATE `trades` SET `profit_loss`= rand() WHERE id < 100000 ``` the seconod code(8 sec): ``` SET @a = 0 ; simple_loop: LOOP SET @a=@a+1; UPDATE trades SET profit_loss = rand() WHERE id = @a ; IF @a=10000 THEN LEAVE simple_loop; END IF; ``` END LOOP simple\_loop;<issue_comment>username_1: Use `std::vector` and use push\_back to allocate memory dynamically. Your code will look something like this: ``` std::vector nizKompl; while(true) { cout << "Unesite novi kompleksni broj(realni imaginarni): "; if(cin >> re >> im){ nizKompl.push\_back({re,im}); } else { cout << endl << endl; break; } } ``` Upvotes: 2 <issue_comment>username_2: If you really need not to use `std::vector` (for educational reasons), then your problem is here: ``` for(int i=0; i ``` you just copied those *pointers* to your new, slightly bigger array. If you delete the objects they point to, your new array is full of unusable dangling pointers. The proximate fixes are: 1. just don't delete these objects. Consider ownership transferred to the new array and keep them alive. Delete the three lines quoted above. 2. **OR** if you really want to delete the originals, you need to copy them first - this means a deep copy of the object rather than a shallow copy of the pointer, so your new array should be populated like ``` // shallow copy: // copy(nizKompl, nizKompl+brojUnesenih, nizTemp); // deep copy: transform(nizKompl, nizKompl+brojUnesenih, nizTemp, clone); ``` with the function ``` ComplexNumber* clone(ComplexNumber *original) { return new ComplexNumber(*original); } ``` NB. I can't think of any good reason to do this, it's just wasteful. Upvotes: 4 [selected_answer]<issue_comment>username_3: As already mentioned, using `std::vector` would be the right approach. But wrt your exact question: ``` for(int i=0; i ``` This is what causes the double delete, since you copy the same pointers to your new array and also delete them. When entering the first number, you'll create an array of size one and create an object. On the second number, you'll allocate a new array of size two, copy the first element over to the new array, but also delete it. And once you add the third element, you'll create a new array of size three, copy the first two pointers and again try to delete them, but the first pointer was already deleted. Upvotes: 2 <issue_comment>username_4: It is unclear why you are not using the standard class `std::vector` and using pointers instead of objects themselves. Nevertheless it seems you mean something like the following ``` #include #include #include struct ComplexNumber { ComplexNumber() : ComplexNumber( 0, 0 ) {} ComplexNumber( int re, int im ) : re( re ), im( im ) {} int re; int im; }; int main() { ComplexNumber \*\*nizKompl = nullptr; size\_t brojUnesenih = 0; bool unos; do { std::cout << "Unesite novi kompleksni broj(realni imaginarni): "; int re, im; if( ( unos = !!( std::cin >> re >> im ) ) ) { ComplexNumber \*\*nizTemp = new ComplexNumber \* [brojUnesenih + 1]; std::copy( nizKompl, nizKompl + brojUnesenih, nizTemp ); nizTemp[brojUnesenih] = new ComplexNumber( re, im ); ++brojUnesenih; delete [] nizKompl; nizKompl = nizTemp; } } while ( unos ); for ( size\_t i = 0; i < brojUnesenih; i++ ) { std::cout << "{ " << nizKompl[i]->re << ", " << nizKompl[i]->im << " } "; } std::cout << std::endl; if ( nizKompl ) { std::for\_each( nizKompl, nizKompl + brojUnesenih, std::default\_delete() ); } delete [] nizKompl; return 0; } ``` The program output might look like ``` Unesite novi kompleksni broj(realni imaginarni): 1 1 Unesite novi kompleksni broj(realni imaginarni): 2 2 Unesite novi kompleksni broj(realni imaginarni): 3 3 Unesite novi kompleksni broj(realni imaginarni): 4 4 Unesite novi kompleksni broj(realni imaginarni): 5 5 Unesite novi kompleksni broj(realni imaginarni): a { 1, 1 } { 2, 2 } { 3, 3 } { 4, 4 } { 5, 5 } ``` Upvotes: 1
2018/03/21
519
1,756
<issue_start>username_0: Let's say I have a simple template string : ``` const foo = `foo`; ``` How do I go about rendering this template string as HTML ? It renders it as plain text if I do the following : `return({ foo });` Output: ``` foo ``` Expected output: ``` foo ```<issue_comment>username_1: I think what you try to do is ``` const foo = `foo`; ``` [Related question.](https://stackoverflow.com/questions/37337289/react-js-set-innerhtml-vs-dangerouslysetinnerhtml) [React documentation.](https://reactjs.org/docs/dom-elements.html#dangerouslysetinnerhtml) Upvotes: 4 [selected_answer]<issue_comment>username_2: Off the top of my head there's 2 ways to parse a string (doesn't have to be a tl) into HTML: **[`.innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML)** property and the more powerful **[`.insertAdjacentHTML()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML)** method. Demo ---- ```js var tl = ` `; document.body.innerHTML = tl; document.body.insertAdjacentHTML('afterbegin', tl); ``` Upvotes: 0 <issue_comment>username_3: You note reactjs as a tag here. Instead of specifying the html as a string, make foo a functional react component. To do that, make sure you have `import React as 'react';`. Then, set foo as the functional component, i.e.: `const foo = () => foo;` Then, you can use that wherever you please. React components are just functions (or classes) that return jsx. Your question is fairly open-ended, so you may be looking for some of the above answers, but this is one approach. Upvotes: 1 <issue_comment>username_4: if you want to show the string of html as html page its better to do this: ``` {{ info | safe }} ``` Upvotes: 0
2018/03/21
1,281
3,762
<issue_start>username_0: I want to use a if-function to distingiush between two sceneraios. ``` For Each Cell In Tabelle3.Range("A" & lastrow2) Option A: If Cell <> "" Then run code Option B: If Cell = "" Then skip this empty cell and go on with the next one ``` Here the whole code: ``` Sub IfFunction() Dim lastrow2 As Long lastrow2 = Tabelle3.Range("A" & Rows.Count).End(xlUp).Row Set myrange2 = Tabelle8.UsedRange For i = 2 To lastrow2 For Each Cell In Tabelle3.Range("A" & lastrow2) If Cell = "" Then i = i + 1 Else: i = i Tabelle3.Cells(7 + i, 19) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 3, False) Tabelle3.Cells(7 + i, 20) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 4, False) Tabelle3.Cells(7 + i, 21) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 5, False) Next i End If End Sub ``` When I try to run this code, it does not execute because an error occurs that there is a 'ELSE without IF'-Function. Does anyone know how I can use an IF-function here or what to use instead? Thanks. :)<issue_comment>username_1: if you continue writing after `Then` this means the `If` statement consists of one line only: ``` If Cell = "" Then i = i + 1 'End If automatically here ``` Then the `Else` has to be in that line too: ``` If Cell = "" Then i = i + 1 Else i = i 'End If automatically here ``` If you want to use a multi line `If` statement ``` If Cell = "" Then i = i + 1 Else i = i End If ``` --- ### But … because `i = i` doesn't do anything you can just write ``` If Cell = "" Then i = i + 1 ``` and omit the `Else` part completely because it does nothing at all. --- ### And anther but … because you are using a `For i` the `Next i` increments `i` automatically and you don't need to increment it yourself. There is no `i = i + 1` needed Upvotes: 3 <issue_comment>username_2: your code has to `For` but one `Next` only, which would result in a syntax error furthermore the `Next i` is intertwined with a `If-Then-Else` block code which would also result in a syntax error finally I guess you're iterating twice along `Tabelle3` column A cells from row 2 to last not empty one, while you only need it once Summing all that up, I'd say you can use this code: ``` Option Explicit Sub IfFunction() Dim myrange2 As Range, cell As Range Set myrange2 = Tabelle8.UsedRange With Tabelle3 For Each cell In .Range("A2:A" & .Cells(.Rows.count, 1).End(xlUp)).SpecialCells(xlCellTypeConstants) cell.Offset(7, 18) = Application.WorksheetFunction.VLookup(cell.Offset(7), myrange2, 3, False) cell.Offset(7, 19) = Application.WorksheetFunction.VLookup(cell.Offset(7), myrange2, 4, False) cell.Offset(7, 20) = Application.WorksheetFunction.VLookup(cell.Offset(7), myrange2, 5, False) Next End With End Sub ``` Upvotes: 0 <issue_comment>username_3: Okay that was actually way to simple :D I was running through the same column twice by ``` For Each Cell In Tabelle3.Range("A" & lastrow2) If Cell = "" Then i = i + 1 Else: i = i ``` and ``` For i = 2 To lastrow2 ``` Instead I can simply use: ``` For i = 2 To lastrow2 If Tabelle3.Cells(7 + i, 1) <> "" Then Tabelle3.Cells(7 + i, 19) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 3, False) Tabelle3.Cells(7 + i, 20) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 4, False) Tabelle3.Cells(7 + i, 21) = Application.WorksheetFunction.VLookup(Tabelle3.Cells(7 + i, 1), myrange2, 5, False) End if Next i ``` Thanks alot for your help & contribution! Upvotes: 1 [selected_answer]
2018/03/21
640
1,668
<issue_start>username_0: I have a list of times for my web form and I need to remove some choices from the list based on `minimum` and `maximum` minute value. For example I want to only display times between 60 and 180 minutes Django Form: ``` time_list = ( ('', 'Select'), ('15', '15 Minutes'), ('30', '30 Minutes'), ('45', '45 Minutes'), ('60', '60 Minutes'), ('75', '1:15'), ('90', '1:30'), ('105', '1:45'), ('120', '2:00'), ('135', '2:15'), ('150', '2:30'), ('165', '2:45'), ('180', '3:00'), ('240', '4:00'), ('300', '5:00'), ('360', '6:00'), ('420', '7:00'), ('480', '8:00'), ('540', '9:00'), ('600', '10:00'), ('660', '11:00'), ('720', '12:00'), ('1440', '24:00'), ) min_time = 60 #defined in DB max_time = 180 #defined in DB ``` Here I'm unsuccessfully trying to filter the list: ``` tmp = [] for i in time_list: if i > min_time and i < max_time: tmp.append(i) time_list = tmp ```<issue_comment>username_1: Try to change it to ``` time_list = iter(time_list) next(time_list) tmp = [] for i in time_list: if int(i[0]) > min_time and int(i[0]) < max_time: tmp.append(i) time_list = tmp ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: In one line: ``` time_list = list(filter(lambda x: min_time < int(x[0]) < max_time, time_list[1:])) ``` If you want to include the empty choice: ``` time_list = [time_list[0]] + list(filter(lambda x: min_time < int(x[0]) < max_time, time_list[1:])) ``` Upvotes: 2
2018/03/21
256
797
<issue_start>username_0: How to change application theme at run time of an application developed in Team developer. I have already tried Build Settings - General settings, but there I didn't find any option for changing theme at run time.<issue_comment>username_1: Try to change it to ``` time_list = iter(time_list) next(time_list) tmp = [] for i in time_list: if int(i[0]) > min_time and int(i[0]) < max_time: tmp.append(i) time_list = tmp ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: In one line: ``` time_list = list(filter(lambda x: min_time < int(x[0]) < max_time, time_list[1:])) ``` If you want to include the empty choice: ``` time_list = [time_list[0]] + list(filter(lambda x: min_time < int(x[0]) < max_time, time_list[1:])) ``` Upvotes: 2
2018/03/21
733
2,400
<issue_start>username_0: I am attempting to create a regex pattern that matches a line where all the words begin with uppercase letters, regardless of length. It must also account for any number of equals signs ('=') being on either side. For example matches: ``` ==This Would Match== ===I Like My Cats=== ====Number Of Equals Signs Does Not Matter=== =====Nor Does Line Length Etc.===== ``` Non-matches: ``` ==This would not regardless of its length== ===Nor would this match, etc=== ``` How do I write this pattern?<issue_comment>username_1: Try this regex: ``` ^=*[A-Z][^ ]*( [A-Z][^ ]*)*=*$ ``` It allows for any number (including 0) of `=` signs on either side and requires every word to start with a capital letter. The `*` quantifier means 0 or more times. `[^ ]` is a negated character class, meaning it matches anything except a space. You can try it online [here](https://regex101.com/r/Ejku6j/1). Upvotes: 0 <issue_comment>username_2: This matches your desired results: ```js var test = [ "==This Would Match==", "===I Like My Cats===", "====Number Of Equals Signs Does Not Matter===", "=====Nor Does Line Length Etc.=====", "==This would not regardless of its length==", "===Nor would this match, etc===" ] var reg = /=*([A-Z]\w*\W*)+=*/g; console.log(test.map(t => t.match(reg) == t)); ``` Upvotes: 1 [selected_answer]<issue_comment>username_3: You could match one or more equals signs at either side like `=+`. To match words that begin with a capital letter could start with `[A-Z]` followed by `\w` one or more times. If you want to match more characters than `\w`, you could create a character class `[\w.]` to add matching a dot for example. This pattern would match between equals sign(s) zero or more times a word that starts with an uppercase character followed by a whitespace, and ends with a word that starts with an uppercase character: [`^=+(?:[A-Z]\w* )*(?:[A-Z][\w.]+)=+$`](https://regex101.com/r/6OfqGW/1) ```js const strings = [ "==This Would Match==", "===I Like My Cats===", "====Number Of Equals Signs Does Not Matter===", "=====Nor Does Line Length Etc.=====", "==This would not regardless of its length==", "===Nor would this match, etc===", "=aaaa=" ]; let pattern = /^=+(?:[A-Z]\w* )*(?:[A-Z][\w.]+)=+$/; strings.forEach((s) => { console.log(s + " ==> " + pattern.test(s)); }); ``` Upvotes: 1
2018/03/21
236
836
<issue_start>username_0: fairly Simple question regarding the new balham theme on Ag-grid. Id like to disable the side button and the tool panel completely as shown in the link below: <https://www.ag-grid.com/javascript-grid-tool-panel/> I can hide the tool panel, but cannot hide the side button labelled 'Columns' and was wondering if there was a simple way to do so? Many thanks<issue_comment>username_1: set the property showToolPanel to false in ag-grid ``` [showToolPanel]="false" ``` and if you completely want to remove the columns tool panel then you can override the css ``` .ag-theme-balham .ag-tool-panel{ visibility: hidden; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: In ag-grid v19, the option is sideBar = false ([sideBar docs](https://www.ag-grid.com/javascript-grid-side-bar/)) Upvotes: 0
2018/03/21
2,062
6,296
<issue_start>username_0: **Caution, I am a novice.** Objective: To create a "Comments" sheet that includes all comments from the current sheet selected. Here is what my sheet looks like: [![Source](https://i.stack.imgur.com/w9cov.png)](https://i.stack.imgur.com/w9cov.png) The way I want the sheet to look is: [![Preferred outcome](https://i.stack.imgur.com/yKruJ.png)](https://i.stack.imgur.com/yKruJ.png) The way the sheet **actually** appears is: [![Actual outcome](https://i.stack.imgur.com/CEeau.png)](https://i.stack.imgur.com/CEeau.png) Essentially, I do not want to use the "Parent Address" for the "Comment In" column but rather the heading above the cell. For example, I do not want $A$2 but actually want it to refer to the heading "Responsible Party". My initial thought was that I could use named ranges but it proved to be out of my capabilities. **I am not a strong coder. Please keep this in mind.** The code is as follows: ``` Sub ExtractComments() Dim ExComment As Comment Dim i As Integer Dim ws As Worksheet Dim CS As Worksheet Set CS = ActiveSheet If ActiveSheet.Comments.Count = 0 Then Exit Sub For Each ws In Worksheets If ws.Name = "Comments" Then i = 1 Next ws If i = 0 Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" Else: Set ws = Worksheets("Comments") End If For Each ExComment In CS.Comments ws.Range("A1").Value = "Comment In" ws.Range("B1").Value = "Comment By" ws.Range("C1").Value = "Comment" With ws.Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With If ws.Range("A2") = "" Then ws.Range("A2").Value = ExComment.Parent.Address ws.Range("B2").Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C2").Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Else ws.Range("A1").End(xlDown).Offset(1, 0) = ExComment.Parent.Address ws.Range("B1").End(xlDown).Offset(1, 0) = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C1").End(xlDown).Offset(1, 0) = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) End If Next ExComment End Sub ``` Thank you for your time.<issue_comment>username_1: use: ``` ws.Range("A2").Value = ExComment.Parent.End(xlUp).Value ``` so: ``` If ws.Range("A2") = "" Then ws.Range("A2").Value = ExComment.Parent.End(xlUp).Value ws.Range("B2").Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C2").Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Else ws.Range("A1").End(xlDown).Offset(1, 0) = ExComment.Parent.End(xlUp).Value ws.Range("B1").End(xlDown).Offset(1, 0) = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C1").End(xlDown).Offset(1, 0) = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) End If ``` while you could consider the following refactoring of your code ``` Sub ExtractComments() If ActiveSheet.Comments.count = 0 Then Exit Sub Dim ws As Worksheet On Error Resume Next Set ws = Worksheets("Comments") On Error GoTo 0 If ws Is Nothing Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" End If Dim ExComment As Comment With ws With .Range("A1:C1") .Value = Array("Comment In", "Comment By", "Comment") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With For Each ExComment In ActiveSheet.Comments .Cells(.Rows.count, 1).End(xlUp).Offset(1).Resize(, 3) = Array(ExComment.Parent.End(xlUp).Value, _ Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1), _ Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":"))) Next ExComment End With End Sub ``` Upvotes: 1 <issue_comment>username_2: It's definitely not bad from a novice :) Try this: ``` ... Else: Set ws = Worksheets("Comments") End If Dim iRow As Long ' you have a better control this way directly specifying the target cell ' header needs to written only once - out of loop ws.Range("A1").Value = "Comment In" ws.Range("B1").Value = "Comment By" ws.Range("C1").Value = "Comment" With ws.Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With iRow = 2 ' first empty row For Each ExComment In CS.Comments ws.Cells(iRow, 1).Value = CS.Cells(1, ExComment.Parent.Column) ' value in 1st row of column of comment ws.Cells(iRow, 2).Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Cells(iRow, 3).Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) iRow = iRow + 1 Next ExComment End Sub ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Just one change to add the header value, and shortened your code a little by working up from the bottom when adding comments, and remove some stuff from the loop. ``` Sub ExtractComments() Dim ExComment As Comment Dim i As Long Dim ws As Worksheet Dim CS As Worksheet Set CS = ActiveSheet If ActiveSheet.Comments.Count = 0 Then Exit Sub For Each ws In Worksheets If ws.Name = "Comments" Then i = 1 Next ws If i = 0 Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" Else: Set ws = Worksheets("Comments") End If With ws .Range("A1").Value = "Comment In" .Range("B1").Value = "Comment By" .Range("C1").Value = "Comment" With .Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With For Each ExComment In CS.Comments .Range("A" & Rows.Count).End(xlUp)(2).Value = CS.Cells(1, ExComment.Parent.Column) .Range("B" & Rows.Count).End(xlUp)(2).Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) .Range("C" & Rows.Count).End(xlUp)(2).Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Next ExComment End With End Sub ``` Upvotes: 2
2018/03/21
1,676
5,213
<issue_start>username_0: Having a really hard time actually getting numbers I need. I need to project the state where the most stoves are sold. I have: ``` SELECT DISTINCT TOP 2 C.StateProvince, COUNT(*) AS TimesSold FROM CUSTOMER C INNER JOIN INVOICE I ON C.CustomerID = I.FK_CustomerID INNER JOIN INV_LINE_ITEM L ON I.InvoiceNbr = L.FK_InvoiceNbr FULL OUTER JOIN STOVE S ON S.SerialNumber = L.FK_StoveNbr GROUP BY C.StateProvince, L.FK_StoveNbr ORDER BY TimesSold DESC; ``` My output I am getting is: ``` State Count ------ ----- OR 20 MT 16 ``` But the output I need is: ``` State Count ------ ----- OR 20 CO 9 ``` Which leads me to believe I am not counting the right thing. Data includes: ``` CUSTOMER (CustomerID, Name, StreetAddress, ApartmentNbr, City, StateProvince, Zipcode, Country) INVOICE (InvoiceNbr, InvoiceDt, TotalPrice, FK_CustomerID, FK_EmpID) EMPLOYEE (EmpID, Name, Title, Initials) INV_LINE_ITEM (LineNbr, Quantity, FK_InvoiceNbr, FK_PartNbr, FK_StoveNbr, ExtendedPrice) STOVE (SerialNumber, Type, Version, DateOfManufacture, Color, FK_EmpID) ```<issue_comment>username_1: use: ``` ws.Range("A2").Value = ExComment.Parent.End(xlUp).Value ``` so: ``` If ws.Range("A2") = "" Then ws.Range("A2").Value = ExComment.Parent.End(xlUp).Value ws.Range("B2").Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C2").Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Else ws.Range("A1").End(xlDown).Offset(1, 0) = ExComment.Parent.End(xlUp).Value ws.Range("B1").End(xlDown).Offset(1, 0) = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C1").End(xlDown).Offset(1, 0) = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) End If ``` while you could consider the following refactoring of your code ``` Sub ExtractComments() If ActiveSheet.Comments.count = 0 Then Exit Sub Dim ws As Worksheet On Error Resume Next Set ws = Worksheets("Comments") On Error GoTo 0 If ws Is Nothing Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" End If Dim ExComment As Comment With ws With .Range("A1:C1") .Value = Array("Comment In", "Comment By", "Comment") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With For Each ExComment In ActiveSheet.Comments .Cells(.Rows.count, 1).End(xlUp).Offset(1).Resize(, 3) = Array(ExComment.Parent.End(xlUp).Value, _ Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1), _ Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":"))) Next ExComment End With End Sub ``` Upvotes: 1 <issue_comment>username_2: It's definitely not bad from a novice :) Try this: ``` ... Else: Set ws = Worksheets("Comments") End If Dim iRow As Long ' you have a better control this way directly specifying the target cell ' header needs to written only once - out of loop ws.Range("A1").Value = "Comment In" ws.Range("B1").Value = "Comment By" ws.Range("C1").Value = "Comment" With ws.Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With iRow = 2 ' first empty row For Each ExComment In CS.Comments ws.Cells(iRow, 1).Value = CS.Cells(1, ExComment.Parent.Column) ' value in 1st row of column of comment ws.Cells(iRow, 2).Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Cells(iRow, 3).Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) iRow = iRow + 1 Next ExComment End Sub ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Just one change to add the header value, and shortened your code a little by working up from the bottom when adding comments, and remove some stuff from the loop. ``` Sub ExtractComments() Dim ExComment As Comment Dim i As Long Dim ws As Worksheet Dim CS As Worksheet Set CS = ActiveSheet If ActiveSheet.Comments.Count = 0 Then Exit Sub For Each ws In Worksheets If ws.Name = "Comments" Then i = 1 Next ws If i = 0 Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" Else: Set ws = Worksheets("Comments") End If With ws .Range("A1").Value = "Comment In" .Range("B1").Value = "Comment By" .Range("C1").Value = "Comment" With .Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With For Each ExComment In CS.Comments .Range("A" & Rows.Count).End(xlUp)(2).Value = CS.Cells(1, ExComment.Parent.Column) .Range("B" & Rows.Count).End(xlUp)(2).Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) .Range("C" & Rows.Count).End(xlUp)(2).Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Next ExComment End With End Sub ``` Upvotes: 2
2018/03/21
2,243
7,201
<issue_start>username_0: I am working with a group to make a command line tool that takes a lot of sub commands - e.g.: ``` cmdtool.exe foo 1 2 3 ``` or ``` cmdtool.exe bar 9 zombies ``` Currently it is implemented with a long and ugly list of ``` else if (command == "foo") { if (argLength < 3) { Console.Error.WriteLine("Error: not enough args for foo"); errorCode = ExitCode.Error; } else { // Do something useful } } else if (command == "bar") // repeat everything from foo ``` My issue with that is that there is a lot of duplicate code and no good overview of all our subcommands I know how I would do it in python: ``` def commandFoo(args): return DoFooStuff(args) def commandBar(args): return DoBarStuff(args) REGULAR_COMMANDS = { "foo": [1, 3, commandFoo], "bar": [2, 2, commandBar] } def evaluateCommand(cmdString, args): if cmdString not in REGULAR_COMMANDS: print("Unknown command:", cmdString) return False lower = REGULAR_COMMANDS[cmdString][0] upper = REGULAR_COMMANDS[cmdString][1] if not lower <= len(args) <= upper: print("Wrong number of args for:", cmdString) return False func = REGULAR_COMMANDS[cmdString][2] return func(args) ``` But how do I do that nicely in C#? I have come close with this: ``` private static int CommandFoo(string[] args) { Console.Error.WriteLine("FooFOO"); return (int)ExitCode.Success; } private static int CommandBar(string[] args) { Console.Error.WriteLine("BarBAR"); return (int)ExitCode.Error; } private static Dictionary> m\_dCommandFuncs = new Dictionary> { { "foo", {1, 3, CommandFoo}}, { "bar", {2, 2, CommandBar}} }; ``` But the syntax for initializing my lookup table is not correct and when I try to correct it, it gets ugly and still doesn't compile. Is this a limitation in the C# syntax? - that I cannot initialize dictionaries and lists in a pretty way? How would a C# expert go about this? **Complete Solution as given by @mcbr :** ``` delegate int Command(string[] args); private static int CommandFoo(string[] args) { Console.Error.WriteLine("FooFOO"); return (int)ExitCode.Success; } private static int CommandBar(string[] args) { Console.Error.WriteLine("BarBAR"); return (int)ExitCode.Error; } private static Dictionary> m\_dCommandFuncs = new Dictionary> { { "foo", new List{1, 3, (Command) CommandFoo}}, { "bar", new List{2, 2, (Command) CommandBar}} }; if (m\_dCommandFuncs.ContainsKey(command)) { List lLimitsAndFunc = m\_dCommandFuncs[command]; int lowerLimit = (int)lLimitsAndFunc[0]; int upperLimit = (int)lLimitsAndFunc[1]; Command commandFunc = (Command) lLimitsAndFunc[2]; if (argLength < lowerLimit || argLength > upperLimit) { Console.Error.WriteLine("error: {0}, wrong number of arguments", command); exitCode = (int)ExitCode.Error; } else { var segment = new ArraySegment(args, 1, (1 + upperLimit - lowerLimit)); exitCode = commandFunc(segment.ToArray()); } } ``` I also looked into various Nuget packages, but they add more clutter than benefits IMHO<issue_comment>username_1: use: ``` ws.Range("A2").Value = ExComment.Parent.End(xlUp).Value ``` so: ``` If ws.Range("A2") = "" Then ws.Range("A2").Value = ExComment.Parent.End(xlUp).Value ws.Range("B2").Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C2").Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Else ws.Range("A1").End(xlDown).Offset(1, 0) = ExComment.Parent.End(xlUp).Value ws.Range("B1").End(xlDown).Offset(1, 0) = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Range("C1").End(xlDown).Offset(1, 0) = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) End If ``` while you could consider the following refactoring of your code ``` Sub ExtractComments() If ActiveSheet.Comments.count = 0 Then Exit Sub Dim ws As Worksheet On Error Resume Next Set ws = Worksheets("Comments") On Error GoTo 0 If ws Is Nothing Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" End If Dim ExComment As Comment With ws With .Range("A1:C1") .Value = Array("Comment In", "Comment By", "Comment") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With For Each ExComment In ActiveSheet.Comments .Cells(.Rows.count, 1).End(xlUp).Offset(1).Resize(, 3) = Array(ExComment.Parent.End(xlUp).Value, _ Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1), _ Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":"))) Next ExComment End With End Sub ``` Upvotes: 1 <issue_comment>username_2: It's definitely not bad from a novice :) Try this: ``` ... Else: Set ws = Worksheets("Comments") End If Dim iRow As Long ' you have a better control this way directly specifying the target cell ' header needs to written only once - out of loop ws.Range("A1").Value = "Comment In" ws.Range("B1").Value = "Comment By" ws.Range("C1").Value = "Comment" With ws.Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With iRow = 2 ' first empty row For Each ExComment In CS.Comments ws.Cells(iRow, 1).Value = CS.Cells(1, ExComment.Parent.Column) ' value in 1st row of column of comment ws.Cells(iRow, 2).Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) ws.Cells(iRow, 3).Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) iRow = iRow + 1 Next ExComment End Sub ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Just one change to add the header value, and shortened your code a little by working up from the bottom when adding comments, and remove some stuff from the loop. ``` Sub ExtractComments() Dim ExComment As Comment Dim i As Long Dim ws As Worksheet Dim CS As Worksheet Set CS = ActiveSheet If ActiveSheet.Comments.Count = 0 Then Exit Sub For Each ws In Worksheets If ws.Name = "Comments" Then i = 1 Next ws If i = 0 Then Set ws = Worksheets.Add(After:=ActiveSheet) ws.Name = "Comments" Else: Set ws = Worksheets("Comments") End If With ws .Range("A1").Value = "Comment In" .Range("B1").Value = "Comment By" .Range("C1").Value = "Comment" With .Range("A1:C1") .Font.Bold = True .Interior.Color = RGB(189, 215, 238) .Columns.ColumnWidth = 20 End With For Each ExComment In CS.Comments .Range("A" & Rows.Count).End(xlUp)(2).Value = CS.Cells(1, ExComment.Parent.Column) .Range("B" & Rows.Count).End(xlUp)(2).Value = Left(ExComment.Text, InStr(1, ExComment.Text, ":") - 1) .Range("C" & Rows.Count).End(xlUp)(2).Value = Right(ExComment.Text, Len(ExComment.Text) - InStr(1, ExComment.Text, ":")) Next ExComment End With End Sub ``` Upvotes: 2
2018/03/21
901
3,599
<issue_start>username_0: I am writing a WPF application which has a lot of different controls, each with its own `ToolTip`. Although the `ToolTips` are useful, some of them are quite long and get in the way. I want to be able to create a button which will enable and disable all the tooltips on the app when it is clicked. what I've been working on seems like a really long and unnecessary way of going at is. Is there a way to accomplish what I want in a quick manner?<issue_comment>username_1: You could try to add an implicit style that sets the `Visbility` property of all `ToolTips` to `Collapsed` for all top-level windows. Something like this: ``` private bool _isToolTipVisible = true; private void Button_Click(object sender, RoutedEventArgs e) { Style style = new Style(typeof(ToolTip)); style.Setters.Add(new Setter(UIElement.VisibilityProperty, Visibility.Collapsed)); style.Seal(); foreach (Window window in Application.Current.Windows) { if (_isToolTipVisible) { window.Resources.Add(typeof(ToolTip), style); //hide _isToolTipVisible = false; } else { window.Resources.Remove(typeof(ToolTip)); //show _isToolTipVisible = true; } } } ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can add global tooltip style into application resources: ``` <Setter Property="Template" Value="{x:Null}" /> ``` This disable all tooltips. To toggle use following: ``` Style _style; void Button_Click(object sender, RoutedEventArgs e) { if (_style == null) { _style = (Style)Application.Current.Resources[typeof(ToolTip)]; Application.Current.Resources.Remove(typeof(ToolTip)); } else Application.Current.Resources.Add(typeof(ToolTip), _style); } ``` Upvotes: 1 <issue_comment>username_3: I needed to have custom tooltips that could be turned off. The other solutions didn't quite cover this, so here's what I ended up doing... This code allows you to have your customised tips, and to easily turn them on and off application-wide. In my case, I'm saving the tool-tip visibility in a user setting. The setting is applied on main window load and then updated if the setting is changed. In *App.xaml*: ``` <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToolTip"> <Border Name="Border" BorderThickness="1" Background="PaleGoldenrod" CornerRadius="4" BorderBrush="Black"> <ContentPresenter Margin="4"/> </Border> </ControlTemplate> </Setter.Value> </Setter> ... various other settings <Setter Property="Visibility" Value="Collapsed"/> ``` Then, in my *MainWindow.xaml.cs* (but could go wherever you are changing the tip visibility): ``` private Style styleWithTips; private Style styleNoTips; ... private void Window_Loaded(object sender, RoutedEventArgs e) { // Set initial tips on/off styleWithTips = (Style)Application.Current.Resources[typeof(ToolTip)]; styleNoTips = (Style)Application.Current.Resources["NoTip"]; updateTipStyle(); } private void Settings_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "ShowHints") { updateTipStyle(); } } ... private void updateTipStyle() { ResourceDictionary resources = Application.Current.Resources; bool showHints = Properties.Settings.Default.ShowHints; if (resources.Contains(typeof(ToolTip))) { resources.Remove(typeof(ToolTip)); } resources.Add(typeof(ToolTip), showHints ? styleWithTips: styleNoTips); } ``` Upvotes: 1
2018/03/21
783
2,832
<issue_start>username_0: I'm trying to compare a class type passed through as an object to the class type on the other side where the method is. How can I do this? I have this so far. The one side: ``` TechToday techToday = new TechToday(); SoftwareRevolution softwareRevolution = new SoftwareRevolution(); Subcriber s1 = new Subcriber(); s1.Subcribe(techToday); s1.Subcribe(softwareRevolution); ``` The other side: ``` class Subcriber { TechToday tt = new TechToday(); SoftwareRevolution sr = new SoftwareRevolution(); public void Subcribe(Object s) { if(s==tt) new ConsoleObserver(s); else new ConsoleOutput(s); } } ```<issue_comment>username_1: You can use `is` operator to check if object is of that particular type like: ``` if(s is TechToday) new ConsoleObserver(s); ``` or you can do something like: ``` if(s.GetType() == typeof(TechToday)) ``` if you are looking to do equality of objects then you will need to check first the type of it and then cast the reference to that specific type and then check for equality something like: ``` if(s is TechToday) { TechToday tt2 = s as TechToday; if(tt2 == tt) new ConsoleObserver(tt2); } ``` or you could also do it like: ``` TechToday tt2 = s as TechToday; if(tt2 == tt) new ConsoleObserver(tt2); ``` Another option is using the new feature of C# 7 pattern matching : ``` if (s is TechToday tt2) { if(tt2 == tt) new ConsoleObserver(tt2); } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: You can use the is operator: ``` class Subcriber { public void Subcribe(Object s) { if(s is TechToday) new ConsoleObserver(s); else new ConsoleOutput(s); } } ``` However using "as" might be better: ``` class Subcriber { public void Subcribe(Object s) { var tt = s as TechToday; if(tt!=null) // unlike above // value passed to ConsoleObserver is TechToday // casted already new ConsoleObserver(tt); else new ConsoleOutput(s); } } ``` Upvotes: 1 <issue_comment>username_3: I'd suggest to use overloads if possible: ``` class Subcriber { public void Subcribe(TechToday s) { new ConsoleObserver(s); } public void Subcribe(SoftwareRevolution s) { new ConsoleOutput(s); } } ``` If you have to stay with `object` in the signature of `Subscribe`, you probably want to use something along ``` if( s is TechToday ) { new ConsoleObserver(s); } ``` But **after all, this does not make much sense**, because as is, the created objects will go out of scope immediately after leaving `Subscribe`. Upvotes: 2
2018/03/21
1,661
5,510
<issue_start>username_0: plan: I want to grab the users last login data such as user-agent,ip,time,os etc. i successfully post all the data that is needed using the bellow: ```php $userfolder = $_SERVER['DOCUMENT_ROOT'].'/account/users/'.$auth_user->user_folder_name($userRow["user_id"],$userRow["username"]).'/'; if (isset($_SERVER['REQUEST_URI']) == '?Login=Success') { $uid = $userRow['user_id']; $last_login = $date->getTimestamp(); $last_login_ip = $_SERVER['REMOTE_ADDR']; if (!file_exists($userfolder.$userRow['username'].'-login.log')) { $filename = $userfolder.$userRow['username'].'-login.log'; $data = json_encode(array("user"=>$userRow['username'],"time" => $last_login,"ip_addy"=>$last_login_ip,"browser"=>$obj->showInfo('browser'),"browser_version"=>$obj->showInfo('version'),"os"=>$obj->showInfo('os'))); $save = fopen($filename, "w"); fwrite($save, $data."\r\n"); fclose($save); } } ``` Which would save something like this: > > {"user":"Admin","time":1521638903,"ip\_addy":"127.0.0.1","browser":"Google Chrome","browser\_version":"64.0.3282.","os":"Windows"} > > > Although now I set another if statement so if the users login data changes or the user logs in using another computer on their network it should do a line break and insert it into the file. ```php $get_data = file_get_contents($userfolder.$userRow['username']."-login.log"); $get_log = json_decode($get_data, true); if ($get_log['ip_addy'] != $userRow['user_last_login_ip'] && $get_log['time'] != $last_login && $get_log['browser'] != $obj->showInfo('browser')) { $filename = $userfolder.$userRow['username'].'-login.log'; $data = json_encode(array("user"=>$userRow['username'],"time" => $date->getTimestamp(),"ip_addy"=>$_SERVER['REMOTE_ADDR'],"browser"=>$obj->showInfo('browser'),"browser_version"=>$obj->showInfo('version'),"os"=>$obj->showInfo('os'))); $save = fopen($filename, "w"); fwrite($save, $data."\r\n"); fclose($save); } ``` which outputs the following: > > {"user":"Admin","time":1521639136,"ip\_addy":"127.0.0.1","browser":"Firefox","browser\_version":"59.0","os":"Windows"} > > > Notice that the previous 'Chrome' entry is no longer in the file as it removes the previous entry and writes a new one my intended output is to display it like the following: ```js { "result":{ "admin":[ { "time":1521639136, "ip_addy":"127.0.0.1", "browser":"Firefox", "browser_version":"59.0", "os":"Windows" } ] } } ``` it does not have to be formatted with space, it can simply be in one line and break line for the next input Current Problem: when data is save to the file and it needs to be updated the file then gets overwritten with the new data and old data is disgarded. Anyone able to help me achieve this would be greatly appreciated.<issue_comment>username_1: According to <http://php.net/manual/en/function.json-encode.php>, you can use JSON\_PRETTY\_PRINT option in json\_encode() `$data = json_encode(array(...), JSON_PRETTY_PRINT);` This should be avalible if you have php 5.4.0 or above. Upvotes: 1 <issue_comment>username_2: if you want to `Append` the content to a file and not overwrite it try : ``` $data = json_encode(array(...), JSON_PRETTY_PRINT); file_put_contents($filename , $data , FILE_APPEND | LOCK_EX); ``` instead of `fwrite()` this will create the file if it doesn't exist, and add content to it if it does > > If filename does not exist, the file is created. Otherwise, the > existing file is overwritten, unless the FILE\_APPEND flag is set. > > > Full documentation : <http://php.net/manual/en/function.file-put-contents.php> Upvotes: 0 <issue_comment>username_3: Finally figured out the error in the following: ``` if (!file_exists($userfolder.$userRow['username'].'-login.log')) { $filename = $userfolder.$userRow['username'].'-login.log'; $data = json_encode(array("user"=>$userRow['username'],"time" => $last_login,"ip_addy"=>$last_login_ip,"browser"=>$obj->showInfo('browser'),"browser_version"=>$obj->showInfo('version'),"os"=>$obj->showInfo('os'))); $save = fopen($filename, "w"); fwrite($save, $data."\r\n"); fclose($save); } ``` Basically `!file_exists` created a new file every time it logged the data so i thought why not try the if statement with just `file_exists` and have an `else` statement to handle if the file/folder does not exists. ``` if (file_exists($userfolder.$userRow['username'].'-login.log')) { //If the file exists do the following $filename = $userfolder.$userRow['username'].'-login.log'; $data = json_encode(array("user"=>$userRow['username'],"time" => $last_login,"ip_addy"=>$last_login_ip,"browser"=>$obj->showInfo('browser'),"browser_version"=>$obj->showInfo('version'),"os"=>$obj->showInfo('os'))); $save = fopen($filename, "w"); fwrite($save, $data."\r\n"); //break works without the !file_exists fclose($save); } else { //else if the file/folder does not exists do the following mkdir($usersfolder, 755); $save = fopen($usersfolder."/".$userRow['username']."-login.log", "a+"); $data = $last_login.",".$last_login_ip.",".$obj->showInfo('os').",".$obj->showInfo('browser').",".$obj->showInfo('version'); fwrite($save, $data."\r\n"); fclose($save); } ``` Upvotes: 1 [selected_answer]
2018/03/21
1,125
4,182
<issue_start>username_0: I have a required field validator in a Gridview. I want fire the validater only if the ddlPartsStatus is "Ordered". I just can't get it to work. At the moment required field validator fires for all the textboxes. my code ``` ``` Any help is greatly appreciated. Thanks<issue_comment>username_1: For this you need a `CustomValidator`. Then the `ClientValidationFunction` should evaluate both the TextBox and the DropDownList. ``` function checkValuesInRow(sender, element) { var isValid = false; var ddlValue = $("#" + sender.controltovalidate).closest('tr').find('select').val(); if (element.Value === "" && ddlValue === "0") { isValid = true; } element.IsValid = isValid; } ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: > > NOTE: Further reading is intended to be informative and not practical given all the clicking that must happen. But it shows how things *can* be done, not necessarily how the *should* be done and is only here due to the OP's Request for more info...so, here we go > > > Given this GridView : ``` ``` Renders a table with *x* number of validators based on your row count. You can use your browser's Developers Tools to inspect `gvPartsToOrderDetail` where you will find something similar to this, note the `data-val-validationgroup` attributes on all rows: ``` \* ``` Do you see that `data-val-validationgroup="vgSubmit"` is not unique? So when you click `btnSubmit` with its `ValidationGroup` set to "vgSubmit", they all get triggered. Now given @username_1's answer you may well prefer to keep it this way. And that's perfectly fine and legal and likely more in line with your needs. But to address the non-uniqueness of the Validation Group you can do this in the markup instead: ``` ``` which will then render: ``` ``` But now you have design problem. To isolate the validation group in the gridview and to tie it to your submit button you need to select a row, which means introducing a Select command button. More clicks, not good, but it can be done. But this introduces a couple of more issues: ``` 1. How do you tell the Submit button which validation group to validate? 2. Also the Submit button has a nasty habit of Posting back regardless of validation. ``` Both can be fixed like this: ``` ``` which is generated programmatically in `btnSubmit_PreRender` as follows: ``` protected void btnSubmit_PreRender( object sender, EventArgs e ) { btnSubmit.OnClientClick = string.Format( "return Page_ClientValidate('vgSubmit_{0}')", gvPartsToOrderDetail.SelectedIndex ); } ``` What follows is the Code behind and the page markup for review: > > To sum up, this solution, if you can call it that: > > > 1. Unique validation group names PER ROW > 2. Requires the addition of a selected row > 3. Rendering the Submit button to prevent postbacks and isolate the appropriate validation group > > > I can only hope this was at least informative and maybe gave you some ideas about the versatility of Server controls. Happy Programming... Code behind: ``` namespace WebApplication3 { public partial class _Default : Page { protected void Page_Load( object sender, EventArgs e ) { if ( !Page.IsPostBack ) { List ListOfParts = new List( new Parts[ ] { new Parts(0, 0), new Parts(0, 0), new Parts(0, 0) } ); gvPartsToOrderDetail.DataSource = ListOfParts; gvPartsToOrderDetail.DataBind(); } } protected void Button1\_PreRender( object sender, EventArgs e ) { Button1.OnClientClick = string.Format( "return Page\_ClientValidate('vgSubmit\_{0}')", gvPartsToOrderDetail.SelectedIndex ); } } //------------------------------------------------------------ // Dummy data class // public class Parts { public Parts( int ticketNo, int status ) { TicketNo = ticketNo; Status = status; } public int TicketNo { get; set; } public int Status { get; set; } } } ``` And the Markup: ``` <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication3._Default" %> ``` Upvotes: 1
2018/03/21
425
1,812
<issue_start>username_0: I have a `Java Object` that I am trying to map into a `JSON` object. Is there an online tool where I can print the Java object using `toString()` and convert it to a `JSON` object? I know that I can do it in code using e.g: <https://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/><issue_comment>username_1: It sounds like you just need the JSON in plain text so you can copy/paste or something. If so, you could set up something incredibly simple using Spring Boot and Jackson, map whatever JSON you're trying to copy to a URI using `@RequestMapping("/")`, and as long as you have your controller annotated with `@RestController`, whatever object you return in the method will automatically be parsed to a JSON when Jackson is on your classpath. Then just go to localhost in your browser and the request uri you specified and you'll have a plain text JSON as a response. Something like this: ``` @RestController public class Controller { @RequestMapping("/") public SomeClass returnObjectInBrowser() { SomeClass someClass = new SomeClass(); someClass.doStuff(); return someClass; } } ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: You can override the `toString()` method of the bean class to convert object to JSON string ``` @Override public String toString() { String str = ""; // Converts object to json string using GSON // Gson gson = new Gson(); // str = gson.toJson(this); //Converts object to json string using Jaxson ObjectMapper mapper = new ObjectMapper(); try { str = mapper.writeValueAsString(this); } catch (Exception exception) { log.error(exception); } return str; } ``` Upvotes: 0
2018/03/21
10,219
29,644
<issue_start>username_0: I am trying to connect Gemfire 8.2 using apache calcite geode adopter. As per following logs its connectied properly but while try to execute query getting exception . > > Note : <http://calcite.apache.org/news/2018/03/19/release-1.16.0/> > > > Moreover, a new adapter to read data from Apache Geode was added in > this release. In addition, more progress has been made for the > existing adapters > > > **1) Connection class** ``` package com.khan.vaquar; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import com.google.common.collect.ImmutableMap; public class GemfireJDBCTest1 { public static void main(String[] args) { // new GemfireJDBCTest1().connection1(); // //new GemfireJDBCTest1().connection2(); } /*** * */ public void connection1() { try { Class.forName(org.apache.calcite.jdbc.Driver.class.getName()); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Properties info = new Properties(); info.setProperty("lex", "JAVA"); // Enables case sensitivity info.setProperty("model", "C://Users//vkhan//Documents//scala-workspace//CalciteGemfire//src//com//khan//vaquar//myModel.json "); // See // section // below try { Connection connection = DriverManager.getConnection("jdbc:calcite:", info); Statement statement = connection.createStatement(); ResultSet resultset = statement.executeQuery("select * from account"); //("select * from \"account\""); final StringBuilder buf = new StringBuilder(); while (resultset.next()) { ResultSetMetaData metaData = resultset.getMetaData(); /* for (int i = 1; i <= metaData.getColumnCount(); i++) { } */ } System.out.println("Conected---------------------------"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } ``` **2) JSON "myModel.json"** ``` { "version": "1.0", "defaultSchema": "geode", "schemas": [ { "name": "geode_raw", "type": "custom", "factory": "org.apache.calcite.adapter.geode.rel.GeodeSchemaFactory", "operand": { "locatorHost": "localhost", "locatorPort": "10334", "regions": "account", "pdxSerializablePackagePath": ".*" } } ] } ``` **Jars** ``` aggdesigner-algorithm-6.0.jar antlr-2.7.7.jar avatica-core-1.11.0.jar avatica-metrics-1.11.0.jar calcite-core-1.16.0.jar calcite-geode-1.16.0.jar calcite-linq4j-1.16.0.jar commons-beanutils-1.9.3.jar commons-codec-1.9.jar commons-collections-3.2.2.jar commons-compiler-2.7.6.jar commons-dbcp-1.4.jar commons-digester-2.1.jar commons-io-2.5.jar commons-lang-2.6.jar commons-lang3-3.2.jar commons-logging-1.1.3.jar commons-pool-1.5.4.jar commons-validator-1.6.jar esri-geometry-api-2.0.0.jar fast-classpath-scanner-2.0.11.jar fastutil-7.1.0.jar findbugs-annotations-1.3.9-1.jar geode-common-1.3.0.jar geode-core-1.3.0.jar geode-json-1.3.0.jar guava-19.0.jar httpclient-4.5.2.jar httpcore-4.4.4.jar jackson-annotations-2.9.4.jar jackson-core-2.9.4.jar jackson-databind-2.9.4.jar janino-2.7.6.jar javax.resource-api-1.7.jar javax.transaction-api-1.2.jar jgroups-3.6.10.Final.jar jna-4.0.0.jar jopt-simple-5.0.3.jar jsr305-3.0.1.jar log4j-api-2.8.2.jar log4j-core-2.8.2.jar memory-0.9.0.jar protobuf-java-3.3.0.jar shiro-core-1.3.2.jar sketches-core-0.9.0.jar slf4j-api-1.7.13.jar ``` Gemfire 8.2 (Geode) [![enter image description here](https://i.stack.imgur.com/bE76o.png)](https://i.stack.imgur.com/bE76o.png) When using this query getting following exception (1) ResultSet resultset = statement.executeQuery("select \* from account"); **Exception :** ``` Build-Date: 2017-10-26 21:57:38 +0530 Build-Id: sbawaskar 0 Build-Java-Version: 1.8.0_121 Build-Platform: Mac OS X 10.12.6 x86_64 Product-Name: Apache Geode Product-Version: 1.3.0 Source-Date: 2017-10-18 22:02:15 +0530 Source-Repository: release/1.3.0 Source-Revision: 59f2a73d108101744ed7b2d88e8d1c948d19781c Native version: native code unavailable Running on: /3.142.66.67, 4 cpu(s), amd64 Windows 7 6.1 Communications version: 70 Process ID: 16120 User: VKhan Current dir: C:\Users\VKhan\Documents\scala-workspace\CalciteGemfire Home dir: C:\Users\VKhan Command Line Parameters: -Dfile.encoding=Cp1252 Class Path: C:\Users\VKhan\Documents\scala-workspace\CalciteGemfire\bin C:\jars\aggdesigner-algorithm-6.0.jar C:\jars\antlr-2.7.7.jar C:\jars\avatica-core-1.11.0.jar C:\jars\avatica-metrics-1.11.0.jar C:\jars\calcite-core-1.16.0.jar C:\jars\calcite-geode-1.16.0.jar C:\jars\calcite-linq4j-1.16.0.jar C:\jars\commons-beanutils-1.9.3.jar C:\jars\commons-codec-1.9.jar C:\jars\commons-collections-3.2.2.jar C:\jars\commons-compiler-2.7.6.jar C:\jars\commons-dbcp-1.4.jar C:\jars\commons-digester-2.1.jar C:\jars\commons-io-2.5.jar C:\jars\commons-lang-2.6.jar C:\jars\commons-lang3-3.2.jar C:\jars\commons-logging-1.1.3.jar C:\jars\commons-pool-1.5.4.jar C:\jars\commons-validator-1.6.jar C:\jars\esri-geometry-api-2.0.0.jar C:\jars\fast-classpath-scanner-2.0.11.jar C:\jars\fastutil-7.1.0.jar C:\jars\findbugs-annotations-1.3.9-1.jar C:\jars\geode-common-1.3.0.jar C:\jars\geode-core-1.3.0.jar C:\jars\geode-json-1.3.0.jar C:\jars\guava-19.0.jar C:\jars\httpclient-4.5.2.jar C:\jars\httpcore-4.4.4.jar C:\jars\jackson-annotations-2.9.4.jar C:\jars\jackson-core-2.9.4.jar C:\jars\jackson-databind-2.9.4.jar C:\jars\janino-2.7.6.jar C:\jars\javax.resource-api-1.7.jar C:\jars\javax.transaction-api-1.2.jar C:\jars\jgroups-3.6.10.Final.jar C:\jars\jna-4.0.0.jar C:\jars\jopt-simple-5.0.3.jar C:\jars\jsr305-3.0.1.jar C:\jars\log4j-api-2.8.2.jar C:\jars\log4j-core-2.8.2.jar C:\jars\memory-0.9.0.jar C:\jars\protobuf-java-3.3.0.jar C:\jars\shiro-core-1.3.2.jar C:\jars\sketches-core-0.9.0.jar C:\jars\slf4j-api-1.7.13.jar Library Path: C:\Program Files\Java\jdk1.8.0_131\jre\bin C:\WINDOWS\Sun\Java\bin C:\WINDOWS\system32 C:\WINDOWS C:/Program Files (x86)/Java/jre1.8.0_161/bin/client C:/Program Files (x86)/Java/jre1.8.0_161/bin C:/Program Files (x86)/Java/jre1.8.0_161/lib/i386 C:\ProgramData\Oracle\Java\javapath C:\Program Files (x86)\RSA SecurID Token Common C:\WINDOWS\system32 C:\WINDOWS C:\WINDOWS\System32\Wbem C:\WINDOWS\System32\WindowsPowerShell\v1.0\ C:\Program Files (x86)\WebEx\Productivity Tools C:\Program Files (x86)\Extra!\ C:\Program Files (x86)\WebEx\PTools020000000 C:\SUPPORT\apache-maven-3.3.9\bin C:\Program Files\TortoiseSVN\bin C:\Program Files\Cloud Foundry C:\Users\VKhan\AppData\Roaming\Cloud Foundry C:\Program Files (x86)\Sennheiser\SoftphoneSDK\ C:\Program Files (x86)\PuTTY\ C:\Program Files\Git\cmd C:\spark\video\softwareandcode\Spark\bin C:\hadoop\bin C:\Program Files (x86)\sbt\bin C:\vaquarkhan\sts-bundle\sts-3.8.4.RELEASE . System Properties: awt.toolkit = sun.awt.windows.WToolkit file.encoding = Cp1252 file.encoding.pkg = sun.io file.separator = \ java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment java.awt.printerjob = sun.awt.windows.WPrinterJob java.class.version = 52.0 java.endorsed.dirs = C:\Program Files\Java\jdk1.8.0_131\jre\lib\endorsed java.ext.dirs = C:\Program Files\Java\jdk1.8.0_131\jre\lib\ext;C:\WINDOWS\Sun\Java\lib\ext java.home = C:\Program Files\Java\jdk1.8.0_131\jre java.io.tmpdir = C:\Users\VKhan\AppData\Local\Temp\ java.runtime.name = Java(TM) SE Runtime Environment java.runtime.version = 1.8.0_131-b11 java.specification.name = Java Platform API Specification java.specification.vendor = Oracle Corporation java.specification.version = 1.8 java.vendor = Oracle Corporation java.vendor.url = http://java.oracle.com/ java.vendor.url.bug = http://bugreport.sun.com/bugreport/ java.version = 1.8.0_131 java.vm.info = mixed mode java.vm.name = Java HotSpot(TM) 64-Bit Server VM java.vm.specification.name = Java Virtual Machine Specification java.vm.specification.vendor = Oracle Corporation java.vm.specification.version = 1.8 java.vm.vendor = Oracle Corporation java.vm.version = 25.131-b11 line.separator = os.version = 6.1 path.separator = ; sun.arch.data.model = 64 sun.boot.class.path = C:\Program Files\Java\jdk1.8.0_131\jre\lib\resources.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\rt.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jce.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.8.0_131\jre\lib\jfr.jar;C:\Program Files\Java\jdk1.8.0_131\jre\classes sun.boot.library.path = C:\Program Files\Java\jdk1.8.0_131\jre\bin sun.cpu.endian = little sun.cpu.isalist = amd64 sun.desktop = windows sun.io.unicode.encoding = UnicodeLittle sun.java.command = com.khan.vaquar.GemfireJDBCTest1 sun.java.launcher = SUN_STANDARD sun.jnu.encoding = Cp1252 sun.management.compiler = HotSpot 64-Bit Tiered Compilers sun.nio.ch.bugLevel = sun.os.patch.level = Service Pack 1 user.country = US user.language = en user.script = user.timezone = America/Chicago user.variant = Log4J 2 Configuration: jar:file:/C:/jars/geode-core-1.3.0.jar!/log4j2.xml --------------------------------------------------------------------------- [info 2018/03/21 10:41:02.553 CDT tid=0x1] Running in client mode [info 2018/03/21 10:41:02.646 CDT tid=0x1] Requesting cluster configuration [info 2018/03/21 10:41:02.646 CDT tid=0x1] Loading previously deployed jars [info 2018/03/21 10:41:02.709 CDT tid=0x1] AutoConnectionSource UpdateLocatorListTask started with interval=10,000 ms. [info 2018/03/21 10:41:02.709 CDT tid=0x1] Pool DEFAULT started with multiuser-authentication=false java.sql.SQLException: Error while executing SQL "select \* from account": From line 1, column 15 to line 1, column 21: Object 'account' not found at org.apache.calcite.avatica.Helper.createException(Helper.java:56) at org.apache.calcite.avatica.Helper.createException(Helper.java:41) at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:156) at org.apache.calcite.avatica.AvaticaStatement.executeQuery(AvaticaStatement.java:218) at com.khan.vaquar.GemfireJDBCTest1.connection1(GemfireJDBCTest1.java:43) at com.khan.vaquar.GemfireJDBCTest1.main(GemfireJDBCTest1.java:17) Caused by: org.apache.calcite.runtime.CalciteContextException: From line 1, column 15 to line 1, column 21: Object 'account' not found at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.apache.calcite.runtime.Resources$ExInstWithCause.ex(Resources.java:463) at org.apache.calcite.sql.SqlUtil.newContextException(SqlUtil.java:803) at org.apache.calcite.sql.SqlUtil.newContextException(SqlUtil.java:788) at org.apache.calcite.sql.validate.SqlValidatorImpl.newValidationError(SqlValidatorImpl.java:4706) at org.apache.calcite.sql.validate.IdentifierNamespace.resolveImpl(IdentifierNamespace.java:172) at org.apache.calcite.sql.validate.IdentifierNamespace.validateImpl(IdentifierNamespace.java:177) at org.apache.calcite.sql.validate.AbstractNamespace.validate(AbstractNamespace.java:84) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateNamespace(SqlValidatorImpl.java:947) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateQuery(SqlValidatorImpl.java:928) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateFrom(SqlValidatorImpl.java:2975) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateFrom(SqlValidatorImpl.java:2960) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateSelect(SqlValidatorImpl.java:3219) at org.apache.calcite.sql.validate.SelectNamespace.validateImpl(SelectNamespace.java:60) at org.apache.calcite.sql.validate.AbstractNamespace.validate(AbstractNamespace.java:84) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateNamespace(SqlValidatorImpl.java:947) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateQuery(SqlValidatorImpl.java:928) at org.apache.calcite.sql.SqlSelect.validate(SqlSelect.java:226) at org.apache.calcite.sql.validate.SqlValidatorImpl.validateScopedExpression(SqlValidatorImpl.java:903) at org.apache.calcite.sql.validate.SqlValidatorImpl.validate(SqlValidatorImpl.java:613) at org.apache.calcite.sql2rel.SqlToRelConverter.convertQuery(SqlToRelConverter.java:553) at org.apache.calcite.prepare.Prepare.prepareSql(Prepare.java:264) at org.apache.calcite.prepare.Prepare.prepareSql(Prepare.java:230) at org.apache.calcite.prepare.CalcitePrepareImpl.prepare2\_(CalcitePrepareImpl.java:781) at org.apache.calcite.prepare.CalcitePrepareImpl.prepare\_(CalcitePrepareImpl.java:640) at org.apache.calcite.prepare.CalcitePrepareImpl.prepareSql(CalcitePrepareImpl.java:610) at org.apache.calcite.jdbc.CalciteConnectionImpl.parseQuery(CalciteConnectionImpl.java:221) at org.apache.calcite.jdbc.CalciteMetaImpl.prepareAndExecute(CalciteMetaImpl.java:603) at org.apache.calcite.avatica.AvaticaConnection.prepareAndExecuteInternal(AvaticaConnection.java:638) at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:149) ... 3 more Caused by: org.apache.calcite.sql.validate.SqlValidatorException: Object 'account' not found at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.apache.calcite.runtime.Resources$ExInstWithCause.ex(Resources.java:463) at org.apache.calcite.runtime.Resources$ExInst.ex(Resources.java:572) ... 31 more [info 2018/03/21 10:41:03.427 CDT tid=0xc] VM is exiting - shutting down distributed system [info 2018/03/21 10:41:03.427 CDT tid=0xc] GemFireCache[id = 657069980; isClosing = true; isShutDownAll = false; created = Wed Mar 21 10:41:02 CDT 2018; server = false; copyOnRead = false; lockLease = 120; lockTimeout = 60]: Now closing. [info 2018/03/21 10:41:03.505 CDT tid=0xc] Destroying connection pool DEFAULT [info 2018/03/21 10:41:05.581 CDT tid=0x18] AutoConnectionSource discovered new locators [XXXX/XXXX:10334] [info 2018/03/21 10:41:05.613 CDT tid=0x19] Updating membership port. Port changed from 0 to 64,781. ID is now XXXXXX(16120:loner):0:8b803849 ``` 2) When using following style getting following exception ``` ResultSet resultset = statement.executeQuery("select * from \"account\""); ``` **Exception :** ``` [info 2018/03/21 11:00:09.274 CDT tid=0x1] Running in client mode [info 2018/03/21 11:00:09.352 CDT tid=0x1] Requesting cluster configuration [info 2018/03/21 11:00:09.368 CDT tid=0x1] Loading previously deployed jars [info 2018/03/21 11:00:09.430 CDT tid=0x1] AutoConnectionSource UpdateLocatorListTask started with interval=10,000 ms. [info 2018/03/21 11:00:09.430 CDT tid=0x1] Pool DEFAULT started with multiuser-authentication=false java.sql.SQLException: Error while executing SQL "select \* from "account"": parse failed: Encountered "from \"" at line 1, column 10. Was expecting one of: "ORDER" ... "LIMIT" ... "OFFSET" ... "FETCH" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" "LATERAL" ... "FROM" "(" ... "FROM" "UNNEST" ... "FROM" "TABLE" ... "," ... "AS" ... ... ... ... ... ... "UNION" ... "INTERSECT" ... "EXCEPT" ... "MINUS" ... at org.apache.calcite.avatica.Helper.createException(Helper.java:56) at org.apache.calcite.avatica.Helper.createException(Helper.java:41) at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:156) at org.apache.calcite.avatica.AvaticaStatement.executeQuery(AvaticaStatement.java:218) at com.khan.vaquar.GemfireJDBCTest1.connection1(GemfireJDBCTest1.java:43) at com.khan.vaquar.GemfireJDBCTest1.main(GemfireJDBCTest1.java:17) Caused by: java.lang.RuntimeException: parse failed: Encountered "from \"" at line 1, column 10. Was expecting one of: "ORDER" ... "LIMIT" ... "OFFSET" ... "FETCH" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" "LATERAL" ... "FROM" "(" ... "FROM" "UNNEST" ... "FROM" "TABLE" ... "," ... "AS" ... ... ... ... ... ... "UNION" ... "INTERSECT" ... "EXCEPT" ... "MINUS" ... at org.apache.calcite.prepare.CalcitePrepareImpl.prepare2\_(CalcitePrepareImpl.java:760) at org.apache.calcite.prepare.CalcitePrepareImpl.prepare\_(CalcitePrepareImpl.java:640) at org.apache.calcite.prepare.CalcitePrepareImpl.prepareSql(CalcitePrepareImpl.java:610) at org.apache.calcite.jdbc.CalciteConnectionImpl.parseQuery(CalciteConnectionImpl.java:221) at org.apache.calcite.jdbc.CalciteMetaImpl.prepareAndExecute(CalciteMetaImpl.java:603) at org.apache.calcite.avatica.AvaticaConnection.prepareAndExecuteInternal(AvaticaConnection.java:638) at org.apache.calcite.avatica.AvaticaStatement.executeInternal(AvaticaStatement.java:149) ... 3 more Caused by: org.apache.calcite.sql.parser.SqlParseException: Encountered "from \"" at line 1, column 10. Was expecting one of: "ORDER" ... "LIMIT" ... "OFFSET" ... "FETCH" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" "LATERAL" ... "FROM" "(" ... "FROM" "UNNEST" ... "FROM" "TABLE" ... "," ... "AS" ... ... ... ... ... ... "UNION" ... "INTERSECT" ... "EXCEPT" ... "MINUS" ... at org.apache.calcite.sql.parser.impl.SqlParserImpl.convertException(SqlParserImpl.java:350) at org.apache.calcite.sql.parser.impl.SqlParserImpl.normalizeException(SqlParserImpl.java:131) at org.apache.calcite.sql.parser.SqlParser.parseQuery(SqlParser.java:138) at org.apache.calcite.sql.parser.SqlParser.parseStmt(SqlParser.java:163) at org.apache.calcite.prepare.CalcitePrepareImpl.prepare2\_(CalcitePrepareImpl.java:756) ... 9 more Caused by: org.apache.calcite.sql.parser.impl.ParseException: Encountered "from \"" at line 1, column 10. Was expecting one of: "ORDER" ... "LIMIT" ... "OFFSET" ... "FETCH" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" ... "FROM" "LATERAL" ... "FROM" "(" ... "FROM" "UNNEST" ... "FROM" "TABLE" ... "," ... "AS" ... ... ... ... ... ... "UNION" ... "INTERSECT" ... "EXCEPT" ... "MINUS" ... at org.apache.calcite.sql.parser.impl.SqlParserImpl.generateParseException(SqlParserImpl.java:22776) at org.apache.calcite.sql.parser.impl.SqlParserImpl.jj\_consume\_token(SqlParserImpl.java:22593) at org.apache.calcite.sql.parser.impl.SqlParserImpl.SqlStmtEof(SqlParserImpl.java:873) at org.apache.calcite.sql.parser.impl.SqlParserImpl.parseSqlStmtEof(SqlParserImpl.java:187) at org.apache.calcite.sql.parser.SqlParser.parseQuery(SqlParser.java:131) ... 11 more [info 2018/03/21 11:00:09.994 CDT tid=0xc] VM is exiting - shutting down distributed system ``` **Updated** I have tried old code and git example code provided by Christian with Gemfire 9.0 and 9.2.2 but getting same exception [![enter image description here](https://i.stack.imgur.com/TYJIf.png)](https://i.stack.imgur.com/TYJIf.png) [![enter image description here](https://i.stack.imgur.com/HGgni.png)](https://i.stack.imgur.com/HGgni.png) 1) Example in git ``` package com.khan.vaquar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.Properties; /** * Example of using Geode via JDBC. * * Before using this example, you need to populate Geode, as follows: \* \* > `* git clone https://github.com/vlsi/calcite-test-dataset > > * cd calcite-test-dataset > > * mvn install > *` \* \* This will create a virtual machine with Geode and the "bookshop" and "zips" \* test data sets. \*/ public class RelationalJdbcExample { protected static final Logger LOGGER = LoggerFactory.getLogger( RelationalJdbcExample.class.getName()); private RelationalJdbcExample() { } public static void main(String[] args) throws Exception { final String geodeModelJson = "inline:" + "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " type: 'custom',\n" + " name: 'TEST',\n" + " factory: 'org.apache.calcite.adapter.geode.rel.GeodeSchemaFactory',\n" + " operand: {\n" + " locatorHost: 'localhost', \n" + " locatorPort: '10334', \n" + " regions: 'account,BookMaster,BookCustomer,BookInventory,BookOrder', \n" + " pdxSerializablePackagePath: 'org.apache.calcite.adapter.geode.domain.\*' \n" + " }\n" + " }\n" + " ]\n" + "}"; Class.forName("org.apache.calcite.jdbc.Driver"); Properties info = new Properties(); info.put("model", geodeModelJson); Connection connection = DriverManager.getConnection("jdbc:calcite:", info); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery( /\*"SELECT \"b\".\"author\", \"b\".\"retailCost\", \"i\".\"quantityInStock\"\n" + "FROM \"TEST\".\"BookMaster\" AS \"b\" " + " INNER JOIN \"TEST\".\"BookInventory\" AS \"i\"" + " ON \"b\".\"itemNumber\" = \"i\".\"itemNumber\"\n " + "WHERE \"b\".\"retailCost\" > 0" \*/ "SELECT \"b\".\"\*\" FROM \"account\" AS \"b\" " ); final StringBuilder buf = new StringBuilder(); while (resultSet.next()) { ResultSetMetaData metaData = resultSet.getMetaData(); for (int i = 1; i <= metaData.getColumnCount(); i++) { buf.append(i > 1 ? "; " : "") .append(metaData.getColumnLabel(i)).append("=").append(resultSet.getObject(i)); } LOGGER.info("Result entry: " + buf.toString()); buf.setLength(0); } resultSet.close(); statement.close(); connection.close(); } } ``` 2) Example in git ``` package com.khan.vaquar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.Properties; /** * Example of using Geode via JDBC. */ public class SimpleJdbcExample { protected static final Logger LOGGER = LoggerFactory.getLogger(SimpleJdbcExample.class.getName()); private SimpleJdbcExample() { } public static void main(String[] args) throws Exception { Properties info = new Properties(); final String model = "inline:" + "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " type: 'custom',\n" + " name: 'TEST',\n" + " factory: 'org.apache.calcite.adapter.geode.simple" + ".GeodeSimpleSchemaFactory',\n" + " operand: {\n" + " locatorHost: 'localhost',\n" + " locatorPort: '10334',\n" + " regions: 'account,BookMaster',\n" + " pdxSerializablePackagePath: 'org.apache.calcite.adapter.geode.domain.*'\n" + " }\n" + " }\n" + " ]\n" + "}"; info.put("model", model); Class.forName("org.apache.calcite.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:calcite:", info); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("SELECT * FROM \"account\""); final StringBuilder buf = new StringBuilder(); while (resultSet.next()) { int columnCount = resultSet.getMetaData().getColumnCount(); for (int i = 1; i <= columnCount; i++) { buf.append(i > 1 ? "; " : "") .append(resultSet.getMetaData().getColumnLabel(i)) .append("=") .append(resultSet.getObject(i)); } LOGGER.info("Entry: " + buf.toString()); buf.setLength(0); } resultSet.close(); statement.close(); connection.close(); } } ```<issue_comment>username_1: The Geode Adapter is compiled with Geode version: 1.3 (<https://github.com/apache/calcite/blob/master/pom.xml#L79>) that corresponds to Gemfire 9.x. Because the Gemfire 8.x is **code incompatible** with Gemfire 9.x. you would not be able to use the Geode Adapter on the Gemfire 8.x or older. Furthermore the OQL in Gemfire 8.x doesn't support GROUP BY construct either. Upvotes: 2 <issue_comment>username_2: I have made following changes into my code to connect Gemfire 9.6 using apache calcite. 1) Geode or Gemfire has no concepts of schema however in apache calcite we have to define it,example ``` final String geodeModelJson = "inline:" + "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " type: 'custom',\n" + " name: 'TEST',\n" + " factory: 'org.apache.calcite.adapter.geode.rel.GeodeSchemaFactory',\n" + " operand: {\n" + " locatorHost: 'localhost', \n" + " locatorPort: '10334', \n" + " regions: 'test1', \n" + " pdxSerializablePackagePath: 'org.apache.calcite.adapter.geode.domain.*' \n" + " }\n" + " }\n" + " ]\n" + "}"; ``` Here you can see schema name =TEST , this is mandatory to connect gemfire else will get error no object found. Then you have to use in sql ``` ResultSet resultSet = statement.executeQuery("select * from \"TEST\".\"test1\""); ``` 2) You need to define your region name in "" else it will convert to uppercase and gemfire region name is case sensetive so account ,ACCOUNT,Account are three diffrent region in gemfire ``` \"TEST\".\"test1\" ``` Here you find full Java code : Jar file : [![enter image description here](https://i.stack.imgur.com/FCnwG.png)](https://i.stack.imgur.com/FCnwG.png) ``` package com.khan.vaquar; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import java.util.Properties; public class RelationalJdbcExample { protected static final Logger LOGGER = LoggerFactory.getLogger( RelationalJdbcExample.class.getName()); private RelationalJdbcExample() { } public static void main(String[] args) throws Exception { final String geodeModelJson = "inline:" + "{\n" + " version: '1.0',\n" + " schemas: [\n" + " {\n" + " type: 'custom',\n" + " name: 'TEST',\n" + " factory: 'org.apache.calcite.adapter.geode.rel.GeodeSchemaFactory',\n" + " operand: {\n" + " locatorHost: 'localhost', \n" + " locatorPort: '10334', \n" + " regions: 'test1', \n" + " pdxSerializablePackagePath: 'org.apache.calcite.adapter.geode.domain.*' \n" + " }\n" + " }\n" + " ]\n" + "}"; Class.forName("org.apache.calcite.jdbc.Driver"); Properties info = new Properties(); info.put("model", geodeModelJson); Connection connection = DriverManager.getConnection("jdbc:calcite:", info); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select * from \"TEST\".\"test1\""); final StringBuilder buf = new StringBuilder(); while (resultSet.next()) { ResultSetMetaData metaData = resultSet.getMetaData(); System.out.println("metaData="+metaData.getColumnCount()); System.out.println("metaData1="+metaData.getColumnName(1)); System.out.println("metaData2="+metaData.getColumnName(2)); // for (int i = 1; i <= metaData.getColumnCount(); i++) { buf.append(i > 1 ? "; " : "") .append(metaData.getColumnLabel(i)).append("=").append(resultSet.getObject(i)); } LOGGER.info("Result entry: " + buf.toString()); buf.setLength(0); } resultSet.close(); statement.close(); connection.close(); } } ``` **Gemfire :** ``` start locator --name=locator1 --port=10334 --initial-heap=256m --max-heap=256m --log-level=DEBUG start server --name=server1 --log-level=DEBUG create region --name=test1 --type=PARTITION --redundant-copies=1 --total- num-buckets=1 query --query='select count(*) from /test1' stop server --name=server1 stop locator --name=locator1 ``` Upvotes: 1 [selected_answer]
2018/03/21
571
2,138
<issue_start>username_0: I'm still learning how to code using java, and i run into problem that i can't solve myself. compiler says : ``` Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextInt(Scanner.java:2117) at java.util.Scanner.nextInt(Scanner.java:2076) at GetInputData.main(GetInputData.java:10) ``` Here is the code ``` import java.util.Scanner; public class GetInputData { public static void main(String[] args) { Scanner in = new Scanner(System.in); int tag; System.out.println("Enter an integer: "); tag = in.nextInt(); System.out.println("Input Integer is: "+tag); } } ``` have been looking around for solution but it looks like lot of people had this kind of problem, so if any of you guys had other workaround can you please share to me, i just want a simple program that read from whatever we input, thanks.<issue_comment>username_1: I ran the code and it works as intended when working from the command line. However, I tried creating an empty file, and piping that in, and I was able to reproduce the error. So the problem lies in whatever your input mechanism is. Whether it's the wrong file or empty file or whatever, that's where you need to look to find the problem. Upvotes: 0 <issue_comment>username_2: Here's the method `throwFor` from `Scanner` class in JDK that shows that it will throw `NoSuchElementException` if either (a) the input resource is closed or (b) you are entering an input that the buffer cannot hold. From your code it looks like you are not closing the scanner (which you should at the very end). So the only possibility is that you are entering an invalid input. By the way, this is not a compiler error, but a run time exception. ``` 859 private void throwFor() { 860 skipped = false; 861 if ((sourceClosed) && (position == buf.limit())) 862 throw new NoSuchElementException(); 863 else 864 throw new InputMismatchException(); 865 } ``` Upvotes: 1
2018/03/21
2,573
9,875
<issue_start>username_0: I have a basic UWP app with an embedded WebView presenting a rather large HTML document (up to 500 letter-sized printed pages). I'd like to add support for printing that HTML document. Here is my approach: 1. To support pagination, I generate a second HTML document broken into "pages" by using a for each "page", up to 500 of these. 2. I load that "paginated" HTML into a second, hidden `WebView` on the XAML page that I resize to fit exactly one page based on the user selected page size. 3. I wait for the WebView to finish loading... 4. Now for each "page": 1. I set the WebView's `scrollY` to show only the current page using JavaScript: `window.scrollTo(0, -pageOffset)` 2. I then use `WebViewBrush` to capture a snapshot of the current page in the `WebView` 3. Repeat this for all remaining pages... **The problem:** I can generate the print preview of all 500 pages, but sometimes the preview is missing pages while other pages show up multiple times. I suspect this is because I use `WebViewBrush.Redraw()` to capture a snapshot of the scrolled WebView, but the documentation says `Redraw()` **happens asynchronously**. I may scroll past the current page before WebViewBrush gets a chance to redraw, hence accidentally capturing the next page. How can I make sure that WebViewBrush has captured the WebView so that I can scroll to the next page? My code to generate a single page: ``` private async Task MakePage(WebView webView, Size pageSize, double pageOffset) { // Scroll to next page: await webView.EvaluateJavaScriptSnippetAsync( $"window.scrollTo(0, {pageOffset})"); var brush = new WebViewBrush(); brush.Stretch = Stretch.Uniform; brush.SetSource(webView); brush.Redraw(); // XXX Need to wait for this, but there's no API // Add a delay hoping Redraw() finishes... I think here is the problem. await Task.Delay(150); var rectangle = new Rectangle() { Width = pageSize.Width, Height = pageSize.Height }; rectangle.Fill = brush; brush.Stretch = Stretch.UniformToFill; brush.AlignmentY = AlignmentY.Top; return rectangle; } ``` Note: If there's an alternative to using WebViewBrush to print 500 pages, I'm open for suggestions. I tried using a separate WebView for each page, but the app runs out of memory after 200 pages. **BOUNTY:** I started a bounty offering 100 points to anybody who can figure out how to print 500 pages.<issue_comment>username_1: According to the Important section of the [`WebViewBrush` remarks](https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.webviewbrush#remarks): > > A WebView control has an inherently asynchronous behavior that redraws the control when its content is completely loaded. But an associated WebViewBrush renders as soon as the XAML is parsed (which might be before the URI content is loaded by the WebView ). Alternatively, you can wait to call SetSource on the WebViewBrush until the source content is fully loaded (for example by calling SetSource in the handler for the WebView.LoadCompleted event. > > > So that you could calling `SetSource` method of `WebViewBrush` after [`WebView.LoadCompleted`](https://learn.microsoft.com/en-us/uwp/api/windows.ui.xaml.controls.webview.loadcompleted). Upvotes: 3 <issue_comment>username_2: What I understand from your question is that you have a single HTML document. That is very much large in terms of content that you can devide it into 500 pages. You need to print that whole HTML page. Here, I considers that there is no content or space or section in your HTML page which you do not want to print. I googled your problem and got something. I modified that code and ran it on my UWP app for giving you strong base. I am sure that this is not the exact solution you want as I do not know the page size you want to print and some other parametes but the following code is more than 90% useful to you. This code generates pages based on the Size you provide to the method. It will devide the whole webpage into no. of pages. It does not have any printng logic. I am sure you have enough capability (based on your reputation point :) ) to play with C# and this code. You can modify it as per you need. **XAML** ``` ``` **C#** ``` public MainPage() { this.InitializeComponent(); wv.LoadCompleted += Wv_LoadCompleted; } async private void Wv_LoadCompleted(object sender, NavigationEventArgs e) { var allPages = await GetWebPages(wv, new Windows.Foundation.Size(100d, 150d)); } async Task> GetWebPages(WebView webView, Windows.Foundation.Size pageSize) { // GETTING WIDTH FROM WEVIEW CONTENT var widthFromView = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" }); int contentWidth; if (!int.TryParse(widthFromView, out contentWidth)) throw new Exception(string.Format("failure/width:{0}", widthFromView)); webView.Width = contentWidth; // GETTING HEIGHT FROM WEBVIEW CONTENT var heightFromView = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" }); int contentHeight; if (!int.TryParse(heightFromView, out contentHeight)) throw new Exception(string.Format("failure/height:{0}", heightFromView)); webView.Height = contentHeight; // CALCULATING NO OF PAGES var scale = pageSize.Width / contentWidth; var scaledHeight = (contentHeight \* scale); var pageCount = (double)scaledHeight / pageSize.Height; pageCount = pageCount + ((pageCount > (int)pageCount) ? 1 : 0); // CREATE PAGES var pages = new List(); for (int i = 0; i < (int)pageCount; i++) { var translateY = -pageSize.Height \* i; var page = new Windows.UI.Xaml.Shapes.Rectangle { Height = pageSize.Height, Width = pageSize.Width, Margin = new Thickness(5), Tag = new TranslateTransform { Y = translateY }, }; page.Loaded += async (s, e) => { var rectangle = s as Windows.UI.Xaml.Shapes.Rectangle; var wvBrush = await GetWebViewBrush(webView); wvBrush.Stretch = Stretch.UniformToFill; wvBrush.AlignmentY = AlignmentY.Top; wvBrush.Transform = rectangle.Tag as TranslateTransform; rectangle.Fill = wvBrush; }; pages.Add(page); } return pages; } async Task GetWebViewBrush(WebView webView) { // ASSING ORIGINAL CONTENT WIDTH var originalWidth = webView.Width; var widthFromView = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollWidth.toString()" }); int contentWidth; if (!int.TryParse(widthFromView, out contentWidth)) throw new Exception(string.Format("failure/width:{0}", widthFromView)); webView.Width = contentWidth; // ASSINGING ORIGINAL CONTENT HEIGHT var originalHeight = webView.Height; var heightFromView = await webView.InvokeScriptAsync("eval", new[] { "document.body.scrollHeight.toString()" }); int contentHeight; if (!int.TryParse(heightFromView, out contentHeight)) throw new Exception(string.Format("failure/height:{0}", heightFromView)); webView.Height = contentHeight; // CREATING BRUSH var originalVisibilty = webView.Visibility; webView.Visibility = Windows.UI.Xaml.Visibility.Visible; var wvBrush = new WebViewBrush { SourceName = webView.Name, Stretch = Stretch.Uniform }; wvBrush.Redraw(); webView.Width = originalWidth; webView.Height = originalHeight; webView.Visibility = originalVisibilty; return wvBrush; } ``` Upvotes: 2 <issue_comment>username_3: **Revisited as promised. Original answer preserved at end.** Turned out to be *way* harder than I thought. Here's a totally different solution that avoids the problem entirely: <https://github.com/ArthurHub/HTML-Renderer/> This project is abandoned but is in good condition and remains relevant. There is a core renderer and a bunch of wrapper projects targeting various .NET platforms * WinForms * WPF * Mono * dotnet core UWP is not listed, but the core renderer is a pure C# solution with platform dependent stuff deliberately factored out and several fully worked PALs (platform adapter layers) to copy. I have used it to print from an MVC5 Web API providing in-browser network printing services to SPA clients. This library is blazingly fast and *much* smaller than MSHTML or EdgeHTML. It doesn't print, it renders. The samples render a bitmap, which the printing sample draws on the Graphics object provided by a WinForms PrintDocument.PrintPage event. This produces horrible up-sampling pixilation for which the (totally undocumented) solution is to render a Windows Metafile instead. There is still the question of pagination, but there is a PAL for PDF from which you can crib the approach. Famous last words: It *shouldn't* be hard to convert the WPF solution to UWP. If you're interested we *could* fork the repo and add the missing UWP PAL. The risk with doing so is being badgered for support - it's likely to be very useful to widget monkeys. For the preview aspect you would probably paginate and paint metafiles on the UI. --- My first thought is an ugly hack that ought to work: sleep the thread. The redraw is already happening on another thread, that's why you're in a race condition. If you guarantee the other thread more time your chances improve greatly. New problem: Thread.Sleep is not available in UWP because everything supports continuations except when it doesn't. Fortunately there are other ways to skin this cat. ``` wvBrush.Redraw(); // System.Threading.Tasks.Task.Delay(30).Wait() is more elegant but less portable than... using (var waitHandle = new System.Threading.ManualResetEventSlim(initialState: false)) waitHandle.Wait(TimeSpan.FromMilliseconds(30)); // exploit timeout ``` The next problem is that render time is unpredictable and a long sleep hurts performance, so you need a way to test for success. You say that failure produces an all white page. I will write a test for all-white and come back and rewrite the end of this answer when I get it working fast. Upvotes: 0
2018/03/21
245
772
<issue_start>username_0: How can I loop through element positions in Python using Selenium? I've tried this and it's not working: ``` for i in range(2,21): un = browser.find_element_by_xpath("(//div[@class='cname'])[i]").text print(un) ```<issue_comment>username_1: You have to format your string to put inside `i` value: ``` for i in range(2,21): un = browser.find_element_by_xpath("(//div[@class='cname'])[{0}]".format(i)).text print(un) ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: As per your code block an alternative would be to to use `find_elements_by_xpath` along with the index `[i]` as follows : ``` for i in range(2,21): un = browser.find_elements_by_xpath("//div[@class='cname']")[i].text print(un) ``` Upvotes: 0
2018/03/21
477
1,662
<issue_start>username_0: Suppose this is my JSON: ``` ds = [{ "name": "groupa", "subGroups": [{ "subGroup": 1, "people": [{ "firstname":"Tony", }, { "firstname":"Brian" } ] }] }, { "name": "groupb", "subGroups": [{ "subGroup": 1, "people": [{ "firstname":"Tony", }, { "firstname":"Brian" } ] }] } ] ``` I create a Dataframe by doing: ``` df = json_normalize(ds, record_path =['subGroups', 'people'], meta=['name']) ``` This gives me: ``` firstname name 0 Tony groupa 1 Brian groupa 2 Tony groupb 3 Brian groupb ``` However, I'd want to also include the subGroup column. I try: ``` df = json_normalize(ds, record_path =['subGroups', 'people'], meta=['name', 'subGroup']) ``` But that gives: ``` KeyError: 'subGroup' ``` Any ideas?<issue_comment>username_1: ``` json_normalize( ds, record_path=['subGroups', 'people'], meta=[ 'name', ['subGroups', 'subGroup'] # each meta field needs its own path ], errors='ignore' ) firstname name subGroups.subGroup 0 Tony groupa 1 1 Brian groupa 1 2 Tony groupb 1 3 Brian groupb 1 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Try this. ``` df = json_normalize(ds, record_path =['subGroups', 'people'],meta['name'['subGroups', 'subGroup']]) ``` Upvotes: 1
2018/03/21
340
1,244
<issue_start>username_0: I have a problem when I start to scroll to the EditText wiggets that are under keyboard. The problem is with not showing EditText in full, as you can see in the picture. [![enter image description here](https://i.stack.imgur.com/IndJP.png)](https://i.stack.imgur.com/IndJP.png) And all EditText wiggets below this E-mail have the same problem. This blue line hides one part of them. I have put all in the "ScrollView > LinearLayout" but nothing helped. I tried with `android:focusable="true"` and `android:windowSoftInputMode="adjustPan"`, also nothing. Any suggestions where to start search?<issue_comment>username_1: ``` json_normalize( ds, record_path=['subGroups', 'people'], meta=[ 'name', ['subGroups', 'subGroup'] # each meta field needs its own path ], errors='ignore' ) firstname name subGroups.subGroup 0 Tony groupa 1 1 Brian groupa 1 2 Tony groupb 1 3 Brian groupb 1 ``` Upvotes: 4 [selected_answer]<issue_comment>username_2: Try this. ``` df = json_normalize(ds, record_path =['subGroups', 'people'],meta['name'['subGroups', 'subGroup']]) ``` Upvotes: 1
2018/03/21
1,010
3,654
<issue_start>username_0: I have made repository to get records from database. Everything is working but I want to add `orderBy` method if there is variable in session: So far I have this: ``` php namespace App\Repositories; use App\Models\User; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Session; class UserRepository { protected $user; private $columns; public function __construct(User $user) { $this-user = $user; $this->columns = ['id', 'email', 'pwd', 'name', 'addr', 'addr_detail', 'addr_no', 'city', 'zip', 'state', 'phone', 'company_number', 'vat_id', 'tax_id', 'unique_string', 'active', 'banned', 'admin']; } public function getAll() { if (Session::has('sort')) { $sort = Session::get('sort'); if (isset($sort["users"]) && !empty($sort["users"])) $this->user->orderBy($sort['users']['column'], $sort['users']['type']); } return $this->user->select($this->columns)->withCount([ 'orders', 'orders as turnover' => function($query) { $query->select(DB::raw("SUM(price) as turnover")); }, 'orders as profit' => function($query) { $query->select(DB::raw("SUM(profit) as profit")); }, ])->get(); } } ``` The condition returns true but the records are not sorted by it. I even tried to put `$this->user->orderBy()` before return but it wasnt sorded at all. It appears it isnt used at all. Here is the query it runs: ``` "select `id`, `email`, `pwd`, `name`, `addr`, `addr_detail`, `addr_no`, `city`, `zip`, `state`, `phone`, `company_number`, `vat_id`, `tax_id`, `unique_string`, `active`, `banned`, `admin`, (select count(*) from `orders` where `users`.`id` = `orders`.`user_id`) as `orders_count`, (select SUM(price) as turnover from `orders` where `users`.`id` = `orders`.`user_id`) as `turnover`, (select SUM(profit) as profit from `orders` where `users`.`id` = `orders`.`user_id`) as `profit` from `users` " ``` Any help appreciated. Thanks<issue_comment>username_1: Try this.. it seems the orderBy is not reflecting to next query at the select.. ``` public function getAll() { $query = $this->user; if (Session::has('sort')) { $sort = Session::get('sort'); if (isset($sort["users"]) && !empty($sort["users"])) { $query = $query->orderBy($sort['users']['column'], $sort['users']['type']); } } return $query->select($this->columns)->withCount([ 'orders', 'orders as turnover' => function($query) { $query->select(DB::raw("SUM(price) as turnover")); }, 'orders as profit' => function($query) { $query->select(DB::raw("SUM(profit) as profit")); }, ])->get(); } ``` Upvotes: 0 <issue_comment>username_2: Try this.. ``` public function getAll() { $query = $this->user->select($this->columns)->withCount([ 'orders', 'orders as turnover' => function($query) { $query->select(DB::raw("SUM(price) as turnover")); }, 'orders as profit' => function($query) { $query->select(DB::raw("SUM(profit) as profit")); }, ]); if (Session::has('sort')) { $sort = Session::get('sort'); if (isset($sort["users"]) && !empty($sort["users"])) $query = $query->orderBy($sort['users']['column'], $sort['users']['type']); } return $query->get(); } ``` Be sure your `if (isset($sort["users"]) && !empty($sort["users"]))` let the execution in. Upvotes: 2 [selected_answer]
2018/03/21
673
2,290
<issue_start>username_0: I have a JSON object that contains two arrays. I want to convert those array elements into individual elements in the JSON object. I need this for an input into a D3 function in javascript. My object now: ``` { 0:{ start:"2016-01-01", values:[10,11,12], names:["a","b","c"] }, 1:{ start:"2016-01-02", values:[25,23,50], names:["a","b","c"] } } ``` Converted object: ``` { 0:{ start:"2016-01-01", a:10, b:11, c:12 }, 1:{ start:"2016-01-02", a:25, b:23, c:50 } } ``` The number of variables can vary. It won't always be 3. Any help appreciated, Thanks<issue_comment>username_1: Try this.. it seems the orderBy is not reflecting to next query at the select.. ``` public function getAll() { $query = $this->user; if (Session::has('sort')) { $sort = Session::get('sort'); if (isset($sort["users"]) && !empty($sort["users"])) { $query = $query->orderBy($sort['users']['column'], $sort['users']['type']); } } return $query->select($this->columns)->withCount([ 'orders', 'orders as turnover' => function($query) { $query->select(DB::raw("SUM(price) as turnover")); }, 'orders as profit' => function($query) { $query->select(DB::raw("SUM(profit) as profit")); }, ])->get(); } ``` Upvotes: 0 <issue_comment>username_2: Try this.. ``` public function getAll() { $query = $this->user->select($this->columns)->withCount([ 'orders', 'orders as turnover' => function($query) { $query->select(DB::raw("SUM(price) as turnover")); }, 'orders as profit' => function($query) { $query->select(DB::raw("SUM(profit) as profit")); }, ]); if (Session::has('sort')) { $sort = Session::get('sort'); if (isset($sort["users"]) && !empty($sort["users"])) $query = $query->orderBy($sort['users']['column'], $sort['users']['type']); } return $query->get(); } ``` Be sure your `if (isset($sort["users"]) && !empty($sort["users"]))` let the execution in. Upvotes: 2 [selected_answer]
2018/03/21
451
1,750
<issue_start>username_0: Retry mechanism in karate testing framework How to retry tests on failure in karate testing framework like Junit and TestNG. something like public class Retry implements IRetryAnalyzer { ``` private int count = 0; private static int maxTry = 3; @Override public boolean retry(ITestResult iTestResult) { if (!iTestResult.isSuccess()) { //Check if test not succeed if (count < maxTry) { //Check if maxtry count is reached count++; //Increase the maxTry count by 1 iTestResult.setStatus(ITestResult.FAILURE); //Mark test as failed return true; //Tells TestNG to re-run the test } else { iTestResult.setStatus(ITestResult.FAILURE); //If maxCount reached,test marked as failed } } else { iTestResult.setStatus(ITestResult.SUCCESS); //If test passes, TestNG marks it as passed } return false; } ``` }<issue_comment>username_1: As of now this is an open feature request: <https://github.com/intuit/karate/issues/247> But there are multiple work arounds. You may get some ideas if you look at the polling example: <https://github.com/intuit/karate/blob/master/karate-demo/src/test/java/demo/polling/polling.feature> Upvotes: 0 <issue_comment>username_2: It works for me on version **0.9.5.RC**5 . But, maybe this is one of the before-mentioned "workarounds"? All you do is something like this, which defaults to 3 attempts: ``` * retry until responseStatus == 404 When method get ``` [![enter image description here](https://i.stack.imgur.com/gpuYm.png)](https://i.stack.imgur.com/gpuYm.png) Upvotes: 1
2018/03/21
770
2,816
<issue_start>username_0: I have used templates to implement path policies. ``` #include #include template class FileReader { public: double getNextNumber(); private: PathPolicy pp; readNumbers() { std::ifstream myFile(pp.path); }; //And so on }; ``` I implemented: ``` [HEADER] struct DefaultPolicy { public: std::string path DefaultPolicy() } ; [IMPLEMENTATION] DefaultPolicy::DefaultPolicy() : path("."){} ``` So now I want to implement lots of different policies like: ``` [HEADER] struct UnitTestPolicy { public: std::string path UnitTestPolicy() } ; [IMPLEMENTATION] UnitTestPolicy::UnitTestPolicy() : path("unittests/resources"){} [HEADER] struct OperationalPathPolicy { public: std::string path OperationalPathPolicy() } ; [IMPLEMENTATION] OperationalPathPolicy::OperationalPathPolicy() : path("/sw/cm/resources"){} ``` I'm not sure how to switch my policies. These are compile-time choices, and I can select the target that I'm building for, but the only idea I have is fall back to macros to make a selection. If I do that, then I don't really need the template abstraction for the policy. How should I select a policy class at build time?<issue_comment>username_1: > > but the only idea I have is fall back to macros to make a selection > > > True. --- > > If I do that, then I don't really need the template abstraction for the policy. > > > False. The template abstraction helps you to minimize use of the preprocessor and isolate your policies cleanly. You can also force instantiation of your template class in a `.cpp` file to avoid compile-time overhead caused by templates, as you are aware of all the possible policy types. --- ``` // filereaderimpl.hpp namespace detail { template class FileReaderImpl { /\* ... \*/ }; } ``` ``` // filereader.hpp #include #ifdef SOME\_BUILD\_TIME\_CHOICE using FileReader = detail::FileHeaderImpl; #else using FileReader = detail::FileHeaderImpl; #endif ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: **EDIT: I misread the problem, the solution below will allow policy selection at runtime, you asked for selection at build time.** I think your problem would be better served by inheritance. So you have a base `PathPolicy` (you can call it whatever i.e. `DefaultPolicy`) class and then have other policies inherit from the `PathPolicy` class. So your `UnitTestPolicy` becomes ``` struct UnitTestPolicy : public PathPolicy { public: UnitTestPolicy() { path = "blah//blah"; } } ; ``` Then in your file reader, use the base class only to abstract other implementations of the policy class. That way your file reader doesn't care what the policy is; it's just going to read the file. Working example [here](http://cpp.sh/5lwe7). Upvotes: 0
2018/03/21
493
1,863
<issue_start>username_0: I would like to use a custom connection pool with MyBatis and the following questions have arisen: What connection pool implementation does MyBatis use? How can I change the default connection pool by HikariCP or BoneCP?<issue_comment>username_1: > > but the only idea I have is fall back to macros to make a selection > > > True. --- > > If I do that, then I don't really need the template abstraction for the policy. > > > False. The template abstraction helps you to minimize use of the preprocessor and isolate your policies cleanly. You can also force instantiation of your template class in a `.cpp` file to avoid compile-time overhead caused by templates, as you are aware of all the possible policy types. --- ``` // filereaderimpl.hpp namespace detail { template class FileReaderImpl { /\* ... \*/ }; } ``` ``` // filereader.hpp #include #ifdef SOME\_BUILD\_TIME\_CHOICE using FileReader = detail::FileHeaderImpl; #else using FileReader = detail::FileHeaderImpl; #endif ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: **EDIT: I misread the problem, the solution below will allow policy selection at runtime, you asked for selection at build time.** I think your problem would be better served by inheritance. So you have a base `PathPolicy` (you can call it whatever i.e. `DefaultPolicy`) class and then have other policies inherit from the `PathPolicy` class. So your `UnitTestPolicy` becomes ``` struct UnitTestPolicy : public PathPolicy { public: UnitTestPolicy() { path = "blah//blah"; } } ; ``` Then in your file reader, use the base class only to abstract other implementations of the policy class. That way your file reader doesn't care what the policy is; it's just going to read the file. Working example [here](http://cpp.sh/5lwe7). Upvotes: 0
2018/03/21
862
2,819
<issue_start>username_0: I am extracting a list from html of a web page in the format ``` lst = '["a","b","c"]' # (type ) ``` The data type of the above is **str** and I want it to convert to a python **list type** , somthing like this ``` lst = ["a","b","c"] #(type ) ``` I can obtain the above by ``` lst = lst[1:-1].replace('"','').split(',') ``` But as the actual value of a,b &c is quite long and complex(contains long html text), I can't be dependent on the above method. I also tried doing it with json module and using `json.loads(lst)` , that is giving the below exception ```none Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/json/\_\_init\_\_.py", line 339, in loads return \_default\_decoder.decode(s) File "/usr/local/lib/python2.7/json/decoder.py", line 364, in decode obj, end = self.raw\_decode(s, idx=\_w(s, 0).end()) File "/usr/local/lib/python2.7/json/decoder.py", line 382, in raw\_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded ``` Any way of converting to list in Python? Edit: The actual value of the list is: `['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable','reqlistitem.title','reqlistitem.contestnumber','reqlistitem.contestnumber','reqlistitem.description','reqlistitem.description','reqlistitem.primarylocation','reqlistitem.primarylocation','reqlistitem.otherlocations','reqlistitem.jobschedule','reqlistitem.jobschedule','reqlistitem.jobfield','reqlistitem.jobfield','reqlistitem.displayreferfriendaction','reqlistitem.no','reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable']`<issue_comment>username_1: i think you are looking for `literal_eval`: ``` import ast string = '["a","b","c"]' print ast.literal_eval(string) # ['a', 'b', 'c'] ``` Upvotes: 3 [selected_answer]<issue_comment>username_2: The problem in your sample string is the single quotes. The JSON standard requires double quotes. If you change the single quotes to double quotes, it will work. An easy way is to use `str.replace()`: ``` import json s = "['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no']" json.loads(s.replace("'", '"')) #[u'reqlistitem.no', u'reqlistitem.applyonlinejobdesc', u'reqlistitem.no'] ``` Upvotes: 1
2018/03/21
473
2,072
<issue_start>username_0: I'm currently working on a new ReactJS application. In all the previous applications I've built I used Express for the server side rendering. I used Express because routing in production mode wouldn't work if I didn't. So I've recently discovered that it's posible to just always redirect my React app to my index.html file and let the React routing just do it's work. This also works when I deploy my application to production. I know Express can be usefull for SEO porposes but other than that I have no idea why I would need to use it. So am I just missing something? Or is it just fine to don't use Express with my React application if I don't need any SEO.<issue_comment>username_1: when deploying react application it is just usually an html and a JS file. So you need some kind of server to host it. Luckily there are services out there that offers that like S3, Github etc. You're using Express because it can host the html and js files. So technically you don't need specifically express but you need some server that will host your files. Upvotes: 0 <issue_comment>username_2: React configured as a Single Page App, renders the express routing all but unnecessary. The standard transition from a web server rendered app to a single page app is to change the server into a REST Web API and any server side data needed from the React App is obtained through AJAX calls. So in most cases you don't **need** Express when you are using React to handle your routing except for in less common cases when you might want to use express as a reverse proxy or something. Upvotes: 3 <issue_comment>username_3: If you want to do [server-side rendering](https://reactjs.org/docs/react-dom-server.html), you'll need a node server (typically but doesn't have to be `express`) to render your React components. This could not only help with SEO but also allow your page to appear to load faster (you wouldn't have to wait for the JS to download and run before the user sees the HTML). If you don't care about the benefits, don't use SSR. Upvotes: 2
2018/03/21
376
1,620
<issue_start>username_0: I am using Angular. I currently am using ng-repeat to display my data from a rest endpoint. I want to have the name field not be the full name but rather - First Name - Last Initial. Example: <NAME> -> <NAME>.<issue_comment>username_1: when deploying react application it is just usually an html and a JS file. So you need some kind of server to host it. Luckily there are services out there that offers that like S3, Github etc. You're using Express because it can host the html and js files. So technically you don't need specifically express but you need some server that will host your files. Upvotes: 0 <issue_comment>username_2: React configured as a Single Page App, renders the express routing all but unnecessary. The standard transition from a web server rendered app to a single page app is to change the server into a REST Web API and any server side data needed from the React App is obtained through AJAX calls. So in most cases you don't **need** Express when you are using React to handle your routing except for in less common cases when you might want to use express as a reverse proxy or something. Upvotes: 3 <issue_comment>username_3: If you want to do [server-side rendering](https://reactjs.org/docs/react-dom-server.html), you'll need a node server (typically but doesn't have to be `express`) to render your React components. This could not only help with SEO but also allow your page to appear to load faster (you wouldn't have to wait for the JS to download and run before the user sees the HTML). If you don't care about the benefits, don't use SSR. Upvotes: 2
2018/03/21
363
1,530
<issue_start>username_0: Question... why does this code only produce a message box "Down"? I'm not getting the Up. If I block down code, the up works. ``` using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Mouse { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_MouseUp(object sender, MouseEventArgs e) { MessageBox.Show("Up"); } private void Form1_MouseDown(object sender, MouseEventArgs e) { MessageBox.Show("Down"); } } } ```<issue_comment>username_1: Because you are showing a `MessageBox` Whenever a mouse down event happened a `MessageBox` will popup. The `MessageBox` Will be in foreground and the up event will be on the `MessageBox` instead of the form. Thus the up event in the form doesn't fire Just do a `Console.WriteLine` instead of `MessageBox` and it should work as expected Upvotes: 3 [selected_answer]<issue_comment>username_2: They will both fire if you remove the message box call. this is interferring with the mouse events because your loosing focus on the form. Instead of using message box try using... ``` Console.WriteLine("MouseUp"); ``` This will display in the ouput window and not interfere with the events Upvotes: 0
2018/03/21
809
2,855
<issue_start>username_0: I'm using Python to automate some reporting, but I am stuck trying to connect to an SSAS cube. I am on Windows 7 using Anaconda 4.4, and I am unable to install any libraries beyond those included in Anaconda. I have used pyodbc+pandas to connect to SQL Server databases and extract data with SQL queries, and the goal now is to do something similar on an SSAS cube, using an MDX query to extract data, but I can't get a successful connection. This first connection string is very similar to the strings that I used to connect to the SQL Server databases, but it gives me an authentication error. I can access the cube no problem using SQL Server Management Studio so I know that my Windows credentials have access. ``` connection = pyodbc.connect('Trusted_Connection=yes',DRIVER='{SQL Server}',SERVER='Cube Server', database='Cube') query = "MDX query" report_df = pandas.read_sql(query, connection) Error: ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user '*****'. (18456) (SQLDriverConnect)") ``` When I tried to replicate the attempts at [Question1](https://stackoverflow.com/questions/24712994/connect-to-sql-server-analysis-service-from-python) and [Question2](https://stackoverflow.com/questions/38985729/connect-to-an-olap-cube-using-python-on-linux) I got a different error: ``` Error: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') ``` Any help/guidance would be greatly appreciated. My experience with SSAS cubes is minimal, so it is possible that I am on the completely wrong path for this task and that even if the connection issue gets solved, there will be another issue loading the data into pandas, etc.<issue_comment>username_1: SSAS doesn't support [ODBC clients](https://learn.microsoft.com/en-us/sql/analysis-services/instances/data-providers-used-for-analysis-services-connections) . It does provide HTTP access through IIS, which requires [a few configuration steps](https://learn.microsoft.com/en-us/sql/analysis-services/instances/configure-http-access-to-analysis-services-on-iis-8-0). Once configured, any client can issue XMLA queries over HTTP. The [xmla package](https://pypi.python.org/pypi/xmla/) can connect to various OLAP sources, including SSAS over HTTP Upvotes: 2 <issue_comment>username_2: Perhaps this solution will help you <https://stackoverflow.com/a/65434789/14872543> the idea is to use the construct on linced MSSQL Server ``` SELECT olap.* from OpenRowset ('"+ olap_conn_string+"',' " + mdx_string +"') "+ 'as olap' ``` Upvotes: 0 <issue_comment>username_3: The Pyadomd package might help you with your problem: [Pyadomd](https://github.com/S-C-O-U-T/Pyadomd) It is not tested on Windows 7, but I would expect it to work fine :-) Upvotes: 0
2018/03/21
710
1,913
<issue_start>username_0: I have two `DateTime` instances, `A` and `B`, where: ``` DateTime A = new DateTime(2018, 11, 4, 1, 00, 0).plusHours(1); DateTime B = new DateTime(2018, 11, 4, 2, 00, 0); println("A: "+ A +", "+ A.getChronology() +", ms "+ A.getMillis()); println("B: "+ B +", "+ B.getChronology() +", ms "+ B.getMillis()); println("A == B is "+ A.equals(B)); ``` produces: ``` A: 2018-11-04T01:00:00.000-05:00, ISOChronology[America/New_York], ms 1541311200000 B: 2018-11-04T02:00:00.000-05:00, ISOChronology[America/New_York], ms 1541314800000 A == B is false ``` How do I compare `A` and `B` to see if they are the same instance? Take a closer look at how `A` and `B` are instantiated. The point is that both `A` and `B` actually refer to the same moment in time, that is when the clock is set back from EDT to EST in NYC.<issue_comment>username_1: SSAS doesn't support [ODBC clients](https://learn.microsoft.com/en-us/sql/analysis-services/instances/data-providers-used-for-analysis-services-connections) . It does provide HTTP access through IIS, which requires [a few configuration steps](https://learn.microsoft.com/en-us/sql/analysis-services/instances/configure-http-access-to-analysis-services-on-iis-8-0). Once configured, any client can issue XMLA queries over HTTP. The [xmla package](https://pypi.python.org/pypi/xmla/) can connect to various OLAP sources, including SSAS over HTTP Upvotes: 2 <issue_comment>username_2: Perhaps this solution will help you <https://stackoverflow.com/a/65434789/14872543> the idea is to use the construct on linced MSSQL Server ``` SELECT olap.* from OpenRowset ('"+ olap_conn_string+"',' " + mdx_string +"') "+ 'as olap' ``` Upvotes: 0 <issue_comment>username_3: The Pyadomd package might help you with your problem: [Pyadomd](https://github.com/S-C-O-U-T/Pyadomd) It is not tested on Windows 7, but I would expect it to work fine :-) Upvotes: 0
2018/03/21
686
2,325
<issue_start>username_0: I have an Angular 5 project. I need to display images in the UI that are fetched from the back end (say for example I want to display users' avatars in the upper toolbar, like in the SO toolbar above). The back end is a REST server that serves images when invoked on some end-point. I cannot seem to GET the images from the back end. And I am sure that the back end works. I have try to do the following (based on this [article](http://brianflove.com/2017/11/02/angular-http-client-blob/)): Here is my service `image.service.ts` (boiler plate has been removed) ``` getImage(url: string): Observable { return this.httpClient.get(`${url}`, {responseType: 'blob'}) } ``` Here is my coponent `image.component.ts` ``` @Component({ selector: 'app-image', templateUrl: './image.component.html', styleUrls: ['./image.component.css'] }) export class ImageComponent implements OnInit { @ViewChild('myImage') image: ElementRef constructor(private imageService: ImageService) {} ngOnInit() { this.getMyImage('http://my-super-host:3000/images/super-hero.png') } getMyImage(url: string): void { this.imageService.getImage(url) .subscribe(response => this.image.nativeElement.src = window.URL.createObjectURL(response)) } } ``` And eventually, here is my `image.component.html` ``` ![]() ``` In the browser's console, there is an error message saying that ``` ERROR TypeError: _this.image is undefined ``` This solution doesn't work. What am I missing here?<issue_comment>username_1: Adding a simple ``` ![]({{url}}) ``` did the trick. From then, you may add `*ngIf`, `class`, `alt`... as needed. Upvotes: 2 [selected_answer]<issue_comment>username_2: Another slightly different solution by someone else is discussed at: [<https://medium.com/techinpieces/blobs-with-http-post-aand-angular-5-a-short-story-993084811af4][1]> Based on that, I wrote code that works with Angular 7, some of which is below. See the link above for more info. ``` getBlob_withQueryParams(imageUrl: string, params: HttpParams): Rxjs.Observable { const headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' }); return this.\_http.get(imageUrl, {headers: headers, params: params, responseType: 'blob' as 'json' }); } ``` Upvotes: 0
2018/03/21
1,231
4,017
<issue_start>username_0: The following is the C code: ``` char *ptr[100]; printf("%s\n",*ptr++); ``` My question is: we know that array name is not a variable (Ritchie's book "The C programming language" Page 99), so if we define ``` int *pa,a[5]; ``` This is legal: ``` pa = a; pa++; ``` while this is illegal: ``` a++; ``` Here `char *ptr[100]` defines a char pointer array, so `ptr` represents the initial address of the array. For the above code, if `*ptr++` means `*(ptr++)`, this is illegal because array name cannot be used as a variable, and also it's meaningless because `*(ptr++)` still gets an address as opposed to `%s`. However, if `*ptr++` means `(*ptr)++`, it also looks strange... Can anyone help to understand this? The above is my thinking process, my question is: how can `*ptr++` give us a string as the code `printf("%s\n",*ptr++);` says?<issue_comment>username_1: I believe this link should help you. [C/C++ int[] vs int\* (pointers vs. array notation). What is the difference?](https://stackoverflow.com/questions/11555997/c-c-int-vs-int-pointers-vs-array-notation-what-is-the-difference) The array notation has a bounds limit while the pointer notation does not. If you wanted to access the next in the array with array notation it would look something like a[n++] n being whatever the current index of the array you are at. Where as assigning ptr to a sets ptr to the first index of the array and you can increment a pointer. Upvotes: 0 <issue_comment>username_2: Postfix increment `++` has a higher precedence than dereference `*`. Thus, `*ptr++` is interpreted as `*(ptr++)`. And as you've correctly figured out, `ptr++` isn't allowed if `ptr` is an array (of anything, values or pointers). If `ptr` is a pointer, then `*ptr++` will indeed increment the pointer (so it will point to the next value *after* the operation), and this expression will return the *current* pointed-to value (before increment of the pointer). This expression is indeed sometimes used, e.g. for copying memory areas, e.g.: ``` while (...) { *dest++ = *src++; // Copy the current element, then increment both pointers } ``` --- `*ptr++` *doesn't necessarily give you a string* — it gives you a string if and only if `ptr` is pointing to a string. And in this case, it's not necessary to post-increment just to get the string — `*ptr` would be enough. `++` is done for another purpose. For example, it `ptr` is a pointer to an *"array" of strings* (i.e. a pointer to a pointer to a`char`, i.e. `char **ptr`), then you could print all the strings like this: ``` int i; for (i = 0; i < N; ++i) { printf("%s\n",*ptr++); // '++' "jumps" to the next string } ``` Upvotes: 2 [selected_answer]<issue_comment>username_3: `*ptr++` is parsed as `*(ptr++)` - apply the `++` operator to `ptr`, then dereference the result. As written, this results in a *constraint violation* - `ptr` is an *array* of pointers to `char`, and an expression of array type is a *non-modifiable lvalue*, and as such may not be the target of an assignment or the operand of the `++` and `--` operators. The line ``` printf("%s\n",*ptr++); ``` should (indeed, *must*) result in the compiler issuing a diagnostic on the order of "invalid lvalue in increment" or something along those lines. Upvotes: 0 <issue_comment>username_4: No. 1: ``` void main(void) { int i; char *ptr[3]={"how","are","you"}; for (i=0;i<3;i++) printf("%s\n",ptr[i]); } ``` This prints out correct answer. Good! No.2: ``` void main(void) { int i; char *ptr[3]; *ptr[0] = "how"; *ptr[1] = "are"; *ptr[2] = "you"; for (i=0;i<3;i++) printf("%s\n",ptr[i]); } ``` warning: assignment makes integer from pointer without a cast [enabled by default].....Why can't initialize like this? No.3: ``` void main(void) { int i; char *ptr[3]={"how","are","you"}; printf("%s\n",*ptr++); } ``` error: lvalue required as increment operand....Why can't we use `*ptr++`? Upvotes: 0
2018/03/21
1,937
5,927
<issue_start>username_0: I am trying to train an LSTM recurrent neural network, for sequence classification. My data has the following formart: ``` Input: [1,5,2,3,6,2, ...] -> Output: 1 Input: [2,10,4,6,12,4, ...] -> Output: 1 Input: [4,1,7,1,9,2, ...] -> Output: 2 Input: [1,3,5,9,10,20, ...] -> Output: 3 . . . ``` So basically I want to provide a sequence as an input and get an integer as an output. Each input sequence has length = 2000 float numbers, and I have around 1485 samples for training The output is just an integer from 1 to 10 This is what I tried to do: ``` # Get the training numpy 2D array for the input (1485X 2000). # Each element is an input sequence of length 2000 # eg: [ [1,2,3...], [4,5,6...], ... ] x_train = get_training_x() # Get the training numpy 2D array for the outputs (1485 X 1). # Each element is an integer output for the corresponding input from x_train # eg: [ 1, 2, 3, ...] y_train = get_training_y() # Create the model model = Sequential() model.add(LSTM(100, input_shape=(x_train.shape))) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) print(model.summary()) model.fit(x_train, y_train, nb_epoch=3, batch_size=64) ``` **I get the following error:** ``` Error when checking input: expected lstm_1_input to have 3 dimensions, but got array with shape (1485, 2000) ``` I tried using this instead: ``` model.add(LSTM(100, input_shape=(1485, 1, 2000))) ``` But got the another error this time: ``` ValueError: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4 ``` Can anyone explain what is my input shape? and what am I doing wrong? Thanks<issue_comment>username_1: try reshaping your training data to: ``` x_train=x_train.reshape(x_train.shape[0], 1, x_train.shape[1]) ``` Upvotes: 1 <issue_comment>username_2: `input_shape=(None, x_train.shape[1], 1)`, where `None` is the batch size, `x_train.shape[1]` is the length of each sequence of features, and `1` is each feature length. (Not sure if batch size is necessary for `Sequential` model). And then reshape your data into `x_train = x_train.reshape(-1, x_train.shape[1], 1)`. Upvotes: 1 <issue_comment>username_3: Given the format of your input and output, you can use parts of the approach taken by one of the official [Keras examples](https://github.com/keras-team/keras/blob/master/examples/imdb_lstm.py). More specifically, since you are not creating a binary classifier, but rather predicting an integer, you can use one-hot encoding to encode `y_train` using `to_categorical()`. ``` # Number of elements in each sample num_vals = x_train.shape[1] # Convert all samples in y_train to one-hot encoding y_train = to_categorical(y_train) # Get number of possible values for model inputs and outputs num_x_tokens = np.amax(x_train) + 1 num_y_tokens = y_train.shape[1] model = Sequential() model.add(Embedding(num_x_tokens, 100)) model.add(LSTM(100)) model.add(Dense(num_y_tokens, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=64, epochs=3) ``` The `num_x_tokens` in the code above would be the maximum size of the element in one of your input samples (e.g. if you have two samples `[1, 7, 2]` and `[3, 5, 4]` then `num_x_tokens` is `7`). If you use `numpy` you can find this with `np.amax(x_train)`. Similarly, `num_y_tokens` is the number of categories you have in `y_train`. After training, you can run predictions using the code below. Using `np.argmax` effectively reverses `to_categorical` in this configuration. ``` model_out = model.predict(x_test) model_out = np.argmax(model_out, axis=1) ``` You can import `to_categorical` using `from keras.utils import to_categorical`, `Embedding` using `from keras.layers import Embedding`, and numpy using `import numpy as np`. Also, you don't have to do `print(model.summary())`. `model.summary()` is enough to print out the summary. **EDIT** If it is the case that the input is of the form `[[0.12, 0.31, ...], [0.22, 0.95, ...], ...]` (say, generated with `x_train = np.random.rand(num_samples, num_vals)`) then you can use `x_train = np.reshape(x_train, (num_samples, num_vals, 1))` to change the shape of the array to input it into the LSTM layer. The code to train the model in that case would be: ``` num_samples = x_train.shape[0] num_vals = x_train.shape[1] # Number of elements in each sample # Reshape for what LSTM expects x_train = np.reshape(x_train, (num_samples, num_vals, 1)) y_train = to_categorical(y_train) # Get number of possible values for model outputs num_y_tokens = y_train.shape[1] model = Sequential() model.add(LSTM(100, input_shape=(num_vals, 1))) model.add(Dense(num_y_tokens, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=64, epochs=3) ``` The `num_vals` is the length of each sample array in `x_train`. `np.reshape(x_train, (num_samples, num_vals, 1))` changes each sample from `[0.12, 0.31, ...]` form to `[[0.12], [0.31], ...]` form, which is the shape that LSTM then takes (`input_shape=(num_vals, 1)`). The extra `1` seems strange in this case, but it is necessary to add an extra dimension to the input for the LSTM since it expects each sample to have at least two dimensions, typically called `(timesteps, data_dim)`, or in this case `(num_vals, 1)`. To see how else LSTMs are used in Keras you can refer to: [Keras Sequential model guide](https://keras.io/getting-started/sequential-model-guide/) (has several LSTM examples) [Keras examples](https://github.com/keras-team/keras/tree/master/examples) (look for `*.py` files with `lstm` in their name) Upvotes: 1 [selected_answer]
2018/03/21
729
1,910
<issue_start>username_0: There's a bug in my code that's supposed to find the largest value in a list of non-negative numbers and put that value in R5. The memory location of the beginning of the list is in R2, and the end of the list of numbers is signified by a negative value. That is, if R2=x4000, and the contents of memory are: x4000 =5, x4001=1, x4002=-1, then the value 5 should be placed in R5. But there's a bug that prevents this from happening. My professor said I only need to add a **single line** somewhere for it to work. Any help is appreciated! Here is my assembly code: ``` .ORIG x3000 SETUP LEA R2, DATA ; set R2 START AND R5,R5,#0 LOOP LDR R3,R2,#0 ADD R2,R2,#1 NOT R4,R5 ADD R4,R4,#1 ADD R4,R3,R4 BRn LOOP ADD R5,R3,#0 BRnzp LOOP ;loop QUIT HALT DATA .FILL #6 .FILL #8 .FILL #11 .FILL #2 .FILL #0 .FILL #5 .FILL #-4 .END ```<issue_comment>username_1: I don't know the ASSM you are programming in, following is PSEUSO code ASSM (the last time I wrote ASSM was in 1991): ``` BEGIN: MOV AX,R2 // Start of data MOV BX,-1 // Initial value START: PEEK AX,CX // Get 1st location to CX CMP CX,0 // Compare with zero JMP_LESS END // End of list reached CMP CX,BX JMP_GT ASSIGN // Do the assign INC AX // Next address JMP START: ASSIGN: MOV BX,CX // BX now has the bigger # INC AX // Next address JMP START END: # Do stuff with highest # # Do cleanup LIST: 8 11 5 -4 ``` Hopefully it will give you an idea where your problem is. Upvotes: 0 <issue_comment>username_2: ``` .ORIG x3000 SETUP LEA R2, DATA ; set R2 START AND R5,R5,#0 LOOP LDR R3,R2,#0 **BRn QUIT ;Ends the loop once the list has a negative number in it** ADD R2,R2,#1 NOT R4,R5 ADD R4,R4,#1 ADD R4,R3,R4 BRn LOOP ADD R5,R3,#0 BRnzp LOOP ;loop QUIT HALT DATA .FILL #6 .FILL #8 .FILL #11 .FILL #2 .FILL #0 .FILL #5 .FILL #-4 .END ``` Upvotes: 1
2018/03/21
277
1,017
<issue_start>username_0: So I want to make a dropdown using Bootstrap 4 for my Spring MVC Aplication. I'm also using Thymeleaf template engine. I 'imported' popper.js and jQuery in my html page.Also I have included Bootstraps's Css and Javascript to static direcotory as separate files in my project ``` ``` And it's still not working. Here the full code of my html page ```html Footer Add Note Sort Date Ascending Date Descending Done Not Done ```<issue_comment>username_1: You also need to include Bootstrap's CSS and Javascript files in order for it to work. ``` ``` Upvotes: 0 <issue_comment>username_2: For the drop-down to work, you must load the following 3 JavaScript files **and load them in that particular order** (first jQuery, then popper.js and then bootstrap.js): ``` ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Updated your snippet. ```html Add Note Sort Date Ascending Date Descending Done Not Done ``` Hope it will helps you Upvotes: 0
2018/03/21
269
959
<issue_start>username_0: I work on prestashop 1.7.2.5. In the order history, two links (detail & reorder) are available. When I click on reorder, the items are added directly to the cart, but I am redirected to the homepage of the site ! I would like to be redirected to the cart directly. How can I change that? an override ? Thanks for helping me ! Sofiane [screenshots](https://i.stack.imgur.com/Qf6Au.jpg)<issue_comment>username_1: You also need to include Bootstrap's CSS and Javascript files in order for it to work. ``` ``` Upvotes: 0 <issue_comment>username_2: For the drop-down to work, you must load the following 3 JavaScript files **and load them in that particular order** (first jQuery, then popper.js and then bootstrap.js): ``` ``` Upvotes: 3 [selected_answer]<issue_comment>username_3: Updated your snippet. ```html Add Note Sort Date Ascending Date Descending Done Not Done ``` Hope it will helps you Upvotes: 0
2018/03/21
848
3,210
<issue_start>username_0: I have a form with some inputs and one `file input`. Everything works well but there is a weird problem! > > Here is my validations code: > > > ``` $validator = \Validator::make($request->all(), [ 'name' => 'required|max:25|min:3', 'email' => 'required|email|max:35|min:5', 'phone' => 'required|max:15|min:7', 'file' => 'max:2000|mimes:jpeg,png,doc,docs,pdf', ]); ``` The problem is that I don't set `required` for `file` but I don't know why when I submit the form it said: **The file must be a file of type: jpeg, png, doc, docs, pdf** Actually I want to `file` be optional. I have tried `sometimes`: ``` 'file' => 'sometimes|max:2000|mimes:jpeg,png,doc,docs,pdf', ``` But it didn't work. Thanks for any suggestion. **Update:** > > my Ajax request: > > > ``` $(document).ready(function () { $("#submit").click(function (event) { event.preventDefault(); var formData = new FormData(); formData.append('name', $('#name').val()); formData.append('email', $('#email').val()); formData.append('phone', $('#phone').val()); formData.append('telegram', $('#telegram').val()); formData.append('contactWith', $('#contactWith').val()); formData.append('orderType', $('#orderType').val()); formData.append('price', $('#price').val()); formData.append('uiLevel', $('#uiLevel').val()); formData.append('codingType', $('#codingType').val()); formData.append('maxTime', $('#maxTime').val()); formData.append('file', $('#file')[0].files[0]); formData.append('message', $('#message').val()); $.ajax({ type: "POST", url: "{{route('orders.store')}}", headers: { "X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content") }, data: formData, contentType: false, processData: false, success: function (msg) { }, }, "json") }) }); ``` > > And my file input: > > > ``` send file browse no file chosen ```<issue_comment>username_1: You can do it as follows ``` $validator = \Validator::make($request->all(), [ 'name' => 'required|max:25|min:3', 'email' => 'required|email|max:35|min:5', 'phone' => 'required|max:15|min:7', ]); if($request->file){ $validator = \Validator::make($request->all(), [ 'file' => 'max:2000|mimes:jpeg,png,doc,docs,pdf', ]); } ``` Upvotes: 0 <issue_comment>username_2: Use the `nullable` rule Docs: <https://laravel.com/docs/8.x/validation#a-note-on-optional-fields> Which gives you: ``` 'file' => 'nullable|max:2000|mimes:jpeg,png,doc,docs,pdf', ``` Upvotes: 1
2018/03/21
3,010
6,731
<issue_start>username_0: I have a ETHBTC.json file : ``` [ { "open": "0.06353900", "high": "0.06354800", "low": "0.06341700", "close": "0.06347300", "volume": "335.48500000", "timestamp": 1521640800000 }, { "open": "0.06347300", "high": "0.06365400", "low": "0.06344000", "close": "0.06357500", "volume": "461.02800000", "timestamp": 1521641100000 }, { "open": "0.06349500", "high": "0.06360400", "low": "0.06341400", "close": "0.06352300", "volume": "495.50600000", "timestamp": 1521641400000 } ] ``` I'm trying to loop through the data and save all of the 'low' values to an array ``` const fs = require('fs'); var data = fs.readFileSync('charts/ETHBTC.json'); var CurrentPair = JSON.parse(data); var lowTotal = []; for(item in CurrentPair){ lowTotal[item] = item.low; console.log(lowTotal[item]); //put this just to check if working. } ``` the console log is giving me undefined values. Any help would be great, thanks<issue_comment>username_1: The operator `in` returns the properties of an object, in your case is returning the indexes of that array. ```js var array = [{ "open": "0.06353900", "high": "0.06354800", "low": "0.06341700", "close": "0.06347300", "volume": "335.48500000", "timestamp": 1521640800000},{ "open": "0.06347300", "high": "0.06365400", "low": "0.06344000", "close": "0.06357500", "volume": "461.02800000", "timestamp": 1521641100000},{ "open": "0.06349500", "high": "0.06360400", "low": "0.06341400", "close": "0.06352300", "volume": "495.50600000", "timestamp": 1521641400000}]; var lowTotal = []; for(item in array){ lowTotal.push(array[item].low); } console.log(lowTotal); ``` Probably, what you want to use is a `for-of-loop` This kind of `for-loop` loops over the array and for each iteration returns a specific element/object. ```js var array = [{ "open": "0.06353900", "high": "0.06354800", "low": "0.06341700", "close": "0.06347300", "volume": "335.48500000", "timestamp": 1521640800000},{ "open": "0.06347300", "high": "0.06365400", "low": "0.06344000", "close": "0.06357500", "volume": "461.02800000", "timestamp": 1521641100000},{ "open": "0.06349500", "high": "0.06360400", "low": "0.06341400", "close": "0.06352300", "volume": "495.50600000", "timestamp": 1521641400000}]; var lowTotal = []; for(item of array){ lowTotal.push(item.low); } console.log(lowTotal); ``` You can use either `reduce` or a simple `forEach`. ```js var array = [{ "open": "0.06353900", "high": "0.06354800", "low": "0.06341700", "close": "0.06347300", "volume": "335.48500000", "timestamp": 1521640800000},{ "open": "0.06347300", "high": "0.06365400", "low": "0.06344000", "close": "0.06357500", "volume": "461.02800000", "timestamp": 1521641100000},{ "open": "0.06349500", "high": "0.06360400", "low": "0.06341400", "close": "0.06352300", "volume": "495.50600000", "timestamp": 1521641400000}]; var result = array.reduce((a, {low}) => [...a, low], []); console.log(result); ``` Upvotes: 2 <issue_comment>username_2: `x in y` loops over the **property names** of the object. You are trying to treat `x` as the *values* of the properties, not the names. For that you need `x of y`. ``` for(item of CurrentPair){ lowTotal[item] = item.low; console.log(lowTotal[item]); //put this just to check if working. } ``` --- It would be more idiomatic to use `map` though. ``` var lowTotal = CurrentPair.map(item => item.low); console.log(lowTotal); ``` --- Aside: Convention, in JavaScript, reserves variable names starting with a capital letter for constructor functions. Don't use the name `CurrentPair` for a plain old array. Upvotes: 1 <issue_comment>username_3: `for ... in` loops are not supported by arrays in JavaScript. What you want is ``` for (const item of CurrentPair) { ... } ``` or ``` for (let i = 0; i < CurrentPair.length; i++) { const item = CurrentPair[i]; } ``` or ``` CurrentPair.forEach(item => { ... }); ``` Upvotes: 0 <issue_comment>username_4: You did it nearly right. But in a `for ... in` loop, you will receive the property `name` or the `index` inside the object. So you need to use `CurrentPair` to get the information you want. ```js var data = '[{"open": "0.06353900","high": "0.06354800","low": "0.06341700","close": "0.06347300","volume": "335.48500000","timestamp": 1521640800000},{"open": "0.06347300","high": "0.06365400","low": "0.06344000","close": "0.06357500","volume": "461.02800000","timestamp": 1521641100000},{"open": "0.06349500","high": "0.06360400","low": "0.06341400","close": "0.06352300","volume": "495.50600000","timestamp": 1521641400000}]'; var CurrentPair = JSON.parse(data); var lowTotal = []; for (var item in CurrentPair) { lowTotal.push(CurrentPair[item].low); } console.log(lowTotal); ``` Because `CurrentPair` is an `array`, you could simply use `forEach` too: ```js var data = '[{"open": "0.06353900","high": "0.06354800","low": "0.06341700","close": "0.06347300","volume": "335.48500000","timestamp": 1521640800000},{"open": "0.06347300","high": "0.06365400","low": "0.06344000","close": "0.06357500","volume": "461.02800000","timestamp": 1521641100000},{"open": "0.06349500","high": "0.06360400","low": "0.06341400","close": "0.06352300","volume": "495.50600000","timestamp": 1521641400000}]'; var CurrentPair = JSON.parse(data); var lowTotal = []; CurrentPair.forEach(function(item) { lowTotal.push(item.low); }); console.log(lowTotal); ``` Upvotes: 0 <issue_comment>username_5: `item` is the array index, not the array value. You use it correctly when using it in `lowTotal[item]`, but not when you try to read the `low` property. It should be: ``` for (item in CurrentPair) { lowTotal[item] = CurrentPair[item].low; } ``` However, see [Why is using "for...in" with array iteration a bad idea?](https://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea?lq=1) Upvotes: 0 <issue_comment>username_6: ``` //I don't know what u are exactly trying to do. This may help //push all low values in an array const lowTotal =CurrentPair.map((pair)=>pair.low); or //push all low values as an array of object const lowTotal =CurrentPair.map((pair)=> {return {low:pair.low}}); //if you want to sum all low values then follow this approach const lowTotal =CurrentPair.map((pair)=>pair.low).reduce((pre,nex)=>Number(pre)+Number(nex)); or const lowTotal=CurrentPair.map(pair=>{return{low:pair.low}}).reduce((pre,nex)=> {return {low:Number(pre.low)+ Number(nex.low)}}) ``` Upvotes: 0
2018/03/21
856
2,892
<issue_start>username_0: I think I have exhausted the entire internet looking for an example / answer to my query regarding implementing a h2o mojo model to predict within RShiny. We have created a bunch of models, and wish to predict scores in a RShiny front end where users enter values. However, with the following code to implement the prediction we get an error of > > Warning: Error in checkForRemoteErrors: 6 nodes produced errors; first > error: No method asJSON S3 class: H2OFrame > > > ``` dataInput <- dfName dataInput <- toJSON(dataInput) rawPred <- as.data.frame(h2o.predict_json(model= "folder/mojo_model.zip", json = dataInput, genmodelpath = "folder/h2o-genmodel.jar")) ``` Can anyone help with some pointers? Thanks, Siobhan<issue_comment>username_1: This is not a Shiny issue. The error indicates that you're trying to use `toJSON()` on an H2OFrame (instead of an R data.frame), which will not work because the **jsonlite** library does not support that. Instead you can convert the H2OFrame to a data.frame using: ``` dataInput <- toJSON(as.data.frame(dataInput)) ``` I can't guarantee that `toJSON()` will generate the correct input for `h2o.predict_json()` since I have not tried that, so you will have to try it out yourself. Note that the only way this may work is if this is a 1-row data.frame because the `h2o.predict_json()` function expects a single row of data, encoded as JSON. If you're trying to score multiple records, you'd have to loop over the rows. If for some reason `toJSON()` doesn't give you the right format, then you can use a function I wrote in this post [here](https://stackoverflow.com/a/47784930/5451344) to create the JSON string from a data.frame manually. There is a [ticket open](https://0xdata.atlassian.net/browse/PUBDEV-5424) to create a better version of `h2o.predict_json()` that will support making predictions from a MOJO on data frames (with multiple rows) without having to convert to JSON first. This will make it so you can avoid dealing with JSON altogether. An alternative is to use a [H2O binary model](http://docs.h2o.ai/h2o/latest-stable/h2o-docs/save-and-load-model.html) instead of a MOJO, along with the standard `predict()` function. The only requirement here is that the model must be loaded into H2O cluster memory. Upvotes: 3 [selected_answer]<issue_comment>username_2: The following works now using the json formatting from first two lines and the single quote around var with spaces. ``` df<- data.frameV1=1,V2=1,CMPNY_EL_IND=1,UW_REGION_NAME = "'LONDON & SE'" ) dfstr <- sapply(1:ncol(df), function(i) paste(paste0('\"', names(df)[i], '\"'), df[1,i], sep = ':')) json <- paste0('{', paste0(dfstr, collapse = ','), '}') dataPredict <- as.data.frame(h2o.predict_json(model = "D:\\GBM_model_0_CMP.zip", json = json, genmodelpath = "D:\\h2o-genmodel.jar", labels = TRUE)) ``` Upvotes: 0
2018/03/21
975
2,974
<issue_start>username_0: I want to replace all occurences of the character . in all strings in a solution These strings look like this: ``` string sentence = "Hello world. Good bye world"; ``` And I want them all to look like this: ``` string sentence = "Hello world_ Good bye world"; ``` I want to do it with a regular Expression. I tried with similar approaches as the described here: [Regular expression to extract text between square brackets](https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets) and I read the documentation here <https://learn.microsoft.com/en-us/visualstudio/ide/using-regular-expressions-in-visual-studio> but I can't figure out how I can continue. Edit: I am using Visual Studio 2017<issue_comment>username_1: A simple expression like: ``` \. ``` Should do the trick. Try using this: ``` String sentence = "Hello world. Good bye world"; sentence.replaceAll(\\.\g,"_"); ``` Edit: Added global flag to regex. Upvotes: -1 <issue_comment>username_2: Visual Studio 2015 Edit/Find and Replace. You will probably find further constraints but should get you started. In find what: ``` (string\s[^\s]+\s+=\s+"[^\.]+)(\.)(\s*[^"]+") ``` In replace with: ``` $1_$3 ``` Upvotes: 0 <issue_comment>username_3: You could do something like the following: ``` (?<=(? ``` ...which basically looks for any period preceded by zero or more of any character not a quote or a quote preceded by a backslash, and then preceded by a quote that does not have a leading backslash. That same period is followed by zero or more of any character not a quote or a quote preceded by a backslash, and then followed by a quote not preceded by a backslash. Keep in mind that this is not foolproof--it does not handle verbatim strings (i.e. @""). You could probably tweak it to accommodate such. Also, the replacement is just the character you want to change to (i.e. underscore). Upvotes: 0 <issue_comment>username_4: ``` (?<=(?<="|[\.](?<=".*))[^\.]*?)(\.)(?=.*") ``` It seems that this pattern works in .NET regex because the engine support varable length lookbehind. [Demo](http://regexstorm.net/tester?p=%28%3F%3C%3D%28%3F%3C%3D%22%7C%5B%5C.%5D%28%3F%3C%3D%22.*%29%29%5B%5E%5C.%5D*%3F%29%28%5C.%29%28%3F%3D.*%22%29&i=..string%20.sentence.%20%3D%20.%22.Hell.o%20world..%20Good.%20bye.%20world.%22.%3B.%20&r=_%0D%0A%0D%0A) (click [table] and [context] tab to check replace result ) [Test string] ``` ..string .sentence. = .".Hell.o world.. Good. bye. world.".;. ``` replace captured character with "\_" ``` ..string .sentence. = ."_​Hell_​o world_​_​ Good_​ bye_​ world_​".;. ``` * (\.) : capturing target.(literal period(.)) * (?=.\*") : quote existence after the period being captured. * (?<=(?<="|[\.](?<=".\*))[^\.]\*?) : preceding quote existence and possibly existence of a period with any non-dot characters preceded by a quote before the period being captured Upvotes: 2 [selected_answer]
2018/03/21
857
2,502
<issue_start>username_0: ``` Console.WriteLine("Unlike my deceased predecessor, A.I./Ai, I do not mind not being human. I am content with what I have."); Console.ReadKey(); bool AI = false; if (AI = true) ``` I want the user to type "AI" and have it set the bool to true if they do.<issue_comment>username_1: A simple expression like: ``` \. ``` Should do the trick. Try using this: ``` String sentence = "Hello world. Good bye world"; sentence.replaceAll(\\.\g,"_"); ``` Edit: Added global flag to regex. Upvotes: -1 <issue_comment>username_2: Visual Studio 2015 Edit/Find and Replace. You will probably find further constraints but should get you started. In find what: ``` (string\s[^\s]+\s+=\s+"[^\.]+)(\.)(\s*[^"]+") ``` In replace with: ``` $1_$3 ``` Upvotes: 0 <issue_comment>username_3: You could do something like the following: ``` (?<=(? ``` ...which basically looks for any period preceded by zero or more of any character not a quote or a quote preceded by a backslash, and then preceded by a quote that does not have a leading backslash. That same period is followed by zero or more of any character not a quote or a quote preceded by a backslash, and then followed by a quote not preceded by a backslash. Keep in mind that this is not foolproof--it does not handle verbatim strings (i.e. @""). You could probably tweak it to accommodate such. Also, the replacement is just the character you want to change to (i.e. underscore). Upvotes: 0 <issue_comment>username_4: ``` (?<=(?<="|[\.](?<=".*))[^\.]*?)(\.)(?=.*") ``` It seems that this pattern works in .NET regex because the engine support varable length lookbehind. [Demo](http://regexstorm.net/tester?p=%28%3F%3C%3D%28%3F%3C%3D%22%7C%5B%5C.%5D%28%3F%3C%3D%22.*%29%29%5B%5E%5C.%5D*%3F%29%28%5C.%29%28%3F%3D.*%22%29&i=..string%20.sentence.%20%3D%20.%22.Hell.o%20world..%20Good.%20bye.%20world.%22.%3B.%20&r=_%0D%0A%0D%0A) (click [table] and [context] tab to check replace result ) [Test string] ``` ..string .sentence. = .".Hell.o world.. Good. bye. world.".;. ``` replace captured character with "\_" ``` ..string .sentence. = ."_​Hell_​o world_​_​ Good_​ bye_​ world_​".;. ``` * (\.) : capturing target.(literal period(.)) * (?=.\*") : quote existence after the period being captured. * (?<=(?<="|[\.](?<=".\*))[^\.]\*?) : preceding quote existence and possibly existence of a period with any non-dot characters preceded by a quote before the period being captured Upvotes: 2 [selected_answer]
2018/03/21
1,172
3,862
<issue_start>username_0: I am stuck with a simple problem of getting text from editText. ``` fab1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder placeLLDialog= new AlertDialog.Builder(PlacesActivity.this); LayoutInflater inflater = getLayoutInflater(); final View view = inflater.inflate(R.layout.place_add_dialog, null); placeLLDialog.setView(R.layout.place_add_dialog); final EditText place = view.findViewById(R.id.placeName); final EditText lati = view.findViewById(R.id.placeLati); final EditText longi = view.findViewById(R.id.placeLongi); placeLLDialog.setTitle("Add Place with Latitude and Longitude") .setPositiveButton("Add", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Log.e(TAG, "Helloooo" + place.getText().toString()); if(!place.getText().toString().equals("") && !lati.getText().toString().equals("") && !longi.getText().toString().equals("")) { Log.e(TAG, "Hello" + place.getText().toString()); final Places places = new Places(place.getText().toString(), lati.getText().toString(), longi.getText().toString()); mPlacesViewModel.insert(places); } closeFABMenu(); } }) .setNegativeButton("Cancel", null) .show(); } ``` When I am doing this, I am not getting the value of place, lati and longi, i.e. "place.getText().toString()" is empty. Can anybody kindly help me with this strange problem?<issue_comment>username_1: A simple expression like: ``` \. ``` Should do the trick. Try using this: ``` String sentence = "Hello world. Good bye world"; sentence.replaceAll(\\.\g,"_"); ``` Edit: Added global flag to regex. Upvotes: -1 <issue_comment>username_2: Visual Studio 2015 Edit/Find and Replace. You will probably find further constraints but should get you started. In find what: ``` (string\s[^\s]+\s+=\s+"[^\.]+)(\.)(\s*[^"]+") ``` In replace with: ``` $1_$3 ``` Upvotes: 0 <issue_comment>username_3: You could do something like the following: ``` (?<=(? ``` ...which basically looks for any period preceded by zero or more of any character not a quote or a quote preceded by a backslash, and then preceded by a quote that does not have a leading backslash. That same period is followed by zero or more of any character not a quote or a quote preceded by a backslash, and then followed by a quote not preceded by a backslash. Keep in mind that this is not foolproof--it does not handle verbatim strings (i.e. @""). You could probably tweak it to accommodate such. Also, the replacement is just the character you want to change to (i.e. underscore). Upvotes: 0 <issue_comment>username_4: ``` (?<=(?<="|[\.](?<=".*))[^\.]*?)(\.)(?=.*") ``` It seems that this pattern works in .NET regex because the engine support varable length lookbehind. [Demo](http://regexstorm.net/tester?p=%28%3F%3C%3D%28%3F%3C%3D%22%7C%5B%5C.%5D%28%3F%3C%3D%22.*%29%29%5B%5E%5C.%5D*%3F%29%28%5C.%29%28%3F%3D.*%22%29&i=..string%20.sentence.%20%3D%20.%22.Hell.o%20world..%20Good.%20bye.%20world.%22.%3B.%20&r=_%0D%0A%0D%0A) (click [table] and [context] tab to check replace result ) [Test string] ``` ..string .sentence. = .".Hell.o world.. Good. bye. world.".;. ``` replace captured character with "\_" ``` ..string .sentence. = ."_​Hell_​o world_​_​ Good_​ bye_​ world_​".;. ``` * (\.) : capturing target.(literal period(.)) * (?=.\*") : quote existence after the period being captured. * (?<=(?<="|[\.](?<=".\*))[^\.]\*?) : preceding quote existence and possibly existence of a period with any non-dot characters preceded by a quote before the period being captured Upvotes: 2 [selected_answer]
2018/03/21
873
3,095
<issue_start>username_0: In the following example ``` template void foo() { const char\* name = typeid(T).name(); std::cout << name; } ``` the variable 'name' will be initialized by type 'T' name. It is very convinient if we need to print this template type name. But, if we have the alias: ``` using shortTypeName = std::smth::smth_else::smth_more; ``` in the result of the call ``` foo(); ``` will be printed 'std::smth::smth\_else::smth\_more'. And I need to print exactly the alias name, but not the type it is defined. Can somebody give an advice, how I can do this?<issue_comment>username_1: > > ... alias identificator ... > > > There's no such thing, at least not after compilation. It's just syntactic sugar and doesn't exist in any sense in the final executable. The *only* way to grab the local name of a type (as opposed to the implementation-defined and probably-mangled typeid name) is with a stringize/stringify macro. --- For future reference, this should eventually be possible when the [Reflection TS](https://en.cppreference.com/w/cpp/experimental/reflect) lands - but I don't yet know whether to expect that to look like `reflexpr(T).get_name()`, or `std::meta::name_of(^T)`, or something else again. Upvotes: 3 [selected_answer]<issue_comment>username_2: > > Can somebody give an advice, how I can do this? > > > The language does not support a mechanism to do this. What you have is simply a type alias. From <http://en.cppreference.com/w/cpp/language/type_alias>: > > A type alias declaration introduces a name which can be used as a synonym for the type denoted by type-id. It does not introduce a new type and it cannot change the meaning of an existing type name. > > > Upvotes: 1 <issue_comment>username_3: You can't. Because a type alias is transparent: It is just a synonym for a new type, not a new type. As an implementation detail it doesn't even get mangled in the type system because it's not a type. > > §7.1.3 The typedef specifier [dcl.typedef] > > > 1. [...] A name declared with the typedef specifier becomes a typedef-name . Within the scope of its declaration, a typedef-name is > syntactically equivalent to a keyword and names the type associated > with the identifier in the way described in Clause 8. A typedef-name > is thus a synonym for another type. **A typedef-name does not > introduce a new type** the way a class declaration (9.1) or enum > declaration does. > 2. A typedef-name can also be introduced by an alias-declaration . The identifier following the using keyword becomes a typedef-name and the > optional attribute-specifier-seq following the identifier appertains > to that typedef-name . It has the same semantics as if it were > introduced by the typedef specifier. In particular, **it does not > define a new type** and it shall not appear in the type-id . > > > `typeid(T).name();` is pretty much useless anyway. Until we have proper introspection in C++ you have to resort to hacks to get what you want (macros, intrusive techniques or external code generator tools). Upvotes: 1
2018/03/21
1,489
4,885
<issue_start>username_0: Let's say I have a table called **user** [![enter image description here](https://i.stack.imgur.com/kC50b.jpg)](https://i.stack.imgur.com/kC50b.jpg) I want to make a HTTP call roughly like this <http://my.awesome.server/dev_api/index.php/login/get_user.php?user=steven&password=<PASSWORD>> Which checks the database if there's a user 'steve' with the password '<PASSWORD>'. These are my codes. **controller** ``` php if(!defined("BASEPATH")) exit("No direct script access allowed"); class login extends CI_Controller { public function index() { $this-load->model("login_model"); $data["users"]=$this->login_model->get_user(); $this->load->view("login_view", $data); } } ``` **model** ``` class Login_model extends CI_Model { function get_user(){ // get username, like $_GET['user'] $user = $this->input->get('user'); // get the password and MD5-ed it, like md5($_GET['password']) $md5_pass = md5($this->get('password')); // the where condition $this->db->where(array('userName' => $user, 'password' => $<PASSWORD>pass)); // ok, now let's query the db $q = $this->db->get('user'); if($q->num_rows() > 0){ foreach ($q->result() as $row){ $data[] = $row; } } return $data; } } ?> ``` **view** ``` php if (!empty($users)){ foreach ($users as $u){ echo $u-userId .' '. $u->userName.' '.$u->password.' '; } } ?> ``` Then I opened this on browser: <http://my.awesome.server/dev_api/index.php/login/>. The result is [![enter image description here](https://i.stack.imgur.com/MjQ37.jpg)](https://i.stack.imgur.com/MjQ37.jpg) How to properly make a HTTP call, then?<issue_comment>username_1: The method in your model is name as `get_user()` while you call it as `login_model->get()` More over you should use POST instead of GET for username and password. Also use [bcrypt](https://en.wikipedia.org/wiki/Bcrypt) or another hashing algorithm instead of MD5 it's more secure. [DO NOT USE MD5](https://security.stackexchange.com/questions/19906/is-md5-considered-insecure) Upvotes: 2 <issue_comment>username_2: if you are passing data via url <http://my.awesome.server/dev_api/index.php/login/get_user.php?user=steven&password=<PASSWORD>> You can retrieve it via URI segment ``` $user= $this->uri->segment(3); $password= $this->uri->segment(4); ``` Sorce: <https://www.codeigniter.com/userguide3/libraries/uri.html> It is posible that this line `$md5_pass = md5($this->get('password'));` is setting the error if $this->get('password') is empty. Upvotes: 0 <issue_comment>username_3: You are trying to work against the framework you are using. CodeIgniter abstract working with GET parameters by proposing you to use *URL segments*. The URI scheme in CodeIgniter is as follow ([see docs](https://www.codeigniter.com/user_guide/general/routing.html)): `controller/method/params...` It is divided in **segments**: 1. the controller (mandatory) 2. the method (mandatory, but may be implied in case of `index`, see below) 3. the first param (optional) 4. the second param (optional) 5. ... and so on You want to use the method `index()` of the controller `Login`, it translates to > > <http://my.awesome.server/dev_api/index.php/login/index> > > > Also, with mode\_rewrite activated with htaccess, it could be simplified in > > <http://my.awesome.server/dev_api/login/index> > > > Now, `index()` is a special method as it is the one called by default in a controller. Hence the final URL would be: > > <http://my.awesome.server/dev_api/login> > > > Now, if you want to pass parameters to your function, CodeIgniter does this through subsequent segments. But you need to declare them in the controller method. ``` class login extends CI_Controller { public function index($user = null, $password = <PASSWORD>) { // Check for $user / $password emptiness // ... // Use $user / $password as needed $data["users"]=$this->login_model->get_user($user , $password); // use the results... } } ``` And now you could call with: > > <http://my.awesome.server/dev_api/login/index/steven/12345> > > > Notice that I've put `index` in the URL? It's because when passing parameters, the method is mandatory. --- That said, I will reiterate what other people have said: 1. Avoid passing login/password through GET. Prefer POST. 2. Use an encrypted connection (**HTTPS**) 3. Do NOT hash your password with md5 or even sha1. You need a strong algorithm. You also need to salt. Anyway, PHP got you covered with [`password_hash`](http://php.net/manual/en/function.password-hash.php). Don't reinvent the wheel. Good luck. Upvotes: 2 [selected_answer]
2018/03/21
384
1,240
<issue_start>username_0: In c# when adding two decimals the program will automatically get rid of the number 0 after the decimal places. For example adding 0.50 to 1.20 will produce the answer of 1.7 and this is annoying because i need to display this answer in terms of money. Is there a way to prevent this?<issue_comment>username_1: If you want to display your Decimal with two decimal places, please use : ``` myDecimal.ToString("N2"); ``` You may want to take a look at [Standard Numeric Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) for more information. Upvotes: 2 <issue_comment>username_2: ``` decimal d = 0.50m; decimal d1 = 1.20m; Console.Write(d+d1); ``` Please find this [Post](https://stackoverflow.com/questions/693372/what-is-the-best-data-type-to-use-for-money-in-c) Upvotes: 1 <issue_comment>username_3: I'm not sure about if you mean this, but you can try the toString() method in currency format this way: ``` double number = 1.2; string numberCurrency = number.ToString("C"); Console.WriteLine(numberCurrency); //this prints "1.20" ``` I recommend you to read this <https://msdn.microsoft.com/es-es/library/kfsatb94(v=vs.110).aspx> Upvotes: 0
2018/03/21
678
1,699
<issue_start>username_0: It's been two days that I'm struggling to solve this issue but without a solution. My data looks like: ``` ['DDD1', 'EEE1', 'AAA1', '1516988948227'] ['DDD2', 'EEE2', 'AAA2', '1516988948076'] ['DDD3', 'EEE3', 'AAA3', '1516990485713'] ['DDD4', 'EEE4', 'AAA4', '1516990487782'] ``` The output I need is: ``` ['DDD1', 'EEE1', 'AAA1', '1516988948227','1516988948076'] ['DDD2', 'EEE2', 'AAA2', '1516988948076','1516990485713'] ['DDD3', 'EEE3', 'AAA3', '1516990485713','1516990487782'] ['DDD4', 'EEE4', 'AAA4', '1516990487782', ' '] ``` In other words I need to add to each line the value of the number in the line that comes after. For the last line I return an empty space. If you have any Idea how I can solve the issue please help. Thank you!<issue_comment>username_1: If you want to display your Decimal with two decimal places, please use : ``` myDecimal.ToString("N2"); ``` You may want to take a look at [Standard Numeric Format Strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) for more information. Upvotes: 2 <issue_comment>username_2: ``` decimal d = 0.50m; decimal d1 = 1.20m; Console.Write(d+d1); ``` Please find this [Post](https://stackoverflow.com/questions/693372/what-is-the-best-data-type-to-use-for-money-in-c) Upvotes: 1 <issue_comment>username_3: I'm not sure about if you mean this, but you can try the toString() method in currency format this way: ``` double number = 1.2; string numberCurrency = number.ToString("C"); Console.WriteLine(numberCurrency); //this prints "1.20" ``` I recommend you to read this <https://msdn.microsoft.com/es-es/library/kfsatb94(v=vs.110).aspx> Upvotes: 0
2018/03/21
956
3,706
<issue_start>username_0: I am working on android application in which I am selecting Video files from gallery. Everything is fine but I want to show video files there which are below `5MB`, I don't want to show all Videos exceeding `5MB`. My code to show Video gallery and `onActivityResult` is given below: ``` public void takeVideoFromGallery(){ Intent intent = new Intent(); intent.setType("video/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Video"),REQUEST_TAKE_GALLERY_VIDEO); } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == this.RESULT_OK) { switch (requestCode) { case REQUEST_TAKE_GALLERY_VIDEO: if (resultCode == RESULT_OK) { showVideoGallery(data); Toast.makeText(this, "Video saved to:\n" +data.getData(), Toast.LENGTH_LONG).show(); } else if (resultCode == RESULT_CANCELED) { Toast.makeText(this, "Video recording cancelled.",Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "Failed to record video",Toast.LENGTH_LONG).show(); } break; } ```<issue_comment>username_1: There is nothing in `ACTION_GET_CONTENT` that allows you to provide arbitrary filters, such as a maximum size. You might see if there is [a file picker library](https://android-arsenal.com/tag/35) that meets your needs. Otherwise, you will need to create this UI yourself, querying the `MediaStore` and only showing the videos that meet your requirements. Upvotes: 2 <issue_comment>username_2: You can pick video via `ACTION_PICK`and add extra like `EXTRA_SIZE_LIMIT` Reference: <https://developer.android.com/reference/android/provider/MediaStore.html#EXTRA_SIZE_LIMIT> note: `EXTRA_SIZE_LIMIT` information does not work for many cases. ``` val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI) intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, Constant.MAX_VIDEO_SIZE_IN_MB) intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, MAX_VIDEO_RECORDING_TIME_IN_SEC) intent.type = "video/*" startActivityForResult(intent, PICK_VIDEO_GALLERY) ``` You can compare the file size via (note: better to compress video before using it if size is concerned) ``` val compressedVideoFile = File(mVideoOutPath) if (compressedVideoFile.length() > Constant.MAX_VIDEO_FILE_SIZE_IN_BYTES) { ToastUtils.shortToast(this@ChatActivity, getString(R.string.error_video_size)) else if (FileUtil.getVideoDuration(this@ChatActivity, compressedVideoFile) > Constant.MAX_VIDEO_FILE_DURATION_IN_MILLIS) { ToastUtils.shortToast(this@ChatActivity, getString(R.string.error_video_length)) } else { mVideoFilePath = mVideoOutPath uploadMedia(Constant.KEY_VIDEO) } ``` For retrieving video duration(in case you want to put check on duration as well): ``` fun getVideoDuration(context: Context, selectedVideoFile: File): Long { var videoDuration = java.lang.Long.MAX_VALUE try { val retriever = MediaMetadataRetriever() retriever.setDataSource(context, Uri.fromFile(selectedVideoFile)) val time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) videoDuration = java.lang.Long.parseLong(time) retriever.release() } catch (e: IllegalArgumentException) { e.printStackTrace() } catch (e: SecurityException) { e.printStackTrace() } return videoDuration } ``` Upvotes: 2
2018/03/21
816
2,097
<issue_start>username_0: I want to update my database (SQL Server Express) all the dates for specific ids. I am displaying the ids I want to. ``` SELECT TOP (1000) ID, Dates FROM tbl_table WHERE (id IN (29695, 29700, 29701, 29702, 29703, 29704, 29705, 29706, 29707, 29708, 29709, 29710, 29711, 29712, 29713, 29714, 29715)) ``` AND my dates in the database are like this: [![enter image description here](https://i.stack.imgur.com/wItux.png)](https://i.stack.imgur.com/wItux.png) Is there any way to update all the date columns with same date - 1 day? For example: if we have `2019-12-20`, update it to `2019-12-19`? For example if I want to do it in PHP, I would loop through this query and fetch all all dates. After I would remove one day like this: ``` date('m/d/Y', strtotime($date. ' - 1 days'); ``` And create a query to update all the columns based on id. I just want to avoid that. Is there any SQL command that do that? Thanks<issue_comment>username_1: The request below will update the rows you want by adding -1 days on each date: ``` UPDATE tbl_table SET dates = Dateadd(day, -1, dates) WHERE id IN ( 29695, 29700, 29701, 29702, 29703, 29704, 29705, 29706, 29707, 29708, 29709, 29710, 29711, 29712, 29713, 29714, 29715 ) ``` `DATEADD` function takes 3 parameters: 1. the `interval` ( day, month, year ..) 2. the `increment` (the value to add or remove if negative) 3. an `expression` (wich is a datetime type) See [DATEADD documentation](https://learn.microsoft.com/fr-fr/sql/t-sql/functions/dateadd-transact-sql) Upvotes: 4 [selected_answer]<issue_comment>username_2: To return a query with the previous day: ``` SELECT TOP (1000) ID, Dates, DATEADD(dd, -1, Dates) AS PreviousDay FROM tbl_table ``` To update the table with the previous day: ``` UPDATE tbl_table SET Dates = DATEADD(dd, -1, Dates) FROM -- Put your conditions here ``` Upvotes: 2 <issue_comment>username_3: ``` UPDATE tableName SET date= DATEADD(d,-1, date) where .... ``` ( here you put where clause for you required) Upvotes: 0
2018/03/21
602
2,597
<issue_start>username_0: I want to translate this into lambda syntax and can't seem to get it to work: Grouping by two columns, select max on a different column, return list of complete complex object. I am writing more text here to get past the validation on this form. How much text is needed until I am allowed to post this? ``` _clientpolicies = (from policy in _reply.CommercialInsuredGroupWithPolicyTerm.InsuredWithPolicyTerm.SelectMany(x => x.PolicyTerm) .Where(x => !(string.IsNullOrWhiteSpace(x.PolicyNumber) && string.IsNullOrWhiteSpace(x.ControlNumber))) .Where(x => x.Insured.DNBAccountNumber == _client.LookupID) group policy by new { PolicyReference = GetPolicyReference(policy), PolicyType = policy.ProductInformation.PolicyTypeCode } into g let maxPolicyInception = g.Max(p => p.InceptionDate) from policyGroup in g where policyGroup.InceptionDate == maxPolicyInception select policyGroup).ToList(); ```<issue_comment>username_1: I dont think there's a way of doing it in one line. So there's my try : ``` policyGroups= _reply.CommercialInsuredGroupWithPolicyTerm.InsuredWithPolicyTerm .SelectMany(x => x.PolicyTerm) .Where(x => !(string.IsNullOrWhiteSpace(x.PolicyNumber) && string.IsNullOrWhiteSpace(x.ControlNumber))) .Where(x => x.Insured.DNBAccountNumber == _client.LookupID) .GroupBy(x => GetPolicyReference(x)) .ThenBy(x => x.ProductInformation.PolicyTypeCode) .ToList(); var maxPolicyInception = policyGroups.Max(p => p.InceptionDate); _clientpolicies = policyGroups .Where(g => g.InceptionDate == maxPolicyInception) .ToList(); ``` Upvotes: 1 <issue_comment>username_2: ``` _clientpolicies = _reply.CommercialInsuredGroupWithPolicyTerm.InsuredWithPolicyTerm.SelectMany(x => x.PolicyTerm) .Where(x => !(string.IsNullOrWhiteSpace(x.PolicyNumber) && string.IsNullOrWhiteSpace(x.ControlNumber))) .Where(x => x.Insured.DNBAccountNumber == _client.LookupID) .GroupBy(x => new { PolicyReference = GetPolicyReference(x), PolicyType = x.ProductInformation.PolicyTypeCode }, (key, g) => g.OrderByDescending(gx => gx.InceptionDate).First() ``` Upvotes: 1 [selected_answer]
2018/03/21
399
1,463
<issue_start>username_0: There are some bash scripts running on our build machines where IncrediBuild is installed. The idea of IncrediBuild is to utilize all cores available in the network to speed up the build process. Example shell script: ``` ... ib_console cmake --build . ``` The shell script shall not be changed. I would like to run the script on machines without ib\_console. Is there a possibility to somehow simulate it or forward the call to cmake ?<issue_comment>username_1: Place this into your `.bashrc` file: ``` if [ ! -f ´whereis ib_console´ ] then alias ib_console='$@' fi ``` Explanation: * **-f** checks, whether the ib\_console binary exists * **$@** take all arguments into one single string (they are then executed standalone) Upvotes: 2 <issue_comment>username_2: @alex: the alias works from the shell but not in the shell script above since aliases are not expanded in non interactive shell scripts. With [Why doesn't my Bash script recognize aliases?](https://unix.stackexchange.com/questions/1496/why-doesnt-my-bash-script-recognize-aliases?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa) I could fix it. ``` if ! [ -f 'whereis ib_console' ]; then ib_console() { echo "ib_console dummy: run '$@'..." $@ echo "ib_console dummy: done" } export -f ib_console fi ``` It is recommended to run 'exec bash' after updating .bashrc Upvotes: 3 [selected_answer]
2018/03/21
652
2,311
<issue_start>username_0: In part of a project, given a single integer/character x and a tuple/string a, I need to create a new tuple/string that's the original tuple/string extended by that element. My current code looks like: ``` def extend(x, a): if type(a) is tuple: return a + (x,) if type(a) is str: return a + x ``` Is there a better way to code this, to either make it shorter or more generalizable to data types?<issue_comment>username_1: How about this way: ``` def extend(x, a): return a + {tuple: (x,), str: x, list: [x]}[type(a)] ``` Of course, keep in mind that the number of datatypes is really big and a *one-size-fits-all* approach does not exist. So, take another hard look on whatever code comes before this and if you *really* need it, use this dictionary approach. --- **EDIT** * If you need to do this many many times, do it with an `if` block. As @chepner says, building a dictionary every time will render this approach too smart for its own good. * If subclassing is also an issue, you should change from `type` to `isinstance` as @Jean-FrancoisFabre says. Upvotes: 2 <issue_comment>username_2: It is not clear why you want to extend tuples and string at the same part of code. May be you need refactoring. `list` seems to be the correct type for such operations and it has already `.append(x)` for it. If you are sure you need different types, you function seems OK. But just add ``` raise TypeError() ``` at the end of it. So you'll be sure not to miss unpredicted data type. Upvotes: 2 <issue_comment>username_3: Ev Kounis use of a dictionary is original but if the aim was to gain speed, it doesn't really work, because the dictionary is rebuilt each time (`x` varies) A slight modification would be to use a dictionary of *conversion functions*. This one is fixed. Pass the parameter to the proper conversion function and it's done: ``` # this is built once d = {tuple: lambda x:(x,), str: lambda x:x, list: lambda x:[x]} def extend(x, a): return a + d[type(a)](x) ``` (which still doesn't work is passing a *subclassed* type of `str`, `tuple`, whatever, but if you're sure you won't, this works) Honestly, using a dictionary for 3 keys won't be that fast, and a chain of `if`s is just as efficient. Upvotes: 2 [selected_answer]
2018/03/21
661
2,466
<issue_start>username_0: I want to show comments for every specific service in my website.. the store comment method is working properly! and when I try to display comments in the blade page I get this error > > SQLSTATE[42S22]: Column not found: 1054 Unknown column 'comments.service\_id' in 'where clause' (SQL: select \* from `comments` where `comments`.`service_id` = 11 and `comments`.`service_id` is not null) (View: C:\xampp\htdocs\dawerelzirou\resources\views\service\showservice.blade.php) > > > CommentsController.php (store comment) ``` public function store(Request $request, $services_id) { $this->validate($request,array( 'body'=>'required', )); $comment=new Comment; $comment->body=$request->body; $comment->user_id=$request->user()->id; $comment->services_id=$services_id; $comment->save(); $request->session()->flash('notif','success'); return back(); } ``` this is Comment.php ``` class Comment extends Model{ public function user() { return $this->belongsTo('App\User');} public function services() { return $this->belongsTo('App\Service');} } ``` This is Service.php ``` class Service extends Model{ public function user(){ return $this->belongsTo('App\User'); } public function comments(){ return $this->hasMany('App\comment'); } } ``` The blade page : ``` @if (count($services->comments)>0) @foreach ($services->comments as $comment) ![](/img/bg.jpeg) $comment->user->username $comment->body @endforeach @endif ```<issue_comment>username_1: Laravel has specific naming conventions - your column should be `service_id`, not `services_id`. Since you're *not* using that naming convention, you need to tell the relationship what column to look in: ``` return $this->hasMany('App\comment', 'services_id'); ``` Note also that on some operating systems with case-sensitive file names, `App\Comment` and `App\comment` are different things. Make sure you're using the right capitalization - either `App\Comment`, `class Comment`, and `Comment.php`, **or** `App\comment`, `class comment`, and `comment.php`. Not a mix! Upvotes: 1 <issue_comment>username_2: Always add proper local and foreign keys while making the relations in laravel if you are not using naming conventions because laravel uses snakecase naming convrntions Upvotes: 3 [selected_answer]
2018/03/21
1,420
3,958
<issue_start>username_0: I am working with big datasets in MySQL (combined with Java) and trying to implement a Frequent Itemset algorithm. A recurring aspect of the algorithm is counting how many times a set of items (an item is a random integer) occurs in the dataset. Take for example this small dataset **T**: ``` ID | COL1 | COL2 | COL3 | COL4 | COL5 | --------------------------------------- 1 | 8 | 35 | 42 | 12 | 27 | 2 | 22 | 42 | 35 | 8 | NULL | 3 | 18 | 22 | 8 | NULL | NULL | 4 | 42 | 12 | 27 | 35 | 8 | 5 | 18 | 27 | 12 | 22 | NULL | ``` And this table **T2**: ``` COL1 | COL2 | ------------- 35 | 27 | 22 | 8 | 42 | 8 | 18 | 35 | 35 | 42 | ``` What I want as result is the following table (it can be an answer to a query as well): ``` COL1 | COL2 | COUNT | --------------------- 35 | 27 | 2 | 22 | 8 | 2 | 42 | 8 | 3 | 18 | 35 | 0 | 35 | 42 | 3 | ``` So I want to count every occurrence of each row of table **T2** in table **T**. Basically how many times is a row of **T2** a subset of rows in **T** This has to be done in every generation of the algorithm. This is a very small example, eventually the same has to be done with **T3** (rows with 3 items), **T4** (rows with 4 items), etc. Table **T** stays the same. I also have to take into account that the order doesn't matter ( |35, 27| = |27, 35|) and that they will probably not be in columns next to each other in **T** Is it possible to do this without going over the dataset too many times (whereas *too many* = more than the amount of rows from **T2**)? Might it be better to represent a row as a tuple (e.g. (35, 27)) so it becomes one item?<issue_comment>username_1: If you can restructure your data to one value per row, for T and TN, something like this should work for all TN at once. ``` SELECT n_id, COUNT(CASE WHEN matches = n_count THEN v_id ELSE NULL) AS occurences FROM ( SELECT n.n_id, v.set_id AS v_id, n.n_count, COUNT(*) AS matches FROM (SELECT n_id, COUNT(*) AS n_count FROM tN GROUP BY id) AS n INNER JOIN tN AS nv ON n.n_id = nv.n_id LEFT JOIN T_VALUES AS v ON nv.value = v.value GROUP BY n.n_id, v.set_id, n.n_count ) AS subQ; ``` If you need the TN values in your final results, something like this would come close. ``` SELECT n_id, n_values, COUNT(CASE WHEN matches = n_count THEN v_id ELSE NULL) AS occurences FROM ( SELECT n.n_id, n.n_count, n.n_values, v.set_id AS v_id, COUNT(*) AS matches FROM ( SELECT n_id, COUNT(*) AS n_count , GROUP_CONCAT(n.value) AS n_values FROM tN GROUP BY id ) AS n INNER JOIN tN AS nv ON n.n_id = nv.n_id LEFT JOIN T_VALUES AS v ON nv.value = v.value GROUP BY n.n_id, n.n_count, n.n_values, v.set_id ) AS subQ; ``` *Note: you can probably get away without a subquery, but could end up having the database calculate the same n\_count and n\_values repeatedly for each row of T.* Upvotes: 2 [selected_answer]<issue_comment>username_2: Because of username_1's answer I realised I had to use a different structure, so instead of using the table **T**: ``` ID | COL1 | COL2 | COL3 | COL4 | COL5 | --------------------------------------- 1 | 8 | 35 | 42 | 12 | 27 | 2 | 22 | 42 | 35 | 8 | NULL | 3 | 18 | 22 | 8 | NULL | NULL | 4 | 42 | 12 | 27 | 35 | 8 | 5 | 18 | 27 | 12 | 22 | NULL | ``` I now use **Tnew**: ``` ID | Item| 1 | 8 | 1 | 35 | 1 | 42 | . | . | . | . | . | . | ``` This works way easier in SQL, you can use Group By and Join to get the result needed. The query works with any number of items with the same ID. Also, you don't have to use the value NULL and the dataset is easier to create If anyone wants to know the query I eventually used, please let me know (bit of work to come up with good tablenames and make it clear and understandable). Upvotes: 0
2018/03/21
994
2,759
<issue_start>username_0: i am trying to download a image from remote server and i get error 500 when i do it via perl getstore. i need to use getstore. it works for other host but this provider. ``` use LWP::Simple; my $url = "http://shop.xeptor.co.uk/imgs/cef4cbbe-d86e-420e-aec6-4371d7e9b2bc/250/250/2262497R4xtrep.jpg"; my $filename = "test.jpg"; my $rc = getstore($url, $filename); if (is_error($rc)) { die "getstore of <$url> failed with $rc"; } ``` i can download the image via wget or via the web browser and not via getstore .<issue_comment>username_1: If you can restructure your data to one value per row, for T and TN, something like this should work for all TN at once. ``` SELECT n_id, COUNT(CASE WHEN matches = n_count THEN v_id ELSE NULL) AS occurences FROM ( SELECT n.n_id, v.set_id AS v_id, n.n_count, COUNT(*) AS matches FROM (SELECT n_id, COUNT(*) AS n_count FROM tN GROUP BY id) AS n INNER JOIN tN AS nv ON n.n_id = nv.n_id LEFT JOIN T_VALUES AS v ON nv.value = v.value GROUP BY n.n_id, v.set_id, n.n_count ) AS subQ; ``` If you need the TN values in your final results, something like this would come close. ``` SELECT n_id, n_values, COUNT(CASE WHEN matches = n_count THEN v_id ELSE NULL) AS occurences FROM ( SELECT n.n_id, n.n_count, n.n_values, v.set_id AS v_id, COUNT(*) AS matches FROM ( SELECT n_id, COUNT(*) AS n_count , GROUP_CONCAT(n.value) AS n_values FROM tN GROUP BY id ) AS n INNER JOIN tN AS nv ON n.n_id = nv.n_id LEFT JOIN T_VALUES AS v ON nv.value = v.value GROUP BY n.n_id, n.n_count, n.n_values, v.set_id ) AS subQ; ``` *Note: you can probably get away without a subquery, but could end up having the database calculate the same n\_count and n\_values repeatedly for each row of T.* Upvotes: 2 [selected_answer]<issue_comment>username_2: Because of username_1's answer I realised I had to use a different structure, so instead of using the table **T**: ``` ID | COL1 | COL2 | COL3 | COL4 | COL5 | --------------------------------------- 1 | 8 | 35 | 42 | 12 | 27 | 2 | 22 | 42 | 35 | 8 | NULL | 3 | 18 | 22 | 8 | NULL | NULL | 4 | 42 | 12 | 27 | 35 | 8 | 5 | 18 | 27 | 12 | 22 | NULL | ``` I now use **Tnew**: ``` ID | Item| 1 | 8 | 1 | 35 | 1 | 42 | . | . | . | . | . | . | ``` This works way easier in SQL, you can use Group By and Join to get the result needed. The query works with any number of items with the same ID. Also, you don't have to use the value NULL and the dataset is easier to create If anyone wants to know the query I eventually used, please let me know (bit of work to come up with good tablenames and make it clear and understandable). Upvotes: 0
2018/03/21
617
1,860
<issue_start>username_0: I need to convert special characters (in this case Ð character) from cp850 to unicode and I am not being able to do it with mb\_convert\_encoding. The correct conversion should be from Ð to Ñ in spanish but function mb\_convert\_enconding('Ð', 'utf-8') returns Ã. Do you have any idea why does this happen? Thanks in advance.<issue_comment>username_1: You need to pass the source encoding: ``` print mb_convert_enconding('Ð', 'utf-8', 'CP850'); ``` If you don't, the default order will be used to try to guess the original encoding, and it's usually detecting UTF8 and/or Latin1 first. Upvotes: 0 <issue_comment>username_2: If you apply utf8\_encode() to an already UTF8 string it will return a garbled UTF8 output. I made a function that addresses all this issues. It´s called `Encoding::toUTF8()`. You don't need to know what the encoding of your strings is. It can be Latin1 (iso 8859-1), Windows-1252 or UTF8, or the string can have a mix of them. `Encoding::toUTF8()` will convert everything to UTF8. Usage: ``` require_once('Encoding.php'); use \ForceUTF8\Encoding; // It's namespaced now. $utf8_string = Encoding::fixUTF8($garbled_utf8_string); ``` Download: <https://github.com/neitanod/forceutf8> Examples: ``` echo Encoding::fixUTF8("Fédération Camerounaise de Football"); echo Encoding::fixUTF8("Fédération Camerounaise de Football"); echo Encoding::fixUTF8("FÃÂédÃÂération Camerounaise de Football"); echo Encoding::fixUTF8("Fédération Camerounaise de Football"); ``` will output: ``` Fédération Camerounaise de Football Fédération Camerounaise de Football Fédération Camerounaise de Football Fédération Camerounaise de Football ``` I've transformed the function (forceUTF8) into a family of static functions on a class called Encoding. The new function is `Encoding::toUTF8()`. Upvotes: 1
2018/03/21
510
1,688
<issue_start>username_0: Is there a way (without VBA) to change the content of a cell in Excel so that nobody can see a client name? So for example in a list of cells I may have: Smith Jones Williams etc... I want to set up the cell so that when the inputter types in the client name, they can see it to make sure it's correct but on pressing return or moving away from the cell it then anonymizes it so it looks like this: \*\*ith \*\*nes \*\*\*\*\*ams Or something similar. Once anonymized the original name cannot be viewed. Thanks<issue_comment>username_1: Copy all of your names to another sheet, then remove duplicates. On the de-duped list, put a code or fake name (<NAME>, <NAME> etc.) next to each original name. Then use VLOOKUP on your original data to pull through each code/fake name. Copy and paste the VLookup column as a value then delete the original name column. Upvotes: 0 <issue_comment>username_2: **Without VBA**: ``` =CONCATENATE(REPT("*",(LEN(A1)-LEN(A1)/2+MOD(LEN(A1),2))), RIGHT(A1,LEN(A1)/2+MOD(LEN(A1),2))) ``` It concatenates two parts: * half of the length is presented as `*` through the `REPT` function * the second half of the length is left. The `MOD(LEN(A1),2)` part is needed to support even and odd length of the strings. **With VBA** Judging from your question, you need something like a login form. The best way to do it is: * make `UserForm` (with VBA); * add a `TextBox`; * in the properties of the `TextBoxc` set the `PasswordChar` to `*` or anything else; [![enter image description here](https://i.stack.imgur.com/d0XAa.png)](https://i.stack.imgur.com/d0XAa.png) Upvotes: 3 [selected_answer]
2018/03/21
468
1,552
<issue_start>username_0: I have a dataframe with measure columns `SalesMonth1` -- `SalesMonth12` and another columns `Index` and `price`. I am trying to do the following but it does not work. Could you please suggest a better way? ``` For i in range(12): DF['Newcol'] = np.where(DF["Index"] >0, DF["SalesMonth[i]"] * DF["price"], DF["SalesMonth[i]"]) ```<issue_comment>username_1: Copy all of your names to another sheet, then remove duplicates. On the de-duped list, put a code or fake name (<NAME>, <NAME> etc.) next to each original name. Then use VLOOKUP on your original data to pull through each code/fake name. Copy and paste the VLookup column as a value then delete the original name column. Upvotes: 0 <issue_comment>username_2: **Without VBA**: ``` =CONCATENATE(REPT("*",(LEN(A1)-LEN(A1)/2+MOD(LEN(A1),2))), RIGHT(A1,LEN(A1)/2+MOD(LEN(A1),2))) ``` It concatenates two parts: * half of the length is presented as `*` through the `REPT` function * the second half of the length is left. The `MOD(LEN(A1),2)` part is needed to support even and odd length of the strings. **With VBA** Judging from your question, you need something like a login form. The best way to do it is: * make `UserForm` (with VBA); * add a `TextBox`; * in the properties of the `TextBoxc` set the `PasswordChar` to `*` or anything else; [![enter image description here](https://i.stack.imgur.com/d0XAa.png)](https://i.stack.imgur.com/d0XAa.png) Upvotes: 3 [selected_answer]
2018/03/21
753
3,027
<issue_start>username_0: This is how my layout looks currently: [![Screencap](https://i.stack.imgur.com/eFaLG.png)](https://i.stack.imgur.com/eFaLG.png) My intention is to have that Pending text in one line without it being character-wrapped onto two lines. My understanding of XAML was that I could do this by setting the yellow text label to something like `HorizontalOptions="Start"` with my text in green having `EndAndExpand` or `FillAndExpand` so that it's container would grow to meet it's width needs. As you can tell by the screenshot that hasn't worked out very well for me and I've spent hours trying every variation on this I can think of and I have gotten absolutely nowhere. The only way I can get the text to be shown on one line is to manually set the width, which is useless since it will be dynamic and can be short or long. Secondly, I could reduce the amount of yellow text (which does allow the green text to appear on one line), which is also useless since the titles will have roughly that length to them. I've also tried changing the `LineBreakMode` but that does nothing for layout and the characters that would normally be wrapped are instead not displayed. E: This is my XAML too: ``` ``` Absolutely any and all help would be appreciated on this problem, thanks.<issue_comment>username_1: I'd try replacing your `StackLayout` with a `Grid` and then adjust your frame accordingly. ``` ``` If you do that though you might also want to try consolidating all your views on your `Page` to use that one grid instead of having extra nested stackLayouts like you currently have. Upvotes: 2 [selected_answer]<issue_comment>username_2: Xamarin forms provide another `Layout` options as `Grid`, for example, and I think this one can be more accurate to what you 're trying to achieve. The problem you're facing is the `StackLayout` tries to adjust itself and its children view to obey their position constraints inside the current viewport that the screen provides, but this gets weird when the inner view requires more space than is available. *Probably if you turn you emulator to landscape mode the layout you've wrote with stacklayouts should look like you're expecting (this way it'll get space enough)*. On the other hand, the grid's rows and columns constraints are more flexible and fair to understand this kind of layout. If I'd understood what you want, the layout should look like this: [![[Image sample]](https://i.stack.imgur.com/9gU79.png)](https://i.stack.imgur.com/9gU79.png) As you can see, it's a grid with 1 row and 3 columns. About the columns, they are: - First, fixed width - Second, dynamically occupy all available space - Third, the width should fit its content width **This is how you can express it with `Grid`:** ``` ``` I encourage you to take a look at the [xamarin.forms layout docs](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts) for more information. I hope it helps (and sorry for the poor English). Upvotes: 0
2018/03/21
622
2,326
<issue_start>username_0: I have an empty JSON object ``` export class Car {} ``` I have imported it in a `component.ts` and I would like to add some fields in a loop. Something like ``` aux = new Car; for (var i = 0; i < 10; i++) { car.addName("name" + i); } ``` My goal would be to get at the end the following object ``` car: { name1: name1; name2: name2; .... } ``` I have created the JSON object empty because at the beginning I do not know how many elements or fields will have. I could create this object by javascript. I do not need to have an `export class` is it possible?<issue_comment>username_1: I'd try replacing your `StackLayout` with a `Grid` and then adjust your frame accordingly. ``` ``` If you do that though you might also want to try consolidating all your views on your `Page` to use that one grid instead of having extra nested stackLayouts like you currently have. Upvotes: 2 [selected_answer]<issue_comment>username_2: Xamarin forms provide another `Layout` options as `Grid`, for example, and I think this one can be more accurate to what you 're trying to achieve. The problem you're facing is the `StackLayout` tries to adjust itself and its children view to obey their position constraints inside the current viewport that the screen provides, but this gets weird when the inner view requires more space than is available. *Probably if you turn you emulator to landscape mode the layout you've wrote with stacklayouts should look like you're expecting (this way it'll get space enough)*. On the other hand, the grid's rows and columns constraints are more flexible and fair to understand this kind of layout. If I'd understood what you want, the layout should look like this: [![[Image sample]](https://i.stack.imgur.com/9gU79.png)](https://i.stack.imgur.com/9gU79.png) As you can see, it's a grid with 1 row and 3 columns. About the columns, they are: - First, fixed width - Second, dynamically occupy all available space - Third, the width should fit its content width **This is how you can express it with `Grid`:** ``` ``` I encourage you to take a look at the [xamarin.forms layout docs](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/controls/layouts) for more information. I hope it helps (and sorry for the poor English). Upvotes: 0
2018/03/21
314
1,025
<issue_start>username_0: I am having some difficulties with footer css. I want it to stay in the bottom of the page. I don't want it to be visible until i scroll to the bottom of the page. ``` .footer{ position: fixed; display: block; width: 100%; height: 80px; bottom: 0; float: none; } ```<issue_comment>username_1: The problem come from `position: fixed;`. "fixed" means that it is fixed on the viewport. So try to remove `position: fixed;` [CSS : Position property](https://www.w3schools.com/css/css_positioning.asp) Upvotes: 2 [selected_answer]<issue_comment>username_2: ``` .footer { position: absolute; display: block; width: 100%; height: 0; bottom: 0; float: none; transition: height 1s ease-in-out; } .footer.active { height: 80px; } window.onscroll = function(ev) { if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) { $(".footer").addClass('active'); } else { $(".footer").removeClass('active'); } }; ... ``` Upvotes: 0