_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d14201
val
This has nothing to do with Meteor, rather it is about setting up your nginx's default page. Try the below links http://gpiot.com/blog/setup-default-server-landing-page-with-nginx/ NGinx Default public www location?
unknown
d14202
val
Every url start with a "/" so RewriteRule ^myOwnAPI/?$ somefile.php [NC,L] won't ever match. Change it to RewriteRule ^/myOwnAPI/? /somefile.php [NC,L] Moreover, please read the offical documentation https://httpd.apache.org/docs/2.4/rewrite/flags.html if you need to "pass" the parameters to the new url (flag QSA).
unknown
d14203
val
I write it in directive. app.directive('commentsDirective', function(){ $scope.$watch('comments', function(){ angular.element('#comment-list').tinyscrollbar_update('relative'); }); })
unknown
d14204
val
This error usually occurs if the user account was not given/assigned to the Virtual Machine User Login role on the VMs. Please check this https://learn.microsoft.com/en-us/azure/active-directory/devices/howto-vm-sign-in-azure-ad-windows#azure-role-not-assigned to assign required roles and try login.
unknown
d14205
val
I realise that this question is a little old now, however hopefully this information will help someone. As far as I can tell, there is no public API available for DataGrid that will allow the reading of the selection anchor, nor the setting of the selection anchor without clearing the existing selection. To work around this, I had a look at WPF's source code (this for .NET Framework 4.8, this for .NET (previously named .NET Core) at the time of writing) and identified that the selection anchor appears to be solely handled by a field of type Nullable<DataGridCellInfo> called _selectionAnchor. For anyone who has worked with adjusting DataGrid selection programmatically, you just need to set _selectionAnchor after the operation for subsequent SHIFT selection operations to behave properly. If you wish to clear the selection anchor having just programmatically deselected all cells, just set the selection anchor to null. You can find more information on reflection here. TLDR: Use reflection to access the private _selectionAnchor field eg: // These lines of code are not intended to do anything more than demonstrate usage of reflection to get and set this private field. // In reality you'd be passing SetValue() something other than the value the field was already set to. var fieldInfo = typeof(DataGrid).GetField("_selectionAnchor", BindingFlags.Instance | BindingFlags.NonPublic); var anchorCellInfo = fieldInfo.GetValue(dataGridInstance) as DataGridCellInfo?; fieldInfo.SetValue(dataGridInstance, anchorCellInfo); NOTE: Using reflection to access private/internal functionality always carries the risk that the maintainer of the thing you're accessing could update those private/internal parts at any point in a future release without prior warning. That said, from what I can see, this particular functionality has been pretty much unchanged for years in WPF so you should hopefully be alright. To be on the safe side, you could potentially add unit tests to verify that the private/internal functionality you're accessing continues to exist and behave in the same way you need it to, so that your application does not subtly break at runtime after updating a package on which you're using reflection to access private/internal functionality. I should emphasise that it is unusual for a project's unit tests to test functionality in its dependencies, however this seems to me to be a somewhat unique case.
unknown
d14206
val
Java 6 provides a cryptographic provider named SunMSCAPI to access the windows cryptography libraries API. This provider implements a keystore "Windows-Root" containing all Trust Anchors certificates. It is possible to insert a certificate in this keystore. KeyStore root = KeyStore.getInstance("Windows-ROOT"); root.load(null); /* certificate must be DER-encoded */ FileInputStream in = new FileInputStream("C:/path/to/root/cert/root.der"); X509Certificate cacert = (X509Certificate)CertificateFactory.getInstance("X.509").generateCertificate(in); root.setCertificateEntry("CACert Root CA", cacert); The user will be prompted if for confirmation. If the operation is canceled by the user then a KeyStoreException is thrown. Some technotes about the provider can be found here: http://download.oracle.com/javase/6/docs/technotes/guides/security/SunProviders.html#SunMSCAPI A: Think about it. If this were possible, what would stop any fraudulent site from doing the same thing and making it look like their site was trusted? The whole point is that the user HAS to OK the certificate installation. A: First of all, possibility to do this would compromise user's security, so it would be a security hole, so no, there's no easy way to do this. Next, different software has different certificate stores. Microsoft and Chrome browser use CryptoAPI stores, Firefox has it's own store (Chrome can also use firefox's one AFAIK). Adobe's software has it's own store (in addition to CryptoAPI one).
unknown
d14207
val
This code used to display the circle image image.layer.borderWidth = 1 image.layer.masksToBounds = false image.layer.borderColor = UIColor.blackColor().CGColor image.layer.cornerRadius = image.frame.height/2 image.clipsToBounds = true A: My guess would be that the component you have called viewCirlce is a rectangle to start with, you are just setting the corner radius. If the component has the same width and height then this could give you a circle. If it's a rectangle, then you'll get an ellipse. A: import UIKit class ViewController: UIViewController { @IBOutlet weak var image: UIImageView! override func viewDidLoad() { super.viewDidLoad() image.layer.borderWidth = 1 image.layer.masksToBounds = false image.layer.borderColor = UIColor.blackColor().CGColor image.layer.cornerRadius = image.frame.height/2 image.clipsToBounds = true } A: add this code and make sure your viewCirlce is a square view self.viewCirlce.layer.masksToBounds = true A: Make sure height and width of viewCirlce are equal and put your this code in a method which is called after viewCirlce is loaded for e.g : override func viewDidLayoutSubviews() { self.viewCirlce = self.viewCirlce.frame.size.height / 2.0 self.viewCirlce.layer.masksToBounds = true }
unknown
d14208
val
Solution found: Future<QuerySnapshot> getData() async { var User = await FirebaseAuth.instance.currentUser(); return await Firestore.instance .collection("dataCollection") .where(FieldPath.documentId, isEqualTo: User.uid ) .getDocuments(); }
unknown
d14209
val
"If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component." applies here: STATIC_URL is an absolute path because it starts with /, so BASE_DIR is dropped. Drop the leading / else dirname thinks that STATIC_URL is absolute and keeps only that. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = 'static/'
unknown
d14210
val
You cannot query whether a specific value exists in a list. This is one of the many reasons why the Firebase documentation recommends against using arrays in the database. But in this case (and most cases that I encounter), you may likely don't really need an array. Say that you just care about what colors your user picked. In that case, you can more efficiently store the colors as a set: palettes -KSmJZ....A5I "0x474A39": true "0xbA9A7C": true "0xDEDEDF": true "0x141414": true "0x323E35": true A: I did it in a different way, made a function that does this: let databaseRef = FIRDatabase.database().reference() let HEX1 = hex1.text! as String let HEX2 = hex2.text! as String let HEX3 = hex3.text! as String let HEX4 = hex4.text! as String let HEX5 = hex5.text! as String let URL = url.text! as String // First set let colorArray1 = [HEX2, HEX3, HEX4, HEX5, URL] databaseRef.child("palette").child(HEX1).setValue(colorArray1) // second set let colorArray2 = [HEX1, HEX3, HEX4, HEX5, URL] databaseRef.child("palette").child(HEX2).setValue(colorArray2) // third set let colorArray3 = [HEX1, HEX2, HEX4, HEX5, URL] databaseRef.child("palette").child(HEX3).setValue(colorArray3) // fourth set let colorArray4 = [HEX1, HEX2, HEX3, HEX5, URL] databaseRef.child("palette").child(HEX4).setValue(colorArray4) // fifth set let colorArray5 = [HEX1, HEX2, HEX3, HEX4, URL] databaseRef.child("palette").child(HEX5).setValue(colorArray5) so that when I target any of the 5 hexes, it will bring me back the whole array together with it.
unknown
d14211
val
This is likely a good use of the Lazy<T> class, used in a static variable so there is only a single copy for the process. It will run the Func you give it once to initialize during the first access of the variable. https://msdn.microsoft.com/en-us/library/dd642331(v=vs.110).aspx However, based on your class structure I'm not sure if it is the best approach. What is the purpose for the hierarchy of Branch : division and Department : Branch. Is the Branch a Division? If you are trying to share common properties as to not code them over again, I would suggest creating a common class that can hold those variables that Branch, Division, and Department can inherit from. A: You can use a static variable / static constructor in the lowest class in the hierarchy. The static constructor will only be called once. A: A simple solution is to use a "control" variable. I'm sure you can improve your design and avoid this problem but I don't have time to check it now.. using System; namespace Program { internal class Program { private static void Main(string[] args) { division d = new division(); d.CreateDivisionStructure(); Console.ReadLine(); } } internal class division { private static int CountHowManyTimesMyVarWasInitilized = 0; public division() { } protected string _myVar; private bool _isReadyForInitialization; public string myVar { get { if (!_isReadyForInitialization) return null; if (_myVar == null) { CountHowManyTimesMyVarWasInitilized++; Console.WriteLine(CountHowManyTimesMyVarWasInitilized); _myVar = "now myVar is not null"; return _myVar; } else { return _myVar; } } set { _myVar = value; } } public void CreateDivisionStructure() { // now _myVar is spposed to be initilized to all dirved clasess isnt is? Console.WriteLine(myVar); for (int i = 0; i < 7; i++) { Branch b = new Branch(7); } _isReadyForInitialization = true; Console.WriteLine(myVar); } } internal class Branch : division { public Branch(bool dImDerivedClass) { // constructor for department to prevent recursive stackoverflow if base of department will call the empty constructor } public Branch(int NumberOfBranches) { Console.WriteLine(myVar); Department d = new Department(7); } } internal class Department : Branch { public Department(bool ImDerivedClass) : base(true) { // constructor for team to prevent recursive stackoverflow if base of Team will call the empty constructor } public Department(int numberOfDep) : base(true) { for (int i = 0; i < numberOfDep; i++) { Console.WriteLine(myVar); Team t = new Team(7); } } } internal class Team : Department { public Team():base(false) { } public Team(int numberOfTeams) : base(true) { for (int i = 0; i < numberOfTeams; i++) { Console.WriteLine(myVar); } } } }
unknown
d14212
val
yep so its working :) $(document).ready(function(e) { $("#scanner_mode").click(function() { cordova.plugins.barcodeScanner.scan( function (result) { document.getElementById("frame").src = result.text; }, function (error) { alert("Scanning failed: " + error); } ); }); }); that works :)
unknown
d14213
val
The abilities that Access 2013 has compared to the Sharepoint "web app" feels limited. You cannot use the VBA code in any of your forms and must deal with SQL and Macro Commands only. So if you use a lot of VBA you will have to redo most of your project and learn how to use the macro's. Personally i have used VBA to do most of my work but like you need it to be out on the web now. My main fear with spending time using Access and Sharepoint is not being able to custom code pieces in. If i run into a limitation i don't believe there is another option. * *Example Web App *When Access web apps 2013 gets Johnny frustrated... *Discontinued features and modified functionality in Access 2013 The interface is different and from an overview seems more effective for simple input and view forms, something easily used on a phone. For instance this is a default contact form in its edit view in Access. Most of your control is centered around the custom buttons on top which i found to be limited to on click macros and simple edit / save data actions. Your options for forum design also is limited, however there is an added bonus of an autocomplete search input bar which is absent from the desktop based projects. In addition the macro list options have been reduced some.
unknown
d14214
val
There is a C API for reading MATLAB .MAT files. http://www.mathworks.se/help/matlab/read-and-write-matlab-mat-files-in-c-c-and-fortran.html
unknown
d14215
val
I don't think there is a direct API for this # to get indices of incorrect predictions incorrects = np.nonzero(model.predict_class(X_test) != Y_test) # Now train on them newX, newY = X_test[incorrects], Y_test[incorrects] model.fit(newX, newY)
unknown
d14216
val
Are you looking for this? http://adobe.com/devnet/flash/articles/embed_metadata.html A: Hope this will helpful for you. http://www.adobe.com/devnet/flex/articles/actionscript_blitting.html http://blog.nightspade.com/2010/02/01/embedding-asset-at-compile-time-in-pure-as3-project/ http://www.bit-101.com/blog/?p=853
unknown
d14217
val
So here's a quick script I whipped up: seekanddestroy.gradle defaultTasks 'seekAndDestroy' repositories{ //this section *needs* to be identical to the repositories section of your build.gradle jcenter() } configurations{ findanddelete } dependencies{ //add any dependencies that you need refreshed findanddelete 'org.apache.commons:commons-math3:3.2' } task seekAndDestroy{ doLast { configurations.findanddelete.each{ println 'Deleting: '+ it delete it.parent } } } You can invoke this script by running gradle -b seekanddestroy.gradle Demo of how it works: if your build.gradle looks like this: apply plugin:'java' repositories{ jcenter() } dependencies{ compile 'org.apache.commons:commons-math3:3.2' } First time build, includes a download of the dependency: λ gradle clean build | grep Download Download https://jcenter.bintray.com/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar Second clean build, uses cached dependency, so no download: λ gradle clean build | grep Download Now run seekanddestroy: λ gradle -b seekanddestroy.gradle -q Deleting: .gradle\caches\modules-2\files-2.1\org.apache.commons\commons-math3\3.2\ec2544ab27e110d2d431bdad7d538ed509b21e62\commons-math3-3.2.jar Next build, downloads dependency again: λ gradle clean build | grep Download Download https://jcenter.bintray.com/org/apache/commons/commons-math3/3.2/commons-math3-3.2.jar A: Works great, but for newer versions of gradle, use this instead: task seekAndDestroy{ doLast { configurations.findanddelete.each{ println 'Deleting: '+ it delete it.parent } } }
unknown
d14218
val
Try to handle the ShownEditor event as the following (semi-pseudo code): var grid = sender as GridView; if (grid.FocusedColumn.FieldName == "Value") { var row = grid.GetRow(grid.FocusedRowHandle) as // your model; // note that previous line should be different in case of for example a DataTable datasource grid.ActiveEditor.Properties.ReadOnly = // your condition based on the current row object } This way you could refine the already opened editor with your needs.
unknown
d14219
val
Found out that even if you have Google services, some android phones can be configured to use other voice recognising services and it can break the flow as React Native Voice is using Google Services. You can check which Voice services a particular Android Phone is using as following: Settings > App Management > Default App > Assistive App and Voice Input > Assistive App Hope this is helpful for those who might be facing the same issues.
unknown
d14220
val
Try creating a color array that has a color for each vertex. Right now I think you're reading off the end of the array into uninitialized memory when you try to render two vertexes, since you don't specify the color for the second vertex. Also, I think the third argument for your glDrawArrays() call should be 2, not 4, since you're only rendering two vertexes. I'm somewhat surprised it didn't crash with an access violation of some sort, honestly :)
unknown
d14221
val
Try using D3 graph. Visit https://d3js.org/ D3 uses javascript language. You can refer to multiple graphs. Even you can take input data from excel file to create dynamic graphs. You can refer to D3 network graph to understand how to change colour of vertex and edges of graph from given data http://christophergandrud.github.io/d3Network/ A: If you have the x and y values you can plot them directly on a worksheet. The following is an example that randomly generates x and y coordinates for 5 points. A small filled circle is drawn at each point. A line is drawn between the previous and the next point forming a closed loop. To demonstrate how you can select the line colors I alternately color them gray and blue to give you an idea of how to selectively color them based on some other criteria. vbBlue is one of a preset color pallet (see this link) which is why it doesn't have to be declared - unlike vbGray. Option Explicit Sub drawALine(xFrm As Double, yFrm As Double, xTo As Double, yTo As Double, c As Long) With ActiveSheet.Shapes.AddLine(xFrm, yFrm, xTo, yTo).Line .DashStyle = msoLineDashDotDot .ForeColor.RGB = c End With End Sub Sub drawNode(r As Double, x As Double, y As Double, c As Long) With ActiveSheet.Shapes.AddShape(msoShapeOval, x - r / 2, y - r / 2, r, r) .Fill.ForeColor.RGB = c End With End Sub Sub ConnectedOverLappingLoop() Dim xMax As Double, yMax As Double, x1 As Double, y1 As Double Dim xFrm As Double, yFrm As Double, xTo As Double, yTo As Double Dim radius As Double Dim vbGray As Long, clr As Long xMax = 200 yMax = 200 radius = 5 vbGray = RGB(150, 150, 150) xFrm = Rnd() * xMax yFrm = Rnd() * yMax x1 = xFrm y1 = yFrm clr = vbBlue drawNode radius, x1, y1, vbBlue Dim i As Integer For i = 1 To 5: xTo = Rnd() * xMax yTo = Rnd() * yMax drawNode radius, xTo, yTo, vbBlue drawALine xFrm, yFrm, xTo, yTo, clr xFrm = xTo yFrm = yTo If clr = vbBlue Then clr = vbGray Else clr = vbBlue End If Next drawALine xFrm, yFrm, x1, y1, clr End Sub
unknown
d14222
val
Sounds like it's started, and log_min_messages is set to a high enough value that you don't see any output. Using another terminal session connect to the server on the port it's running on. If you don't know that check the port value in the postgresql.conf inside the data directory. Generally you should use pg_ctl -D blah -w start rather than postgres directly. See the manual. Or, for long term use, set it up to run on startup via an init script.
unknown
d14223
val
The scenario you are describing (give someone a link to do something, and only that thing) is typically solved with server-side validation rather than just hiding the URL. Often, you want to make use of a "nonce", that is a one-time secret value for each allowed action that users could not guess. So for example http://www.example.com/validate-email/?nonce=d389mxfh47c A user could not simply change the nonce to get a desired effect. The server can look up what the correct, authorized action is for that nonce when the user accesses/submits the page.
unknown
d14224
val
It depends on how you have your data set up, but why can't you hook into your existing code? What are you doing in your existing code to refresh the detail view when a user selects a row in master view table? Can't you just call that method directly? It's hard to give specific advice without more detailed information on your current design.
unknown
d14225
val
Apple removed it because they just want to "force" everybody to use Storyboards, although from what I know, a big amount of people just don't find them useful. I'm afraid you'll have to do it yourself, just create an empty app and set yourself the view. Check an example: http://www.appcoda.com/hello-world-app-using-xcode-5-xib/ A: Apple remove it from xcode 5 . you have only one option to choose storyboard. if you want to xibs then remove storyboard after creating singleView application and add xib manually. another option is to create application in xcode 4.6 or earliar version then run it on xcode 5. A: * *Create a new project *Select Single View Application *Set ProjectName and other settings *Save Project at location *Select Project in Navigator Panel in Left *Remove Main.storyboard file from project *Add New .xib file in Project *Set Main Interface to your .xib file in "General Tab" on right panel. *Paste following code in didFinishLaunchingWithOptions method self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; self.window.rootViewController = [[UIViewController alloc] initWithNibName:@"YourViewController" bundle:nil]; [self.window makeKeyAndVisible];
unknown
d14226
val
Take a look at css transitions and/or animations. You could just update the css in your Javascript code like this: CSS #img { /* Initialize with 0% opacity (invisible) */ opacity: 0%; /* Use prefix for cross browser compatibility */ transition: opacity 1s; -o-transition: opacity 1s; -moz-transition: opacity 1s; -webkit-transition: opacity 1s; } Javascript Image.onload = function(){ this.style.opacity = "100%"; } You can use the same technique for swiping with the left property with a relative position in CSS. Adding it to the code var imagecount = 1; var total = 2; function slide (x){ var Image = document.getElementById('img'); imagecount = imagecount + x; if(imagecount > total){imagecount = 1;} if(imagecount < 1){imagecount = total;} Image.src = "images/img"+ imagecount +".png"; Image.style.opacity = "0%"; // Reset the opacity to 0% when reloading the image ! } window.setInterval(function slideA () { var Image = document.getElementById('img'); imagecount = imagecount + 1; if(imagecount > total){ imagecount = 1;} if(imagecount < 1){ imagecount = total;} Image.src = "images/img"+ imagecount +".png"; Image.style.opacity = "0%"; // Reset the opacity to 0% when reloading the image ! },5000); Then simply add it in the html node: <img src="images/img1.png" id="img" onload="this.style.opacity = '100%'">
unknown
d14227
val
Here is the full code to get this working. You need to create 2 files. // action.stub <?php namespace {{ namespace }}; use {{ namespacedModel }}; class {{ class }} { private ${{ modelVariable }}; public function execute({{ m }} ${{ modelVariable }}) { $this->{{ modelVariable }} = ${{ modelVariable }}; } } // makeAction.php <?php namespace App\Console\Commands; use Illuminate\Console\GeneratorCommand; use InvalidArgumentException; use Symfony\Component\Console\Input\InputOption; class makeAction extends GeneratorCommand { protected $signature = 'make:action {name} {--m=}'; protected $description = 'Create action file'; protected $type = 'Action file'; protected function getNameInput() { return str_replace('.', '/', trim($this->argument('name'))); } /** * Build the class with the given name. * * @param string $name * @return string */ protected function buildClass($name) { $stub = parent::buildClass($name); $model = $this->option('m'); return $model ? $this->replaceModel($stub, $model) : $stub; } /** * Replace the model for the given stub. * * @param string $stub * @param string $model * @return string */ protected function replaceModel($stub, $model) { $modelClass = $this->parseModel($model); $replace = [ '{{ namespacedModel }}' => $modelClass, '{{ m }}' => class_basename($modelClass), '{{ modelVariable }}' => lcfirst(class_basename($modelClass)), ]; return str_replace( array_keys($replace), array_values($replace), $stub ); } /** * Get the fully-qualified model class name. * * @param string $model * @return string * * @throws \InvalidArgumentException */ protected function parseModel($model) { if (preg_match('([^A-Za-z0-9_/\\\\])', $model)) { throw new InvalidArgumentException('Model name contains invalid characters.'); } return $this->qualifyModel($model); } /** * Get the stub file for the generator. * * @return string */ protected function getStub() { return app_path().'/Console/Commands/Stubs/action.stub'; } /** * Get the default namespace for the class. * * @param string $rootNamespace * @return string */ protected function getDefaultNamespace($rootNamespace) { return $rootNamespace.'\Actions'; } /** * Get the console command arguments. * * @return array */ protected function getOptions() { return [ ['model', 'm', InputOption::VALUE_OPTIONAL, 'Model'], ]; } } Command to run PHP artisan make:action task.AddTaskAction --m=Task it will create the following file <?php namespace App\Actions\task; use App\Models\Task; class AddTaskAction { private $task; public function execute(Task $task) { $this->task = $task; } }
unknown
d14228
val
You can try and use OUTPUT, it would be something like: INSERT INTO ExampleTable (<Column1>, <Column2>, <Column3>) OUTPUT INSERTED.ID VALUES (<Value1>, <Value2>, <Value3>) Also, this question, has a lot more info on the different types of identity selection, you should check it out. EDIT You would use this as a regular scalar: var command = new SqlCommand("..."); Guid id = (Guid) command.ExecuteScalar();
unknown
d14229
val
You can use os.scandir() to iterate over files in a directory: import re, os for file in os.scandir(input_dir): with open(file, "r") as fin, open("path_to_output_dir/" + output_file_name, "w") as fout: # whatever file operations you want to do for line in fin: fout.write(line) A: Read all files in the folder through the OS module, read the contents of each file, and then modify it. import os fileList = os.listdir(path) for info in os.listdir(path): domain = os.path.abspath(path) #Get folder path info = os.path.join(domain,info) #Combining the path with the file name is the full path of each file info = open(info,'r') #Read file contents #You can modify the file here info.close()
unknown
d14230
val
Replace with: (float.TryParse(comboCurrencyValue.SelectedItem.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture,out currency)&& float.TryParse(txtYourValue.Text,out inputValue)) To explain: in Poland a comma is used instead of a decimal point, so you must specify that you want to use an invariant culture.
unknown
d14231
val
As I suggested in the comment, you can edit your code like below (see three commented lines) and should be able to run without references. I am assuming that the code is correct otherwise and it is providing intended results Public Sub sendMail() Call ini_set If mail_msg.Cells(200, 200) = 1 Then lr = main_dist.Cells(main_dist.Rows.Count, "A").End(xlUp).Row On Error Resume Next For i = 2 To lr Application.DisplayAlerts = False Dim applOL As Object '\\Outlook.Application Dim miOL As Object '\\Outlook.MailItem Dim recptOL As Object '\\Outlook.Recipient mail_msg.Visible = True mailSub = mail_msg.Range("B1") mailBody = mail_msg.Range("B2") mail_msg.Visible = False Set applOL = New Outlook.Application Set miOL = applOL.CreateItem(olMailItem) Set recptOL = miOL.Recipients.Add(main_dist.Cells(i, 5)) recptOL.Type = olTo tempPath = ActiveWorkbook.Path & "\" & main_dist.Cells(i, 4) & ".xlsm" With miOL .Subject = mailSub .Body = mailBody .Attachments.Add tempPath .send End With Set applOL = Nothing Set miOL = Nothing Set recptOL = Nothing Application.DisplayAlerts = True Next i End Sub Late binding can help in some other cases as well especially if there are several users and they are having different setups with respect to software versions!
unknown
d14232
val
The both stacks use dynamically allocated memory for their nodes (though for std::stack it depends on underlying container). Of course it is better to use standard class. It was already tested and written by qualified programmers and it is flexible enough: you can use several standard containers to implement the stack because standard stack is a container adapter. In fact you can write your own underlying container for std::stack as for example a wrapper around an array and in this case the whole stack will be placed in the stack memory though its size of course will be fixed.:) Nevertheless the standard stack also has many drawbacks. For example you can not use std::forward_list as the underlying container. I made a proposal to specialize standard class std::stack for std::forward_list. A: which one is better depends surely on the use case. But generally I would advise you to use the STL implementation of the stack, because it is heavily used and therefore tested perfectly. Furthermore, you'll get a perfect abstraction of a stack with the STL implementation. Second, the STL implementation is also using dynamic memory allocation, so from this point of view there is no difference to your implementation. A: Using dynamic memory gives the advantage of adding possible memory leaks and/or segmentation faults to your program. I only use dynamic memory when forced to. Forcing example: working with a library that uses c-strings for parameters and return values.
unknown
d14233
val
myVar is str type. Not int type. You should fix myVar = int(input("Enter a number: ")) A: 0 and "0" are two different values. 0 == 0 is true; 0 == "0" is false. input always returns a str, so entering 0 sets myVar to "0", not 0. if myName == "John" and myVar == "0":
unknown
d14234
val
You don't need to write all that logic, you can just use Apache Commons BeanUtils; which provides a utility method (among MANY other utilities), that takes a Map of field names versus field values and populate a given bean with it: BeanUtils.populate(target, fieldNameValueMap); Then the only thing you need to implement is the logic to create the fieldNameValueMap Map; which you can do with this simple method: Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) { String[] fieldNames = headerLine.split("\t"); String[] fieldValues = valuesLine.split("\t"); return IntStream.range(0, fieldNames.length) .mapToObj(Integer::new) .collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx])); } You can test this solution with the following working demo: import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.apache.commons.beanutils.BeanUtils; import lombok.Data; public class DynamicBeanUtils { static Map<String, String> createFieldNameValueMap(String headerLine, String valuesLine) { String[] fieldNames = headerLine.split("\t"); String[] fieldValues = valuesLine.split("\t"); return IntStream.range(0, fieldNames.length) .mapToObj(Integer::new) .collect(Collectors.toMap(idx -> fieldNames[idx], idx -> fieldValues[idx])); } public static void main(String[] args) { String headerLine = "booleanValue\tintValue\tstringValue\tdoubleValue\totherValue"; String valuesLine = "true\t12\tthis bean will be populated\t22.44\ttest string!!!"; Object target = new MyBean(); try { BeanUtils.populate(target, createFieldNameValueMap(headerLine, valuesLine)); } catch (IllegalAccessException | InvocationTargetException e) { // HANDLE EXCEPTIONS! } System.out.println(target); } @Data public static class MyBean { private String stringValue; private double doubleValue; private int intValue; private boolean booleanValue; private String otherValue; } } This is the maven repository page for this dependency, so you can include it in your build: https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils/1.9.3 I used Lombok in this solution as well, only to save me the pain of writing getter/setters/toString to test this solution; but it is not required for your solution. Complete code on GitHub Hope this helps. A: You are going way overboard with your solution. Your data is organized as an array of variable length arrays; and does not require some crazy on-the-fly class generation solution. As a side note, on-the-fly class generation is not inherently crazy; it is crazy to use on-the-fly class generation in this situation. Do this: * *Look at your data; it is organized as follows: * *first: outer key *second: exactly one line containing a variable number of space separated array of inner keys. *third: some number of lines containing values. *Design a solution to fix your problem * *Read the outer key. Use that value to create the outer key portion of your JSON. *Read the inner keys. Store these in an array; use LinkedList, not ClownList (ArrayList). *Do this until the next empty line: * *Read a line of values. *Write the inner JSON; use the inner keys as the keys for this. *Skip empty lines until one of the following: * *If at end of file, write the ending portion of the JSON. *If you read the next outer key, goto to line 2 (Read the inner keys) above. *Write the code. A: I realized that instead of creating the POJOs with a complex approach. It is better to use the Maps and convert them to JSON using Jackson ObjectMapper. Posting for others who think this might be a useful approach. public String convert(Map<String, ? extends Metadata> metadataMap) { String output = ""; Map<String, List<Map<String, String>>> finalMap = new HashMap<>(); metadataMap.forEach((k, v) -> { List<Map<String, String>> datamap = new LinkedList<>(); String key = k; String[] fields = v.getFields(); List<String> lines = v.getLines(); lines.forEach(line -> { if (line != null && !line.isEmpty() && !line.equals("null")) { String[] fieldData = line.split("\t",-1); Map<String, String> eachLineMap = new HashMap<>(); for (int index = 0; index < fields.length; index++) { if (index < fieldData.length && (fieldData[index] != null && !fieldData[index].isEmpty())) { eachLineMap.put(fields[index], fieldData[index]); } else { eachLineMap.put(fields[index], " "); } datamap.add(eachLineMap); } } }); finalMap.put(key, datamap); }); try { output = new ObjectMapper().writeValueAsString(finalMap); }catch(JsonProcessingException e){ e.printStackTrace(); } return output; }
unknown
d14235
val
check this fiddle var countObj = {}; for( var counter = 0; counter < array.length; counter++ ) { var yearValue = array [ counter ].year; if ( !countObj[ yearValue ] ) { countObj[ yearValue ] = 0; } countObj[ yearValue ] ++; } console.log( countObj ); A: Try this: var array = [{ "name": "Tony", "year": "2010" }, { "name": "Helen", "year": "2010" }, { "name": "Jack", "year": "2005" }, { "name": "Tony", "year": "2008" }, { "name": "Max", "year": "2005" }]; var map={} for (var i = 0; i<array.length;i++){ if ( !map[ array [ i ].year ] ){ map[ array [ i ].year ] = 0; } map[ array [ i ].year] ++; } console.log( map ); Fiddle A: Here arrange uses reduce to build an object using the years as keys. It accepts a prop argument so that you can build the object as you see fit. function arrange(arr, prop) { return arr.reduce(function(p, c) { var key = c[prop]; p[key] = p[key] || 0; p[key]++; return p; }, {}); } You can then iterate over the key/values of that object and print out the results for year: var obj = arrange(array, 'year'); for (var p in obj) { console.log(p + ' = ' + obj[p] + ' times'); } Or even by name: var obj = arrange(array, 'name'); DEMO A: You are trying to re-invent the wheel. This and many more methods are exposed by a third-party JS library, called "lodash"; old name was "underscore". All its methods or most of them are exposed like _.methodName(listName, iteratorFunction) You can download it at: https://lodash.com/ Once you download and include lodash your script in your html, go to your function and do: _.groupBy(yourArrayVariable, function(item){ return item.year; }); WARNING This method will not return an array. It will return a JSON, in which the keys are represented by the "item.year" through the whole original array, and the values will be an array for each year listed. Every such array is a list of objects having the same "year" value: { "2010" : [ { "name" : "Tony", "year" : "2010" }, { "name" : "Helen", "year" : "2010" } ], "2011" : [ ..... ] } Lodash has lots of useful methods anyway. A: var array = [{ "name": "Tony", "year": "2010" }, { "name": "Helen", "year": "2010" }, { "name": "Jack", "year": "2005" }, { "name": "Tony", "year": "2008" }, { "name": "Max", "year": "2005" }]; var result = {}; array.forEach(function(data) { console.log(data.year); result[data.year] = result[data.year] ? ++result[data.year] : 1; }); document.write(JSON.stringify(result));
unknown
d14236
val
You can do like.. <asp:TemplateField> <ItemTemplate> <asp:Button ID="btnChange" runat="server" Text="Change" Visible='<%# (Boolean) Eval("Change") %>' /> </ItemTemplate> </asp:TemplateField> As you mentioned in the comment you are getting error on the above code, you try like... Visible='<%# Convert.ToBoolean(Eval("Change")) == true ? true : false %>'
unknown
d14237
val
I would fix your error. The general design guideline is indeed the (object sender, EventArgs e) signature. It's a convention and is all about code consistency, code readability...etc. Following this pattern will help other people attaching handlers to your events. Some general tips/answers: * *For a static event, you should indeed use null as sender (because there is no sender instance per definition). *If you have nothing to pass for the e parameter, use EventArgs.Empty instead of new EventArgs() or null. *You could use EventHandler and EventHandler<T> to simplify the definition of your events. *For the sake of simplicity, you could use a custom EventArgs<T> class inheriting from EventArgs if you want to pass a single value to your event handler. If you want to use the singleton pattern with a Lazy<T> definition, here's a complete example. Do note no event is static, so the sender parameter contains a reference to the singleton instance: public class EventArgs<T> : EventArgs { public EventArgs(T value) { this.Value = value; } public T Value { get; set; } } public class EventArgs2 : EventArgs { public int Value { get; set; } } internal static class Program { private static void Main(string[] args) { Singleton.Instance.MyEvent += (sender, e) => Console.WriteLine("MyEvent with empty parameter"); Singleton.Instance.MyEvent2 += (sender, e) => Console.WriteLine("MyEvent2 with parameter {0}", e.Value); Singleton.Instance.MyEvent3 += (sender, e) => Console.WriteLine("MyEvent3 with parameter {0}", e.Value); Singleton.Instance.Call(); Console.Read(); } } public sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } /// <summary> /// Prevents a default instance of the <see cref="Singleton"/> class from being created. /// </summary> private Singleton() { } /// <summary> /// Event without any associated data /// </summary> public event EventHandler MyEvent; /// <summary> /// Event with a specific class as associated data /// </summary> public event EventHandler<EventArgs2> MyEvent2; /// <summary> /// Event with a generic class as associated data /// </summary> public event EventHandler<EventArgs<int>> MyEvent3; public void Call() { if (this.MyEvent != null) { this.MyEvent(this, EventArgs.Empty); } if (this.MyEvent2 != null) { this.MyEvent2(this, new EventArgs2 { Value = 12 }); } if (this.MyEvent3 != null) { this.MyEvent3(this, new EventArgs<int>(12)); } Console.Read(); } } EDIT: You could also build some EventArgs<T1, T2> if you need to pass two values. Ultimately, EventArgs<Tuple<>> would also be possible, but for more than 2 values I would build a specific XXXEventArgs class instead as it's easier to read XXXEventArgs.MyNamedBusinessProperty than EventArgs<T1, T2, T3>.Value2 or EventArgs<Tuple<int, string, bool>>.Value.Item1. Regarding KISS/YAGNI: remember the (object sender, EventArgs e) convention is all about code consistency. If some developer uses your code to attach an handler to one of your events, I can assure you he will just love the fact that your event definition is just like any other event definition in the BCL itself, so he instantly knows how to properly use your code. There even are others advantages than just code consistency/readability: I inherited my custom XXXEventArgs classes from EventArgs, but you could build some base EventArgs class and inherit from it. For instance, see MouseEventArgs and all classes inheriting from it. Much better to reuse existing classes than to provide multiple delegate signatures with 5/6 identical properties. For instance: public class MouseEventArgs : EventArgs { public int X { get; set; } public int Y { get; set; } } public class MouseClickEventArgs : MouseEventArgs { public int ButtonType { get; set; } } public class MouseDoubleClickEventArgs : MouseClickEventArgs { public int TimeBetweenClicks { get; set; } } public class Test { public event EventHandler<MouseClickEventArgs> ClickEvent; public event EventHandler<MouseDoubleClickEventArgs> DoubleClickEvent; } public class Test2 { public delegate void ClickEventHandler(int X, int Y, int ButtonType); public event ClickEventHandler ClickEvent; // See duplicated properties below => public delegate void DoubleClickEventHandler(int X, int Y, int ButtonType, int TimeBetweenClicks); public event DoubleClickEventHandler DoubleClickEvent; } Another point is, using EventArgs could simplify code maintainability. Imagine the following scenario: public MyEventArgs : EventArgs { public string MyProperty { get; set; } } public event EventHandler<MyEventArgs> MyEvent; ... if (this.MyEvent != null) { this.MyEvent(this, new MyEventArgs { MyProperty = "foo" }); } ... someInstance.MyEvent += (sender, e) => SomeMethod(e.MyProperty); In case you want to add some MyProperty2 property to MyEventArgs, you could do it without modifying all your existing event listeners: public MyEventArgs : EventArgs { public string MyProperty { get; set; } public string MyProperty2 { get; set; } } public event EventHandler<MyEventArgs> MyEvent; ... if (this.MyEvent != null) { this.MyEvent(this, new MyEventArgs { MyProperty = "foo", MyProperty2 = "bar" }); } ... // I didn't change the event handler. If SomeMethod() doesn't need MyProperty2, everything is just fine already someInstance.MyEvent += (sender, e) => SomeMethod(e.MyProperty);
unknown
d14238
val
You can use session, before returning prescriptions/create page you can do Session::flash('script_id', $script_id); and when user submits prescription creation just take it $script_id = Session::get('script_id');
unknown
d14239
val
You need to add your changes into theme. I found carousel by the path themes/copper/layouts/partials/testimonial.html: <!-- start of brand-carousel --> {{ if $data.homepage.clients_logo_slider.enable }} {{ with $data.homepage.clients_logo_slider }} <section class="section-padding bg-white overflow-hidden"> <div class="container"> <div class="row justify-content-center"> <div class="col-lg-6 col-md-9 text-center mb-30"> <span class="section-title fw-extra-bold fs-36">{{ .title | markdownify }}</span> </div> </div> <div class="row"> <div class="col-md-12" data-aos="fade-left"> <div class="brand-carousel"> {{ range .logos }} <div class="brand-item d-flex align-items-center justify-content-center"> <img class="img-fluid" src="{{ . |absURL}}" alt=""></div> {{ end }} </div> </div> </div> </div> </section> {{ end }} {{ end }} <!-- end of brand-carousel --> Here I see css class <div class="brand-carousel"> And logic I found by the path themes/copper/assets/js/script.js: // brandCarousel fix function brandCarousel() { $('.brand-carousel').slick({ dots: false, arrows: false, infinite: true, speed: 500, autoplay: true, autoplaySpeed: 3000, mobileFirst: true, slidesToScroll: 1, responsive: [{ ... So, function brandCarousel() take div with class .brand-carousel and make it slick. I didn't check it, but I recommend you try to change some of this option, and start with autoplaySpeed.
unknown
d14240
val
List cannot be "painted". Please use the following instead: List of items: ForEach(items) { item in HStack { Text(item) } }.background(Color.red) Scrollable list of items: ScrollView { ForEach(items) { item in HStack { Text(item) } }.background(Color.red) } In your case: VStack { // or HStack for horizontal alignment Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) } }.background(Color.red) A: Using UITableView.appearance().backgroundColor can affect the background colour of all List controls in the app. If you only want one particular view to be affected, as a workaround, you can set it onAppear and set it back to the default onDisappear. import SwiftUI import PlaygroundSupport struct PlaygroundRootView: View { @State var users: [String] = ["User 1", "User 2", "User 3", "User 4"] var body: some View { Text("List") List(users, id: \.self){ user in Text(user) } .onAppear(perform: { // cache the current background color UITableView.appearance().backgroundColor = UIColor.red }) .onDisappear(perform: { // reset the background color to the cached value UITableView.appearance().backgroundColor = UIColor.systemBackground }) } } PlaygroundPage.current.setLiveView(PlaygroundRootView()) A: You can provide a modifier for the items in the list NavigationView { ZStack { Color("AppBackgroundColor").edgesIgnoringSafeArea(.all) List { Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) .listRowBackground(Color.blue) // << Here } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) .listRowBackground(Color.green) // << And here } }.listStyle(.grouped) } } A: For SwiftUI on macOS this works : extension NSTableView { open override func viewDidMoveToWindow() { super.viewDidMoveToWindow() // set the background color of every list to red backgroundColor = .red } } It will set the background color of every list to red (in that example). A: iOS 16 Since Xcode 14 beta 3, You can change the background of all lists and scrollable contents using this modifier: .scrollContentBackground(.hidden) You can pass in .hidden to make it transparent. So you can see the color or image underneath. iOS 15 and below All SwiftUI's Lists are backed by a UITableView (until iOS 16). so you need to change the background color of the tableView. You make it clear so other views will be visible underneath it: struct ContentView: View { init(){ UITableView.appearance().backgroundColor = .clear } var body: some View { Form { Section(header: Text("First Section")) { Text("First cell") } Section(header: Text("Second Section")) { Text("First cell") } } .background(Color.yellow) } } Now you can use Any background (including all Colors) you want Note that those top and bottom white areas are the safe areas and you can use the .edgesIgnoringSafeArea() modifier to get rid of them. Also note that List with the .listStyle(GroupedListStyle()) modifier can be replaced by a simple Form. But keep in mind that SwiftUI controls behave differently depending on their enclosing view. Also you may want to set the UITableViewCell's background color to clear as well for plain tableviews A: Easiest way to do this for now is just to use UIAppearance proxy. SwiftUI is young so there's a couple of features not fully implemented correctly by Apple yet. UITableView.appearance().backgroundColor = .red A: @State var users: [String] = ["User 1", "User 2", "User 3", "User 4"] init(){ UITableView.appearance().backgroundColor = .red UITableViewCell.appearance().backgroundColor = .red UITableView.appearance().tableFooterView = UIView() } var body: some View { List(users, id: \.self){ user in Text(user) } .background(Color.red) } PlaygroundPage.current.liveView = UIHostingController(rootView: ContentView()) A: A bit late to the party, but this may help. I use a combination of: * *Setting the UITableView.appearance appearance *Setting the UITableViewCell.appearance appearance *Settings the List listRowBackground modifier. Setting the appearance affects the entire app, so you may want to reset it to other values where applicable. Sample code: struct ContentView: View { var body: some View { let items = ["Donald", "Daffy", "Mickey", "Minnie", "Goofy"] UITableView.appearance().backgroundColor = .clear UITableViewCell.appearance().backgroundColor = .clear return ZStack { Color.yellow .edgesIgnoringSafeArea(.all) List { Section(header: Text("Header"), footer: Text("Footer")) { ForEach(items, id: \.self) { item in HStack { Image(systemName: "shield.checkerboard") .font(.system(size: 40)) Text(item) .foregroundColor(.white) } .padding([.top, .bottom]) } .listRowBackground(Color.orange)) } .foregroundColor(.white) .font(.title3) } .listStyle(InsetGroupedListStyle()) } } } A: since, you are asking for changing the background color of view, you can use .colorMultiply() for that. Code: var body: some View { VStack { ZStack { List { Section(header: Text("Now in theaters")) { Text("Row1") } Section(header: Text("Popular movies")) { Text("Row2") } /*Section(header: Text("Now in theaters")) { ScrollMovies(type: .currentMoviesInTheater) } Section(header: Text("Popular movies")) { ScrollMovies(type: .popularMovies) } */ }.listStyle(.grouped) }.colorMultiply(Color.yellow) } } Output:
unknown
d14241
val
Assuming you want to get all the builder/client pairs that only have a single builder_for relationship between them, this query uses the aggregating function COUNT to do that: MATCH (builder:Person)-[rel:builder_for]->(client:Person) WITH builder, client, COUNT(rel) AS rel_count WHERE rel_count = 1 RETURN builder, client; [UPDATE] If, instead, you want builder/client pairs in which the builder has only that one client, and vice versa, then this query should work: MATCH (builder:Person) WHERE SIZE((builder)-[:builder_for]->()) = 1 MATCH (builder)-[:builder_for]->(client:Person) WHERE SIZE(()-[:builder_for]->(client)) = 1 RETURN builder, client; This query uses efficient relationship degree-ness checks (in the WHERE clauses) to ensure that the builder and client nodes only have, respectively, a single outgoing or incoming builder_for relationship.
unknown
d14242
val
trials=3 while trials!=0: account= int(input(" PLEASE INPUT YOUR ACCOUNT NUMBER: ")) pin = int(input(" PLEASE INPUT YOUR 5 DIGIT PIN: ")) correct_pin= valid_pins[valid_accounts.index(account)] if (account not in valid_accounts) or (pin!=correct_pin): print(" INVALID LOGIN DETAILS. ") trials= trials-1 print(" YOU HAVE ", trials, " TRIALS LEFT") elif (account in valid_accounts) and (pin==correct_pin): print("Welcome") break But the program will have some uncovered cases still * *If the inputted account is not in the account list you'll get ValueError. *Converting input() into int() immediately is not a very good practice. if a string is inputted you'll get a ValueError. Edit: trials=3 while trials!=0: try: # Check if the input is convertible to int() account= int(input(" PLEASE INPUT YOUR ACCOUNT NUMBER: ")) pin = int(input(" PLEASE INPUT YOUR 5 DIGIT PIN: ")) if account in valid_accounts: # Create correct_pin only after making sure that the account is in valid_accounts. # Otherwise .index() will not work correct_pin= valid_pins[valid_accounts.index(account)] # You need to check the correct pin only when the account is valid # Makes no sence to check the pin if there is no such account. if (pin==correct_pin): print("Welcome") break else: # Pin is either correct or not. Else is more suitable than elif. print(" INVALID LOGIN DETAILS. ") trials -= 1 print(" YOU HAVE ", trials, " TRIALS LEFT") else: # Account is either valid or not. Else is more suitable than elif. print(" INVALID LOGIN DETAILS. ") trials -= 1 print(" YOU HAVE ", trials, " TRIALS LEFT") except ValueError: print(" PLEASE INPUT ONLY INTEGERS")
unknown
d14243
val
Have you initialized the modal with javascript? All you need is JQuery, the bootstrap CSS file, and the bootstrap JS file. Then add this code in a <script> tag at the bottom of your page! $(document).ready(function () { $('#myModal').modal(); }); A: ** Fixed just putting this here to close it ;D i used the wrong CDN
unknown
d14244
val
Using you code the solution is #include<stdio.h> #include<conio.h> int main() { int n=5,r=1,c=1,i=1,mid=0; int maxRow = n; if(n%2==0){ mid=(n/2); maxRow--; } else mid=(n/2)+1; printf("mid = %d\n",mid); while(r<=maxRow) { while(c<=n) { printf("%d ",i); c++; i++; } r++; if(r<=mid) i=i+n; else if (r >= n) i=n+1; else i=i-((1+(r-mid))*n); printf("\n"); c=1; } getch(); return 0; } As you can see: * *the i=i-(2*n); is changed. What you wrote wasn't generic, but specific for the n=3 case. *I added else if (r >= n). *Last thing you must use a specific variable for the outer while because of n must be decremented if n is even. Some tips: * *Give to your variables explanatory names *To make your code more readable declare variables 1 per line, if you want to init them. *Live empty lines between code chunks. int main () { int squareDim=5; int row=1; int col=1; int valueToPrint=1; int mid=0; int maxRow = squareDim; if(squareDim%2==0) { mid=(squareDim/2); maxRow--; } else { mid=(squareDim/2)+1; } printf("mid = %d\n",mid); while(row<=maxRow) { while(col<=squareDim) { printf("%d ",valueToPrint); col++; valueToPrint++; } row++; if(row<=mid) { valueToPrint=valueToPrint+squareDim; } else if (row >= squareDim) { valueToPrint=squareDim+1; } else { valueToPrint=valueToPrint-((1+(row-mid))*squareDim); } printf("\n"); col=1; } return 0; }
unknown
d14245
val
It must be name of your app. By default the Actionbar (the blue bar) might show the name of your app. You may get rid of the ActionBar from page-router-outlet by setting actionBarVisibility attribute to never <page-router-outlet actionBarVisibility="never"></page-router-outlet>
unknown
d14246
val
To get a confusion matrix you need to make predictions on the test set. Then you need to provide the predicted values and the associated true values to the confusion matrix. Note -- in your code for the test_dataset you MUST set shuffle=False in flow_from_directory!! Code below should generate an adaptable confusion matrix plot and classification report. model is your trained model. import numpy as np import matplotlib.pyplot as plt from matplotlib.pyplot import imshow import seaborn as sns sns.set_style('darkgrid') def cm_cr(test_gen, model): preds=model.predict(test_gen) labels=test_gen.labels classes=list(test_gen.class_indices.keys()) # ordered lst of class names pred_list=[ ] # will store the predicted classes here true_list=[] for i, p in enumerate (preds): index=np.argmax(p) pred_list.append(classes[index]) true_list.append(classes[labels[i]]) y_pred=np.array(pred_list) y_true=np.array(true_list) clr = classification_report(y_true, y_pred, target_names=classes) print("Classification Report:\n----------------------\n", clr) cm = confusion_matrix(y_true, y_pred ) length=len(classes) if length<8: fig_width=8 fig_height=8 else: fig_width= int(length * .5) fig_height= int(length * .5) plt.figure(figsize=(fig_width, fig_height)) sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False) plt.xticks(np.arange(length)+.5, classes, rotation= 90, fontsize=16) plt.yticks(np.arange(length)+.5, classes, rotation=0, fontsize=16) plt.xlabel("Predicted") plt.ylabel("Actual") plt.title("Confusion Matrix") plt.show() cm_cr(test_dataset, model) I did not do the ROC curve but there is a good tutorial here for that activity.
unknown
d14247
val
Android have deprecated it because they want you to use your application theme colors rather then using android native colors. You can find your application theme colors in the following path: project/app/res/values/colors.xml in that file you will have few colors declared already like: <color name="colorPrimary">#2196f3</color> <color name="colorPrimaryDark">#1976d2</color> <color name="colorPrimaryLight">#B3E5FC</color> <color name="colorAccent">#03A9F4</color> <color name="primary_text">#212121</color> <color name="secondary_text">#757575</color> <color name="icons">#FFFFFF</color> <color name="divider">#BDBDBD</color> So have to use these colors now. If you want to change the color value just change the value and you can have your desired color.
unknown
d14248
val
There is a difference between the path structure in HTTP and in the file system. PHP knows nothing about the defined alias for HTTP access. You have to define the path to the files in a way that the file system understands. Which probably means to use $download_dir = "H:/Filme/";
unknown
d14249
val
You set ndata to be sizeof(int32_t) which is 4. Your ndata is passed as len argument to TF_NewTensor() which represents the number of elements in data (can be seen in GitHub). Therefore, it should be set to 1 in your example, as you have a single element. By the way, you can avoid using malloc() here (as you don't check for return values, and this may be error-pront and less elegant in general) and just use local variables instead. UPDATE In addition, you pass NULL both for deallocator and deallocator_arg. I'm pretty sure this is the issue as the comment states "Clients must provide a custom deallocator function..." (can be seen here). The deallocator is called by the TF_NewTensor() (can be seen here) and this may be the cause for the segmentation fault. So, summing it all up, try the next code: void my_deallocator(void * data, size_t len, void * arg) { printf("Deallocator called with data %p\n", data); } void main() { int64_t dims[] = { 1 }; int32_t data[] = { 10 }; ... = TF_NewTensor(TF_INT32, dims, /*num_dims=*/ 1, data, /*len=*/ 1, my_deallocator, NULL); }
unknown
d14250
val
You can unpivot this using CROSS APPLY (VALUES SELECT t.Hospital, t.Zip, v.Year, v.Paid$, v.Visits, v.LOS FROM [MyTable] T CROSS APPLY (VALUES (2021, Paid$_21, Visits21, LOS21), (2022, Paid$_22, Visits22, LOS22) ) v(Year, Paid$, Visits, LOS) Note that this only queries the base table once. db<>fiddle A: SELECT Hospital, Zip, '2021' As Year, Paid$_21 As Paid$, Visits21 as Visits, LOS21 as LOS FROM [MyTable] UNION SELECT Hospital, Zip, '2022' As Year, Paid$_22 As Paid$, Visits22 as Visits, LOS22 as LOS FROM [MyTable] You can also try UNPIVOT
unknown
d14251
val
You may consider matching what you want instead of replacing the characters you do not want. The following will match word characters and hyphen both inside and outside of curly braces. $str = 'aaa.{foo}-{bar} dftgyh {foo-bar}{bar} .? {.!} -! a}aaa{'; preg_match_all('/{[\w-]+}|[\w-]+/', $str, $matches); echo implode('', $matches[0]); Output as expected: aaa{foo}-{bar}dftgyh{foo-bar}{bar}-aaaa A: Also an option to (*SKIP)(*F) the good stuff and do a preg_replace() with the remaining: $str = preg_replace('~(?:{[-\w]+}|[-\w]+)(*SKIP)(*F)|.~' , "", $str); test at regex101; eval.in
unknown
d14252
val
By looking at the site that you have provided, There is container class in media query that has the height: 100vh; property, which is causing this issue. .container { width: 100%; height: 100vh; /* background:wheat; */ } Either remove that class from media query or change to .container { width: 100%; } This will solve your problem.
unknown
d14253
val
Have you already looked at the IMCE module? IMCE is an image/file uploader and browser that supports personal directories and quota. https://drupal.org/project/imce
unknown
d14254
val
It returns nothing because function is not set to return anything. Last line should be: KeyNo = Mid(RandomString, 3, intLen * 2) A: As @June7 correctly notes in their answer, the reason that your function does not return anything is because the symbol KeyNo is initialised as a null string ("") by virtue of the fact that the function is defined to return a string (Function KeyNo ... As String), however, you don't redefine KeyNo to anything else within the function, hence, the function will always return an empty string. However, for the task that you have described: I want to be able to update the field RanKeyNo5 with the numeric equivalent (2 digits) for a specified number of letters as they occur in the Ran field. The code could be greatly simplified - for example, consider the following approach: Function KeyNo(strStr As String, intLen As Integer) As String Dim i As Integer Dim a As Integer For i = 1 To Len(strStr) a = Asc(Mid(strStr, i, 1)) - 64 If a <= intLen Then KeyNo = KeyNo & Format(a, "00") Next i End Function ?KeyNo("BFHCIEALGJDK",5) 0203050104
unknown
d14255
val
It is possible to merge in chunks (batches) in SQL. You need to * *limit the number of rows from the temp table in each chunk *delete those same rows *repeat The SELECT statement should use an ORDER BY and LIMIT SELECT word1, word2, distance, distcount FROM tempcach ORDER BY primary key or unique columns LIMIT 1000 ) AS src ( After the merge, the delete statement will select the same rows to delete DELETE FROM tempcach WHERE primary key or unique columns IN (SELECT primary key or unique columns FROM tempcach ORDER BY primary key or unique columns LIMIT 1000) A: First, just because this kind of thing annoys me, why are you selecting all the fields of the temporary table in a subselect? Why not the simpler SQL: MERGE INTO Alldistances alld USING tempcach AS src ( newword1, newword2, newdistance, newcount ) ON ( alld.word1 = src.newword1 AND alld.word2 = src.newword2 AND alld.distance = src.newdistance ) WHEN MATCHED THEN UPDATE SET alld.distcount = alld.distcount+src.newcount WHEN NOT MATCHED THEN INSERT ( word1, word2, distance, distcount ) VALUES ( newword1, newword2, newdistance, newcount ); What you need to have the database avoid loading the whole table into memory is indexing on both tables. CREATE INDEX all_data ON Alldistances (word1, word2, distance); CREATE INDEX tempcach_data ON tempcach (word1, word2, distance);
unknown
d14256
val
ads.facebook.com->webform.example.com->www.example.com/subsite1/ User B: ads.facebook.com->webform.example.com->www.example.com/subsite2/ User C: ads.facebook.com->webform.example.com->www.example.com/subsite6/ User D: ads.facebook.com->webform.example.com->www.example.com/subsite1/ So for all sub-sites we have created Google analytics views in a single account Like: Webform view for:webform.example.com Sub-site1 view for:www.example.com/subsite1/ Sub site2 view for:www.example.com/subsite2/ etc. On “Webform” View: We are able to calculate the user who comes from facebook Ads using Google analytic Gols through referrers etc. On “subsite1” view: We are able to calculate how many user comes from survey web forms to sub-site using Google analytic Gols through referrers etc. The Issue is: We need to calculate the user who comes from facebook to survey site and then reached to each sub-site.Any Idea how it could be achieve? Umair
unknown
d14257
val
You can instead specify rowTag as nt:vars: df = spark.read.format("xml").option("rowTag","nt:vars").load("file.xml") df.printSchema() root |-- nt:var: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- _VALUE: string (nullable = true) | | |-- _id: string (nullable = true) | | |-- _type: string (nullable = true) df.show(truncate=False) +-------------------------------------------------------------------------------------------+ |nt:var | +-------------------------------------------------------------------------------------------+ |[[ 89:19:00.01, 1.3.0, TimeStamp], [1.9.5.67.2, 1.3.1, OBJECT ], [AB-CD-EF, 1.3.9, STRING]]| +-------------------------------------------------------------------------------------------+ And to get the values as separate rows, you can explode the array of structs: df.select(F.explode('nt:var')).show(truncate=False) +--------------------------------+ |col | +--------------------------------+ |[ 89:19:00.01, 1.3.0, TimeStamp]| |[1.9.5.67.2, 1.3.1, OBJECT ] | |[AB-CD-EF, 1.3.9, STRING] | +--------------------------------+ Or if you just want the values: df.select(F.explode('nt:var._VALUE')).show() +------------+ | col| +------------+ | 89:19:00.01| | 1.9.5.67.2| | AB-CD-EF| +------------+
unknown
d14258
val
Here is an example for how to create dynamic web service client with apache cxf, avoid the "no operation found for name" unchecked exception and use authentication. DynamicClientFactory dcf = DynamicClientFactory.newInstance(); Client client = dcf.createClient("WSDL Location"); AuthorizationPolicy authorization = ((HTTPConduit) client.getConduit()).getAuthorization(); authorization.setUserName( "user name" ); authorization.setPassword( "password" ); Object[] res = client.invoke(new QName("http://targetNameSpace/", "operationName"), params...); System.out.println("Echo response: " + res[0]); the new QName with the name space fixed the exception. Enjoy.
unknown
d14259
val
<td style="text-align:center;"> <% if my_data.last_status_update.blank? %> &nbsp; - &nbsp; <% else %> <%=h my_data.last_status_update.strftime("%m-%d-%Y @ %H:%M CST") %> <% end %> </td> <% if !my_data.last_status_update.blank? && my_data.last_status_update.year == Time.now.year && my_data.last_status_update.day == Time.now.day && my_data.last_status_update.hour >= 5 %> <td style="text-align:center;background:#90ee90"> YES </td> <% else %> <td style="text-align:center;background:#ff9999"> EXPIRED! </td> <% end %> A: I have never player with the Time method, but I guess you could check the rails API : http://corelib.rubyonrails.org/classes/Time.html. You could play with Time.at.
unknown
d14260
val
Do you set your browser local language in Control Panel like below in win 7? In this situation, we can get local language in IE 11 using window.navigator.browserLanguage which is "fr-FR". In other modern browsers, we can only use window.navigator.language: In your app, you could use the code below: var sAgent = window.navigator.userAgent; var Idx = sAgent.indexOf("Trident"); //check if IE 11 if (Idx > 0) { this.lang = window.navigator.browserLanguage; } else { this.lang = window.navigator.language; }
unknown
d14261
val
This appears to be a defect in the new 4.0 version of Select2, which is still in beta. jsfiddle With v3.5.2, the following line in the updateResults function prevents the unnecessary ajax calls: // prevent duplicate queries against the same term if (initial !== true && lastTerm && equal(term, lastTerm)) return; jsfiddle Here's a somewhat related issue. At least, I think both issues could be fixed at the same time. You may want to add a comment to that issue.
unknown
d14262
val
This worked for me, can you give some more information about what sort of error you are encountering? We get the parent directly from the entry and simply place the folder with a new name under the same parent. Take note that this will fail, with an invalidmodification error if the new name is the same as the old, even if you change the caps in the name. var test = function( entry, new_name ){ entry.getParent( function( parent ){ entry.moveTo( parent , new_name, function( new_node ){ console.log( new_node ) console.log( "Succes creating the new node" ) //We were able to rename the node }, function( error ){ console.error( error ) console.error( "Something wrong when finding the parent" ) }) }, function( error ){ console.error( error ) console.error( "Something wrong when finding the parent" ) }) } test( entry, "For the watch" )
unknown
d14263
val
Edit: This is an outdated answer. see @Javier answer below as pointed out by @ondrejsv on comment. It does not work anymore at least in Vuetify 2.1.9 and Vue 2.6.x. The solution by Javier seems to work. Increase the z-index style property of your dialog. <v-dialog style="z-index:9999;" ... rest of your code ... A: I find it quite practical to wrap the map in an image, like this <v-img height="100%" width="100%"> <l-map> ... </l-map> </v-img> This way there is no need to do anything with the z-index. A: The problem is a clash of z-index ranges. Vuetify uses z-index ranges 0-10 while leaflet uses the range 100-1100. Fortunately, the z-index of a child element is relative to the z-index of their parent. I advice you to give l-map a z-index of 0 like this. <l-map :center="center" :zoom="zoom" @click.right="mapRclicked" ref="map" style="z-index: 0; height: 50vh; width: 50vh" > This will automatically bring your component in line with all of Vuetify z-indexes. In contrast, @bgsuello workaround requires that you modify the z-index of every Vuetify component that may conflict with the map, including other dialogs, menus, animations, tabs, toolbars, snackbars... A: I am on Vue2.x + Vuetify + Vue2leaflet. I tried many things and finally what worked for me was to cover the with a . My code reads as : <v-lazy> <v-img> <l-map> .... rest of the code </l-map> </v-img> </v-lazy> This takes inputs on v-lazy from https://medium.com/@elralimi.lamia/leaflet-vuejs-vuetify-map-not-showing-well-in-a-modal-with-grey-parts-9a5d551ea472. v-img was suggested by geomuc in the above response. Other options that I tried but failed were: this.map.invalidateSize(); , this.map.remove();, this.$nextTick(() => {...}, z-index.
unknown
d14264
val
This can be done with a clever combinartion of _.map and _.groupBy. const items = [ { tab: 'Results', section: '2017', title: 'Full year Results', description: 'Something here', }, { tab: 'Results', section: '2017', title: 'Half year Results', description: 'Something here', }, { tab: 'Reports', section: 'Marketing', title: 'First Report', description: 'Something here', } ]; function groupAndMap(items, itemKey, childKey, predic){ return _.map(_.groupBy(items,itemKey), (obj,key) => ({ [itemKey]: key, [childKey]: (predic && predic(obj)) || obj })); } var result = groupAndMap(items,"tab","sections", arr => groupAndMap(arr,"section", "items")); console.log(result); <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> A: You could use an object without additional libraries. The object contains a property _ which keeps the nested arrays of the given nested group. var items = [{ tab: 'Results', section: '2017', title: 'Full year Results', description: 'Something here' }, { tab: 'Results', section: '2017', title: 'Half year Results', description: 'Something here' }, { tab: 'Reports', section: 'Marketing', title: 'First Report', description: 'Something here' }], keys = { tab: 'sections', section: 'items' }, // or more if required result = [], temp = { _: result }; items.forEach(function (object) { Object.keys(keys).reduce(function (level, key) { if (!level[object[key]]) { level[object[key]] = { _: [] }; level._.push({ [key]: object[key], [keys[key]]: level[object[key]]._ }); } return level[object[key]]; }, temp)._.push({ title: object.title, description: object.description }); }); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }
unknown
d14265
val
Just use: <% response.sendError(...); %> The <% ... %> delimiters already execute code directly.
unknown
d14266
val
Your example repository is lacking a branch-c, so it's not a complete MCVE, but it's a good start :) When I clone the above repo using git clone --recurse-submodules <URL> only the submodule-a and submodule-b submodules get initialised and cloned. Yes, this is the current behaviour of git clone --recurse-submodules. The submodules are cloned and initialized using an invocation of git submodule update --init --recursive during the checkout phase of git clone, and as such, only submodules recorded in the default branch (or the branch specified using git clone -b <branch>) are cloned and initialized. When I then want to check out branch branch-c using git checkout branch-c, the directory for submodule-c gets created, but the submodule itself is not initialised. There is no indication in the command output that some additional steps are needed. Neither git status nor git diff give any hint. Yes, this is unfortunately still the default behaviour of Git. Submodules working trees are not checked out by default by git checkout <branch>. git submodule status (or just git submodule) will show uninitialized submodules with a - prefixed. When instead I want to check out branch-c using git checkout --recurse-submodules branch-c I get an error: fatal: not a git repository: ../../.git/modules/subrepos/subrepo-c fatal: could not reset submodule index This is a good reflex but unfortunately it does not work in that specific case and leads to this bad UX. git checkout --recurse-submodules <branch> assumes that every submodule recorded in branch-c are already initialized. Since that's not the case here, it errors out because it can't find the .git directory of the submodule. The message could be clearer. What you have to do (the first time you switch to branch-c after cloning your repository) is to check out branch-c non-recursively, and then initialize the submodule: git checkout branch-c git submodule update --init --recursive Then, you will be able to correctly switch between your branches with --recurse-submodules: git checkout --recurse-submodules main git checkout --recurse-submodules branch-c # etc Note that you can set submodule.recurse in your config to avoid having to use --recurse-submodules all the time.
unknown
d14267
val
I'm not aware of a general approach in C++ but assuming you have a fixed set of derived classes, you can actually deal with the situation using an extra indirection: class BarbWireFence; class WoodenFence; class Fence { public: virtual void add(Fence& fence) = 0; virtual void add(BarbWireFence& fence) = 0; virtual void add(WoodenFence& fence) = 0; }; class BarbWireFence { void add(Fence& fence) override { fence.add(*this); } void add(BarbWireFence& fence) override; // deal with the actual addition void add(WoodenFence& fence) override; // deal with the actual addition }; class WoodenFence { void add(Fence& fence) override { fence.add(*this); } void add(BarbWireFence& fence) override; // deal with the actual addition void add(WoodenFence& fence) override; // deal with the actual addition }; A: Welcome to the wonderful world of binary methods. There is no satisfactory solution to this problem. You may want to learn about double dispatch and its more formal sibling the Visitor pattern. These two things are basically the same, only presented a bit differently. In the most simplistic scenario you do this: class WoodenFence; class BarbWireFence; class Fence { public: virtual void addFence(const Fence& fence) = 0; virtual void addMe(BarbWireFence& fence) const = 0; virtual void addMe(WoodenFence& fence) const = 0; ... }; class BarbWireFence : public Fence { public: ... void addFence(const Fence& fence) { fence->addMe(*this); } void addMe(BarbWireFence& fence) const { fence->addBarbWireFence(*this); } void addMe(WoodenFence& fence) const { throw error("bad fence combo"); } void addBarbWireFence(const BarbWireFence& fence) { // actually add fence... } }; class WoodenFence : public Fence { public: ... void addFence(const Fence& fence) { fence->addMe(*this); } void addMe(BarbWireFence& fence) const { throw error("bad fence combo"); } void addMe(WoodenFence& fence) const { fence->addWoodenFenceFence(*this); } void addWoodenFence(const WoodenFence& fence) { // actually add fence... } ... }; You can figure out what should happen when you add 10 other fence types. There's a totally different direction one might take, namely, templatize the entire business and get rid of the Fence base class, as it doesn't provide a type-safe interface. class BarbWireFence { public: ... void addSimilarFence(const BarbWireFence& fence) { //continue the fence with the given one } }; class WoodenFence { public: ... void addSimilarFence(const WoodenFence& fence) { //continue the fence with the given one } }; template <typename Fence> void addFence (Fence& f1, const Fence& f2) { f1->addSimilarFence(f2); }
unknown
d14268
val
The documentation for MessageAction explains: When updating a Message, unset fields will be ignored by default. To override existing fields with no value (remove content) you can use override(true). Setting this to true will cause all fields to be considered and will override the Message entirely causing unset values to be removed from that message. This can be used to remove existing embeds from a message: message.editMessage("This message had an embed").override(true).queue()
unknown
d14269
val
If you have an List with different object that can be of different kinds and need different views to display. Do it that way: Let the object define the view by themselves. Implement an interface ViewProvider on every object. This interface should provide the method getView() which then can be called in the adapter. The adapter has now only to get the element out of the list full of ViewProviders and call the method getView to get the view. You will not have to worry about the recycling off the views as the views are stored in every ViewProvider and will be created only once. The update of the fields (if any) can then also be made on the Object side and not in the adapter. But you have to notify the adapter about the data change by calling notifyDataSetChanged()
unknown
d14270
val
Is there any code of facebook that we can get picture and public information of the user without graph api and facebook app? No. The Graph API is the basis of any automated communication with Facebook’s systems, and an app id is the basis of using the API. Cz now facebook need https to make a app. Rightfully so. You should not compromise your users’ security and privacy by not using HTTPS any more these days, especially if any kind of “login” is involved. Getting a certificate doesn’t have to cost you much any more - Let’s Encrypt is widely available.
unknown
d14271
val
You should hold on the basic communication paradigms when sending/receiving data from/to a DB. In your case you need to pass data to a DB via web and application. Never, ever let an app communicate with your DB directly! So what you need to do first is to implement a wrapper application to give controlled access to your DB. Thats for example often done in PHP. Your PHP application then offers the interfaces by which external applications (like your FFOS app) can communicate with the DB. Since this goes to very basic programming knowledge, please give an idea of how much you know about programming at all. I then consider offering further details. A: You can use a local database in JS, e.g. PouchDB, TaffyDB, PersistenceJS, LokiJS or jStorage. You can also save data to a backend server e.g. Parse or Firebase, using their APIs. Or you can deploy your own backend storage and save data to it using REST. A: It might be a bit harder to do than you expect but it can be easier than you think. Using mysql as a backend has serious implication. For example, mysql doesn't provide any http interfaces as far as I know. In other words, for most SQL based databases, you'll have to use some kind of middleware to connect your application to the database. Usually the middleware is a server that publish some kind of http api probably in a rest way or even rpc such as JSONrpc. The language in which you'll write the middleware doesn't really matter. The serious problem you'll face with such variant is to restrict data. Prevent other users to access data to which they shouldn't have access. There is also an other variant, I'd say if you want to have a database + synchronization on the server. CouchDB + PouchDB gives you that for free. I mean it's really easy to setup but you'll have to redesign some part of your application. If your application does a lot of data changes it might end up filling your disks but if you're just starting, it's possible that this setup will be more than enough.
unknown
d14272
val
Although this looks like a duplicate of: Is SignalR a suitable substitute for jQuery Ajax (or similar), I'd say you should use SignalR, based on the chosen answer to the similar question. SignalR is perfect for notifying users real-time. You can call client functions from the server and vice versa. This makes it very dynamic. I think it would be more heavier to call an endpoint every 2 minutes – even if there was no order placed – then only perform an action when an order has been placed. The capacity for concurrent connections depends on the performance of the server.
unknown
d14273
val
In my case it was because I needed to set the cookie to secure = false. Apparently I could still have secure true no problem with http and an IP but once I uploaded with a domain it failed.
unknown
d14274
val
You could attach the extraneous date to the object that you are representing in the table view. Give it a new property overrideDate and check that first when configuring your cell. Alternatively, if this is what you want, change the Core Data number based on the chosen date and save it. Depending on your setup (e.g. Fetched Results Controller with delegate enabled and implemented, like in the standard Xcode template), the table view should update correctly.
unknown
d14275
val
"An explicit value for the identity column in table RentalEase.dbo.tblTenant' can only be specified when a column list is used and IDENTITY_INSERT is ON." So use a column list, as the message states: SET IDENTITY_INSERT RentalEase.dbo.tblTenant ON INSERT INTO RentalEase.dbo.tblTenant ([ID], [fieldname], [fieldname], ...) SELECT [ID], ...
unknown
d14276
val
What you are seeing is the this.toString(), that is the default implementation of Object.toString(), since you are not overriding it. add @Override public String toString() { return this.item_name != null ? this.item_name : "name not set"; } to your OrderItem add see what difference it makes @Override public View getView(int position, View conertView, ViewGroup parent){ if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.order_object_layout, parent, false); } /** Gather items from the view */ TextView p_name = (TextView) convertView.findViewById(R.id.product_name); TextView p_value = (TextView) convertView.findViewById(R.id.product_value); TextView p_quantity = (TextView) convertView.findViewById(R.id.product_quantity); /** Asign data to the text views */ OrderItem item = (OrderItem) object.get(position); p_name.setText(item.getName()); return convertView; } Also it should be class OrderObjectAdapter extends ArrayAdapter<OrderItem>{ not class OrderObjectAdapter<OrderItem> extends ArrayAdapter<OrderItem>{
unknown
d14277
val
My apologies to everyone, I'm retarded. For anyone who has same issue just have screen height - the y coordinate to convert, cuz even if u pick different corner the system itself stays.
unknown
d14278
val
When invoking it, you choose which one you want. There isn't a way to get exactly the same functionality as the camera app unless you, as you said, make a custom view for it. But wherever you want to invoke this, you could provide the options for either choosing a photo or taking one at that point. You'll notice other apps that either let you take a photo or choose one from your library give you those as separate options within their UI.
unknown
d14279
val
I recently added a search feature to one of my websites using the LIKE function. When I submit my search form via GET, I build the database query string based on those variables that are passed with the form. if(strcmp($_GET['SSeries'],'') != 0) { $searchString .= "Series LIKE '%".$_GET['SSeries']."%' AND "; $uFriend .= "Series CONTAINS '".$_GET['SSeries']."' AND "; } if(strcmp($_GET['SModel'],'') != 0) { $searchString .= "Model LIKE '%".$_GET['SModel']."%' AND "; $uFriend .= "Model CONTAINS '".$_GET['SModel']."' AND "; } if(strcmp($_GET['SSerial'],'') != 0) { $searchString .= "Serial LIKE '%".$_GET['SSerial']."%' AND "; $uFriend .= "Serial CONTAINS '".$_GET['SSerial']."' AND "; } $_SESSION['searchString'] = $searchString; then at the end, declare a variable that connects them all together. Then, I just use that variable in my search string like so: if(empty($_SESSION['searchString'])) { $sql = "SELECT * from identification;"; $sqluFriend = "Search ALL"; } else { $sql = "SELECT * from identification WHERE ".substr($_SESSION['searchString'], 0, -5).";"; $sqluFriend = "Search ".substr($_SESSION['uFriend'], 0, -5).""; } If the search string is empty, I create a query that has no where clause. Also, note the use of the substr() method used, as removes the last 5 symbols from the search string (Basically so the string doesn't end with AND as that would cause issues with the query.) Also, you can ignore the $sqluFriend variables, I use those to display a user friendly version of the query. Basically, as shown above, I build the search string depending on if the GET variable is posted, it makes it a dynamic search query. Another thing is you should wrap your $searchString builder with if statements that check if any of the data is posted, to avoid errors/return error codes etc. Here is how I did that: if((isSet($_GET['SSSeries'])) || (isSet($_GET['SSModel'])) || (isSet($_GET['SSSerial']))) { You can of course expand this to meet your needs fairly easily. What I did was connected my form to an ajax request every time an input was changed, so that when someone entered anything it would automatically reload the table with the results. Hope I could help.
unknown
d14280
val
After the holidays I came back fresh and found the problem. The filepath string needs to have quotes around it when fed to the stdin for ffprobe, but when I aggregated the files it stripped the quotes. The fix? add quotes around the filepath in the string. I hope this helps someone, apparently I am the only person in the whole internet to have this problem.
unknown
d14281
val
try this: DateTime frmdt = Convert.ToDateTime(fromDate); string frmdtString = frmdt.ToString("yyyy-MM-dd"); or at once: string frmdt = Convert.ToDateTime(fromDate).ToString("yyyy-MM-dd"); So your code could look like this: Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015 string frmdt = Convert.ToDateTime(Fromdate).ToString("yyyy-MM-dd"); ToDate = Txtbox_AjaxCalTo.Text.Trim(); string todt = Convert.ToDateTime(todt).ToString("yyyy-MM-dd"); gvOrders.DataSource = GetData(string.Format("select * from GoalsRoadMap where Activities='{0}' and project ='" + ProjectName + "' and updateddate between '{1}' and '{2}' ", customerId, frmdt, todt )); A: As mentioned by Christos you can format DateTime to universal Date string (here are examples https://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx). But right way to create queries is to use parameters. The following sample for SqlClient, but the idea is the same for other providers. var cmd=new SqlCommand("UPDATE Table1 SET field1=@value WHERE dateField=@date"); cmd.Parameters.Add("@date",SqlDbType.Date).Value=myDateTime; //myDateTime is type of DateTime ... And you have an error in SQL, BETWEEN '2015-10-03' AND '2015-10-03' will return nothing. Instead try this one dateField>='2015-10-03' AND dateField<='2015-10-03' A: You could format your date string as you wish. Let that dt is your DateTime object with the value 10/3/2015 12:00:00 AM. Then you can get the string representation you want like below: var formatted = dt.ToString("yyyy-MM-dd"); A: If your SQL date items stored as date and time, not just date, then your problem will be that for items between '2015-10-03' and '2015-10-03', it returns nothing. So you just need to add one day to your toDate.Date that its Time is 12:00:00 AM. Something like this: Fromdate = Txtbox_AjaxCalFrom.Text.Trim();// 10/3/2015 string frmdt = Convert.ToDateTime(Fromdate).Date; // 10/3/2015 12:00:00 AM //Or //var frmdt = DateTime.Parse(Txtbox_AjaxCalFrom.Text).Date; ToDate = Txtbox_AjaxCalTo.Text.Trim(); string todt = Convert.ToDateTime(todt).Date.AddDays(1);// 11/3/2015 12:00:00 AM now if run your query like this, it may works: var items = allYourSearchItems.Where(x => x.Date >= frmdt && x.Date < todt ); A: None of the above answer worked for me. Sharing what worked: string Text="22/11/2009"; DateTime date = DateTime.ParseExact(Text, "dd/MM/yyyy", null); Console.WriteLine("update date => "+date.ToString("yyyy-MM-dd"));
unknown
d14282
val
You can't do what you're trying to do because F# is a language that uses expressions rather than statements. F# expressions always evaluate to a value (although that value might be unit: ()). The code you originally posted doesn't compile because something of type unit is expected, that's because your if/then expression has no else branch. Consider the following: let a = if x > 5 then 10 This code will produce a compiler error, that's obvious because we haven't specified what the integer value of a might be if x is not greater than 5. Of course, this code will compile: let a = if x > 5 then 10 else 5 If you provide and if without an else, the F# compiler will assume the type is unit so this is also valid code: let a = if x > 5 then () This is because both cases still just return unit, there is no type mismatch. Because F# uses expressions, everything has to be bindable to a value. Anyway, you can solve this by using nested Seq.exists statements, this way you can check every combination of values. let inline task1 items r = items |> Seq.exists (fun s -> items |> Seq.exists(fun t -> s + t = r)) I've changed some of your naming conventions (it's idiomatic for F# function parameters to be camelCased) and have made your function inline so it will work on any type that supports addition. A: Generally, you don't want to use loops to implement complicated iterations / recursive functions in F#. That's what tail recursive functions are good for. To get the computational complexity below O(n²), how about this: consider the set of candidate summands, which is the complete set of numbers at first. Now look at the sum of the largest and smallest number in this set. If this sum is larger than the target number, the largest number won't sum to the target number with anything. The same goes the other way around. Keep dropping the smallest or largest number from the set of candidates until either the set is empty or a match has been found. The code could look like this: let rec f M x = if Set.isEmpty M then false else let biggest, smallest = Set.maxElement M, Set.minElement M let sum = biggest + smallest if sum > x then f (Set.remove biggest M) x elif sum < x then f (Set.remove smallest M) x elif sum = x then true else failwith "Encountered failure to compare numbers / NaN" When I look at the mathematical definition, it doesn't seem to be a requirement that the target number is in the set. But if this matters, just check beforehand: let fChecked M x = if Set.contains x M then f M x else invalidArg "x" "Target number is not contained in set." Tom make this generic over the comparable type, the function could be marked inline. Set operations are O(log n), we go over the whole thing once, multiplying O(n), making the total complexity O(n log n) (where n is the number of elements in the set). Effective speed version If it's about actual speed rather than "just" the computational complexity, arrays are probably faster than immutable sets. Here's a version that uses array indices: /// Version where M is types as an unsorted array we're allowed to sort let f M x = Array.sortInPlace M let rec iter iLow iHigh = if iLow > iHigh then false else let sum = M.[iLow] + M.[iHigh] if sum > x then iter iLow (iHigh - 1) elif sum < x then iter (iLow + 1) iHigh elif sum = x then true else failwith "Encountered failure to compare numbers / NaN" iter 0 (M.Length - 1) Note that we could pre-sort the array if the same set is used repeatedly, bringing down the complexity for each call on the same set down to O(n).
unknown
d14283
val
Alas, no: https://github.com/nodejs/node/blob/56679eb53044b03e4da0f7420774d54f0c550eec/src/inspector/worker_inspector.cc#L28 But you could always try to convince them and submit a PR because the feature appears useful
unknown
d14284
val
The namespace https://www.w3.org/2003/05/soap-envelope/ is SOAP 1.2, for which the correct content-type is application/soap+xml. Try changing the specified content type to this value. Content type text/xml is correct for SOAP 1.1.
unknown
d14285
val
You must try it like this, the classes which were added during scroll could also needs to be removed at certain conditions as below, $(window).scroll(function() { var fromTopPx = 200; // distance to trigger var scrolledFromtop = $(window).scrollTop(); if (scrolledFromtop > fromTopPx && scrolledFromtop <= 600) // distance to trigger second background image { $('html').addClass('scrolled'); $('html').removeClass('scrolledtwo'); } else if (scrolledFromtop >= 601 && scrolledFromtop < 1000) // distance to trigger third background image { $('html').addClass('scrolledtwo'); $('html').removeClass('scrolled'); } else { $('html').removeClass('scrolled'); $('html').removeClass('scrolledtwo') } }); html { background-repeat: no-repeat; background-position: center center; background-attachment: fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } body { height: 1200px; } html { background-image: url("http://placehold.it/350x150/111/fff"); } html.scrolled { background-image: url("http://placehold.it/350x150/f11/fff"); } html.scrolledtwo { background-image: url("http://placehold.it/350x150/f2f/fff"); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Remove .scrolledtwo class when scrollTop is between 200 to 600, same-way remove .scrolled when it between 601 to 1000 else if it crosses the condition remove both. A: Your code is working fine. Have a look. Make a long page you will see the effect. You have set the criteria to change the background image. Good work. A: Only problem was : You were not removing the older added class and were adding new class, at in the middle region i.e. > 600 you are having both the classes scrolled and scrolledTwo. So one solution is : Remove the older class before adding new class. Use these lines at correct places : a- $('html').removeClass('scrolled'); b- $('html').removeClass('scrolledTwo'); use this script : $(window).scroll(function(){ var fromTopPx = 200; // distance to trigger var scrolledFromtop = $(window).scrollTop(); if(scrolledFromtop > fromTopPx && scrolledFromtop < 600) // distance to trigger second background image { $('html').removeClass('scrolledtwo') $('html').addClass('scrolled'); } else if(scrolledFromtop > 600 && scrolledFromtop < 1000) // distance to trigger third background image { $('html').removeClass('scrolled'); $('html').addClass('scrolledtwo'); } else{ ***$('html').removeClass('scrolled');*** $('html').removeClass('scrolledtwo') } return false; });
unknown
d14286
val
The library doesn't fully support Neo4j 4.x yet -still in development-. You can either use an older image of Neo4j (using Neo4j:3.5.19 connects successfully), or you can use a different driver.
unknown
d14287
val
request.META.get('HTTP_REFERER','/') this how you get prev url page
unknown
d14288
val
${} is not used to enclose a single variable but the whole statement. And you should use eq instead of ==. So the correct syntax is: ${buttonName.key eq SIZE}
unknown
d14289
val
The "correct" way to do this is...not to use a singleton. If you want all other code to use the same instance of some type, then give that code a reference to that instance - as a parameter to a function or a constructor. Using a singleton (non-template) would be exactly the same as using a global variable, a practice you should avoid. Using a template means the compiler decides how to instantiate the code, and how to access the "instance". The problem you're experiencing is a combination of this and using a static in a DLL. There are many reasons why singletons are bad, including lifetime issues (when, exactly, would it be safe to delete a singleton?), thread-safety issues, global shared access issues and more. In summary, if you only want one instance of a thing, only create one instance of it, and pass it around to code that needs it. A: The trick that works for me is to add __declspec(dllexport) to the singleton's template definition; split the template implementation from the class definition and only include the implementation in the A DLL; and finally, force the template to be instantiated in the A DLL by creating a dummy function that calls Singleton<Logger>::instance(). So in your A DLL's header file, you define the Singleton template like this: template <class T> class __declspec(dllexport) Singleton { public: static T &instance(); }; Then in your A DLL's cpp file you define the template implementation, and force an instantiation of Singleton<Logger> like this: template <class T> T &Singleton<T>::instance() { static T _instance; return _instance; }; void instantiate_logger() { Singleton<Logger>::instance(); } With my compiler at least, I don't need to call instantiate_logger from anywhere. Just having it exist forces the code to be generated. So if you dump the A DLL's export table at this point, you should see an entry for Singleton<Logger>::instance(). Now in your C DLL and D DLL, you can include the header file with the template definition for Singleton, but because there is no template implementation, the compiler won't be able to create any code for that template. This means the linker will end up complaining about unresolved externals for Singleton<Logger>::instance(), but you just have to link in the A DLL's export library to fix that. The bottom line is that the code for Singleton<Logger>::instance() is only ever implemented in DLL A, so you can never have more than one instance. A: MSDN says that Win32 DLLs are mapped into the address space of the calling process. By default, each process using a DLL has its own instance of all the DLLs global and static variables. If your DLL needs to share data with other instances of it loaded by other applications, you can use either of the following approaches: Create named data sections using the data_seg pragma. Use memory mapped files. See the Win32 documentation about memory mapped files. http://msdn.microsoft.com/en-us/library/h90dkhs0%28v=vs.80%29.aspx A: Here's a really sketchy solution that you might be able to build from. Multiple templates will be instantiated but they will all share the same instance objects. Some additional code would be needed to avoid the memory leak (e.g. replace void * with boost::any of shared_ptr or something). In singleton.h #if defined(DLL_EXPORTS) #define DLL_API __declspec(dllexport) #else #define DLL_API __declspec(dllimport) #endif template <class T> class Singleton { public: static T &instance() { T *instance = reinterpret_cast<T *>(details::getInstance(typeid(T))); if (instance == NULL) { instance = new T(); details::setInstance(typeid(T), instance); } return *instance; } }; namespace details { DLL_API void setInstance(const type_info &type, void *singleton); DLL_API void *getInstance(const type_info &type); } In singleton.cpp. #include <map> #include <string> namespace details { namespace { std::map<std::string, void *> singletons; } void setInstance(const type_info &type, void *singleton) { singletons[type.name()] = singleton; } void *getInstance(const type_info &type) { std::map<std::string, void *>::const_iterator iter = singletons.find(type.name()); if (iter == singletons.end()) return NULL; return iter->second; } } I can't think of a better way right now. The instances have to be stored in a common location. A: I recommend to combine a refcounted class and an exported api in your Logger class: class Logger { public: Logger() { nRefCount = 1; return; }; ~Logger() { lpPtr = NULL; return; }; VOID AddRef() { InterLockedIncrement(&nRefCount); return; }; VOID Release() { if (InterLockedDecrement(&nRefCount) == 0) delete this; return; }; static Logger* Get() { if (lpPtr == NULL) { //singleton creation lock should be here lpPtr = new Logger(); } return lpPtr; }; private: LONG volatile nRefCount; static Logger *lpPtr = NULL; }; __declspec(dllexport) Logger* GetLogger() { return Logger::Get(); }; The code needs some fixing but I try to give you the basic idea. A: I think your problem in your implementation: static T _instance; I assume that static modifier causes compiler to create code in which your T class instances one for each dll. Try different implementations of a singletone. You can try to make static T field in Singletone class. Or maybe Singletone with static pointer inside class should work. I'd recommend you to use second approach, and in your B dll you will specify Singletone<Logger>::instance = nullptr; Than on first call for instance() this pointer will be initialized. And I think this will fix your problem. PS. Don't forget manually handle mutlithreading instancing A: Make some condition like instance() { if ( _instance == NULL ) { _instance = new Singleton(); } return _instance; } This will create only single instance and when it got calls for 2nd time it will just return older instance.
unknown
d14290
val
You can use a converter with numpy.loadtxt that converts the value to a parsable float. In this case we trivially replace Dwith E; import numpy as np numconv = lambda x : str.replace(x.decode('utf-8'), 'D', 'E') np.loadtxt('test.txt', converters={0:numconv, 1:numconv, 2:numconv}, dtype='double') # array([[ 0.00000000e+00, -1.14521000e-17, 1.26240800e-17], # [ 1.00000000e-01, -4.69728600e-07, 1.05596300e-07], # [ 2.00000000e-01, -1.87780600e-06, 4.22049300e-07], # [ 3.00000000e-01, -4.22082400e-06, 9.48298500e-07]])
unknown
d14291
val
You could try xception-71 with DPC, which should give tighter segmentations. Or maybe you can try this https://github.com/tensorflow/models/issues/3739#issuecomment-527811265.
unknown
d14292
val
Well I don't know about the winspool.drv, but you can use the WMI to get the status of the printer. Here is an example of the using Win32_Printer. PrintDialog pd = new PrintDialog(); pd.ShowDialog(); PrintDoc.PrinterSettings = pd.PrinterSettings; PrintDoc.PrintPage += new PrintPageEventHandler(PrintDoc_PrintPage); PrintDoc.Print(); object status = Convert.ToUInt32(9999); while ((uint)status != 0) // 0 being idle { ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_Printer where Name='" + pd.PrinterSettings.PrinterName + "'"); foreach (ManagementObject service in mos.Get()) { status = service.Properties["PrinterState"].Value; Thread.Sleep(50); } } If you don't use the PrintDialog object (to choose a printer) you can run the WMI query and it will return all the printers in the system.
unknown
d14293
val
I'm guessing you are using OSS version. Default location for data is /var/lib/cassandra and you can backup it if you wan't. Procedure for upgrade is simple: * *run nodetool drain *stop cassandra *save your cassandra.yaml *remove old and install new version *update new cassandra.yaml with your settings *start cassandra *run nodetool ugradesstables This should leave you with your node running the new version of cassandra with all your schema and data in it. Be careful if you are upgrading past 2.1 because 2.2 and up require java8. Everything else is the same.
unknown
d14294
val
Depending on what modality your images are, this might possibly be due to not converting the image data into the correct, clinically relevent, machine/vendor independent, units prior to any ML training 0-1 normalization. Typically in dicom files, the actual raw data values aren't that - they need processing... For instance, if you're trying to train on CT data, then the units you should be trying to train your model on are Houndsfield's (HU) numbers. (Do a google on that, CT and dicom to get some background). However raw CT dicom data could be little or big endian, likely needs a slope/intercept correction applied and also could need to have look up tables applied to convert it into HU numbers. ...ie can get complicated and messy. (again do a bit of googling ...you at least should have a bit of background on this if you're trying to do anything with medical image formats). I'm not sure how to process nifti data, however luckily for dicom files using pydicom this conversion can be done for you by the library, using (typically) a call to pydicom.pixel_data_handlers.util.apply_modality_lut: dcm = pydicom.dcmread(my_ct_dicom_file) data_in_HU = pydicom.pixel_data_handlers.util.apply_voi_lut( dcm.pixel_array, dcm )
unknown
d14295
val
The error says it expecting an Array but I don't see any array in your calToAction Query, I guess this might fix your problem: export const query = graphql` query($path: String!) { cms { headerActions: callToActions( where: [ { placement: Header, AND: { pages_some: { path: $path } } } ] ) { url label } } } `
unknown
d14296
val
Based on the JSON you pasted in, I agree that the generated classes don't look correct. For example, morn does not seem to appear in the JSON at all. Did you paste in the entire JSON content that was used to generate the classes? What are you using to serialize/deserialize the JSON? Jackson is a common framework with which to do that. You would need to define mappers from the beans that store the deserialized JSON to the POJO beans. I've not used it myself (I use Jackson and create the JSON and POJO beans myself), but based on the json gen doc, it appears that it's intended to generate the JSON-bean side of things. So you would still need to (at least potentially) define your POJO beans (unless they happened to map 100%, which seems unlikely for a variety of reasons, from different JSON property names versus POJO field names, etc.).
unknown
d14297
val
Hope this will be useful. The order of addition will not be preserve. $("input[type=checkbox]").click(function () { var checkList = []; $("#genreslist").find("input").each(function () { if (this.checked) checkList.push(this.value); }); $("#genre").val(checkList.join("/")); }); Fiddle : here To preserve order you can do : $("input[type=checkbox]").click(function(){ var spacer = ""; var value = $("#genre").val(); if($("#genre").val()){ spacer = " / "; } if($(this).is(':checked')){ $("#genre").val(value + spacer + $(this).val()); } else { var endSpacer = ""; if(value.indexOf($(this).val()) == 0) { spacer=""; endSpacer = value.length > $(this).val().length ? " / " : ""; } $("#genre").val($("#genre").val().replace(spacer + $(this).val() + endSpacer,"")); } }); Fiddle : here
unknown
d14298
val
It's getting cut off because you dragged and dropped controls onto the form rather then hand coded the XAML. If you want it dynamic, you need to hand craft the XAML with the proper layout panels (Grid, StackPanel, etc) using proper layout techniques. The designer produced code is not dynamic at all. It's very strict. A: It is getting cut off because you have fixed width on most of the controls. for example, <Label x:Name="diagnoseResultLabel" Content="N/A" HorizontalAlignment="Left" Margin="123,72,-154,0" VerticalAlignment="Top" Grid.ColumnSpan="2" Height="26" Width="31"/> Get rid of Width property (or make it Auto) and it would work. At the same time as @SledgeHammer pointed out, please craft the XAML with with some layouts. A: What worked for me I deleted this part from my XAMl <Grid.RowDefinitions> <RowDefinition/> <RowDefinition Height="0*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="0*"/> <ColumnDefinition Width="0*"/> </Grid.ColumnDefinitions> Not sure what it did but im assuming it deleted some transparent wall that was infront of it.
unknown
d14299
val
try1 <- apply(dat[,c(2:3)], MARGIN=1, function(x) {sum(x==1, na.rm=TRUE)}) I would like the script to write NA if both var1 and var2 are NA, but if one of the two variables has an actual value, I'd like the script to treat the NA as 0. I have tried this: check1 <- apply(dat[,2:3], MARGIN=1, function(x) {ifelse(x== is.na(dat$var1) & is.na(dat$var2), NA, {sum(x==1, na.rm=TRUE)})}) This, however, produces a 4x4 matrix (int[1:4,1:4]). The real dataset has hundreds of observations so that just became a mess...Does anybody see where I go wrong? Thank you! A: Here's a working version: apply(dat[,2:3], MARGIN=1, function(x) { if(all(is.na(x))) { NA } else { sum(x==1, na.rm=TRUE) } } ) #[1] 1 NA 0 2 Issues with yours: * *Inside your function(x), x is the var1 and var2 values for a particular row. You don't want to go back and reference dat$var1 and dat$var2, which is the whole column! Just use x. *x== is.na(dat$var1) & is.na(dat$var2) is strange. It's trying to check whether x is the same as is.na(dat$var1)? *For a given row, we want to check whether all the values are NA. ifelse is vectorized and will return a vector - but we don't want a vector, we want a single TRUE or FALSE indicating whether all values are NA. So we use all(is.na()). And if() instead of ifelse.
unknown
d14300
val
it turns out that there is one suspicious file inside config folder, once it's deleted the artisan command works just fine again.
unknown