Taken from this answer.
packages.config
file. This is the first time I see ignoring a problem actually makes it go away...
Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can
I've finally found the solution and really hope this helps someone else too.
.csproj
file for the project in question. Delete the following lines of code:
<PropertyGroup>
<ManifestCertificateThumbprint>...........</ManifestCertificateThumbprint>
</PropertyGroup>
<PropertyGroup>
<ManifestKeyFile>xxxxxxxx.pfx</ManifestKeyFile>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>true</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<SignManifests>false</SignManifests>
</PropertyGroup>
Also, there's the handy little "increase indent" and "decrease indent" buttons. If you highlight a block of code and click those buttons the entire block will indent.
Pay close attention to the first part of the error: "variable is not declared"
Ignore the second part: "it may be inaccessible due to its protection level". It's a red herring.
Some questions... (the answers might be in that image you posted, but I can't seem to make it larger and my eyes don't read that small of print... Any chance you can post the code in a way these older eyes can read it? Makes it hard to know the total picture. In particular I am suspicious of your Page directives.)
We know that 1stReasonTypes is a listbox, but for some reason it seems like we don't know WHICH listbox. This is why I want to see your page directives.
But also, how are you calling the private method FormRefresh()? It's not an event handler, which makes me wonder if you are trying to reference a listbox in a form that is not handled properly in this code behind.
You may need to find the control 1stReasonTypes. Try maybe putting your listbox inside something like
<div id="MyFormDiv" runat="server">.....</div>
then in FormRefresh(), do a...
Dim 1stReasonTypesNew As listbox = MyFormDiv.FindControl("1stReasonTypes")
Or use an existing control, object, or page instead of a div. More info on FindControl: http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx
But no matter how you slice it, there is something funky going here such that 1stReasonTypes doesn't know which exact listbox it's supposed to be.
I had the same problem. You could also check which way the slash is pointing. For me it worked to use backslash, instead of forward slash. Example
xcopy /s /y "C:\SFML\bin\*.dll" "$(OutDir)"
Instead of:
xcopy /s /y "C:/SFML/bin/*.dll" "$(OutDir)"
There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap
and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.
There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap
attribute does no work in all situations. In general, what works most widely is the nobr
markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>
.
In Visual Studio 2019 WinForm Projects, it is available under
Project Properties -> Application -> View Windows Settings (button)
I found some articles to be of major use:
This link is an experience someone else had: http://goneale.com/2009/05/24/cant-install-microsoft-sql-server-2008-management-studio-express/
This link has the exact steps involved to install everything properly: http://www.codefrenzy.net/2011/06/03/how-to-install-sql-server-2008-management-studio/
This link confirms the previous link: https://superuser.com/questions/88244/installing-sql-server-management-studio-when-vs2010-beta-2-is-already-installed
My Instructions
I am not sure if my instructions will be 100% accurate, but in my instance, because I installed VS2010 on a fresh copy of Windows 7, the VS2010 installer installs SQL Server 2008 Express for you, so from this point I just need the Management Studio.
What I gathered from these explanations is to do the following:
Download the SQL Server Management Studio install from http://www.microsoft.com/download/en/details.aspx?id=22973
Run the setup, when you get to the point where it asks you to "Perform a new installation of SQL Server 2008" or "Add features to an existing instance of SQL Server 2008", this part is the CONFUSING PART (HEY MICROSOFT TAKE NOTES, DON'T DO THIS KIND OF STUFF).
As much as you want to select "Add features to an existing instance of SQL Server 2008" DON'T!!!!
You need to select "Perform a new installation of SQL Server 2008". It doesn't sound right I know - it is very confusing and counter intuitive, but this seems to be the way to install management studio. :(
Press next until you see the features selection portion. Heeeeeyyyy look at that, it has a check box for Management Studio. It should be selected already, if not then select it of course and press next.
Press Next next next next next next... basically just install it at this point.
Enjoy, it has installed.
In xamarin form project. I deleted
.VS Project folder.
ProjectName.Android.csProj.User
ProjectName.Android.csProj.bak
Use the following code in service OnStart
method:
System.Diagnostics.Debugger.Launch();
Choose the Visual Studio option from the pop up message.
Note: To use it in only Debug mode, a #if DEBUG
compiler directive can be used, as follows. This will prevent accidental or debugging in release mode on a production server.
#if DEBUG
System.Diagnostics.Debugger.Launch();
#endif
It looks that whatever that text is containing some characters which cannot be converted to integer like space, letters, special characters etc. Check what is coming through dropdown as below
lvTwoOrMoreOptions.SelectedItems[0].Text.ToString();
and see if that is the case.
I had the same problem. Debugging does not work with the stuff that comes with the OpenCV executable. you have to build your own binarys.
Then enable Microsoft Symbol Servers in Debug->options and settings->debug->symbols
I had the same problem, expect I coped my MainWindow xaml and cs into a new file and then copied them back to their original place. I then got this error after trying to compile the WPF app.
What I did to fix this error was rename the namespace (from egNamespace -> egNamespaceNew, and it worked again. I then changed the namespace back to the original one.
You might have not closed the the output. Close the output, clean and rebuild the file. You might be able to run the file now.
Summarising @Rasmi Ranjan Nayak and @nogard answers and adding another option:
You should use the flag --gtest_filter
, like
--gtest_filter=Test_Cases1*
(You can also do this in Properties|Configuration Properties|Debugging|Command Arguments)
You should set the variable GTEST_FILTER
like
export GTEST_FILTER = "Test_Cases1*"
You should set a flag filter
, like
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
such that your main function becomes something like
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
::testing::GTEST_FLAG(filter) = "Test_Cases1*";
return RUN_ALL_TESTS();
}
See section Running a Subset of the Tests for more info on the syntax of the string you can use.
+1 to user Short for an answer that worked for me!
I tried to do some debugging of this with msbuild /v:diag
, and I'm seeing that MSBuild is trying to embed a manifest in the executable, with <somename>.dll.embed.manifest.res on the linker command line, where that is a resource file built from <somename>.dll.embed.manifest. But the manifest file is an empty Unicode text file. (That is, a two-byte file with the Unicode 0xFEFF prefix)
So the root problem seems to have something to do with that manifest file not being generated, or it being used when <somename>.dll.intermediate.manifest should have been used.
An alternate solution seems to be to turn off the "Embed Manifest" option under Properties, Manifest Tool, Input and Output.
In 2015, if you still getting this confusing error, blame python default setuptools that PIP uses.
pip install -U setuptools
pip install blahblah
It will work fine.
UPDATE: It won't work fine for all libraries. I still get some error with few modules, that require lib-headers. They only thing that work flawlessly is Linux platform
I had this problem when I installed something that created a user environment PATH variable. My TeamCity build agent was running as a service under my own username and it found the user PATH variable instead of the machine PATH variable. With the wrong path variable, it couldn't find much of anything and gave this error.
Debug version of the vc++ library dlls are NOT meant to be redistributed!
Debug versions of an application are not redistributable, and debug versions of the Visual C++ library DLLs are not redistributable. You may deploy debug versions of applications and Visual C++ DLLs only to your other computers, for the sole purpose of debugging and testing the applications on a computer that does not have Visual Studio installed. For more information, see Redistributing Visual C++ Files.
I will provide the link as well : http://msdn.microsoft.com/en-us/library/aa985618.aspx
For Visual Studio Express 2013 to get rid of these problem you have to do the following.
Right click on your project click Properties. In properties window from left menus select Configuration Properties->C/C++->General
In right side select
Treat Warning As Errors NO
and
SDL Checks NO
I came across this partial class problem in a winform of a solution after converting from .net 4.5.1 to 4.7.2.
Initially the problem the compiler was not complaining about partial class but the use of properties.default...without qualification. After adding Global::solnNameSpace. qualifiers, then I got the partial class problem.
after viewing answers in this thread, I look at the resource designer file, I found it was generated with explicit solnNameSpace while the classes in the solution did not. Also the solnNameSpace is the same as the name of the problematic class name.
To fix the problem with the least effort and time I backed out Global... qualifier and removed the explicit namespace ... and end statements from the resource designer file. I know I may get in trouble later on if there were changes that cause auto generation of the resource designer file but I was was under tight deadline. I made documentation on the temp change instead of a better long term solution since the solution is under no change allowed for nature of the solution and multi project use.
I simply closed all pages of visual studio and reopened ..it worked.
For Chrome go to
Settings->Network->Change Proxy setting
Now Internet properties will open so you need to go LAN settings and click on check box :
Bypass proxy server for local address
I've tried all but nothing worked in my case then I've changed these mentioned settings which resolved the issue quite well for me. Try If it could of any help latter viewers. These settings could be vary in your situation but make sure build all the including DLLs with the same config settings you kept initially (mentioned in the image.).
Cheers!
Might just be for Visual Studio '15, if you right-click on source code, there's an option for insert comment
This puts summary
tags around your comment section, but it does give the indentation that you want.
In my case one of the projects contains multiple IDL files. The MIDL compiler generates a DLL data file called 'dlldata.c' for each of them, regardless of the IDL file name. This caused Visual Studio to compile the IDL files on every build, even without changes to any of the IDL files.
The workaround is to configure a unique output file for each IDL file (the MIDL compiler always generates such a file, even if the /dlldata switch is omitted):
In my case, I had to remove the following from the .csproj file:
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
In fact, in this snippet you can see where the error message is coming from.
I was converting from MSBuild-Integrated Package Restore to Automatic Package Restore (http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore)
Try this,
Using foreach
Loop:
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
if (chk != null && chk.Checked)
{
// ...
}
}
Use it in OnRowCommand
event and get checked CheckBox value.
GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];
The string
class's Replace
method can also be used to remove multiple characters from a string:
Dim newstring As String
newstring = oldstring.Replace(",", "").Replace(";", "")
Check the project properties. It's configurable there if you are using another .net windows application for example
You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.
Visual Studio 2017 version 15.8 made it possible to use the PackageReferencesyntax to reference NuGet packages in Visual Studio Extensibility (VSIX) projects. This makes it much simpler to reason about NuGet packages and opens the door for having a complete meta package containing the entire VSSDK.
Installing below NuGet package will solve the EmbedInteropTypes Issue.
Install-Package Microsoft.VisualStudio.SDK.EmbedInteropTypes
Other than the common ones above, I had a multi-project solution to publish. Apparently some files target different frameworks.
So my solution: Properties > Specific Version (False)
I ran into a similar problem where Visual Studio (2017) said it could not find my project's PDB file. I could see the PDB file did exist in the correct path. I had to Clean and Rebuild the project, then Visual Studio recognized the PDB file and debugging worked.
Visual Studio 2010 SP1 and 2012 added support for IIS Express eliminating the need to edit angle brackets.
I believe this solution is superior to the vikomall's options.
The UI-based solution above uses site-specific location elements in IIS Express's applicationHost.config leaving the app untouched.
More information here: http://msdn.microsoft.com/en-us/magazine/hh288080.aspx
I found that my excel file that was created in Excel 365 was incompatible with any of the versions available. I re-saved the excel file in 97-2003 version and of course chose that version in the dropdown list and it read the file OK.
Take care not to include
#include <string.h>
but only
#include <string>
It took me 1 hour to find this in my code.
Hope this can help
Just for kicks, here's the functions I wrote to do it before I had the .PadRight bit:
public string insertSpacesAtEnd(string input, int longest)
{
string output = input;
string spaces = "";
int inputLength = input.Length;
int numToInsert = longest - inputLength;
for (int i = 0; i < numToInsert; i++)
{
spaces += " ";
}
output += spaces;
return output;
}
public int findLongest(List<Results> theList)
{
int longest = 0;
for (int i = 0; i < theList.Count; i++)
{
if (longest < theList[i].title.Length)
longest = theList[i].title.Length;
}
return longest;
}
////Usage////
for (int i = 0; i < storageList.Count; i++)
{
output += insertSpacesAtEnd(storageList[i].title, longest + 5) + storageList[i].rank.Trim() + " " + storageList[i].term.Trim() + " " + storageList[i].name + "\r\n";
}
xcopy "$(ProjectDir)Views\Home\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\Home"
and if you want to copy entire folders:
xcopy /E /Y "$(ProjectDir)Views" "$(SolutionDir)MEFMVCPOC\Views"
Update: here's the working version
xcopy "$(ProjectDir)Views\ModuleAHome\Index.cshtml" "$(SolutionDir)MEFMVCPOC\Views\ModuleAHome\" /Y /I
Here are some commonly used switches with xcopy
:
- /I - treat as a directory if copying multiple files.
- /Q - Do not display the files being copied.
- /S - Copy subdirectories unless empty.
- /E - Copy empty subdirectories.
- /Y - Do not prompt for overwrite of existing files.
- /R - Overwrite read-only files.
I had the same problem :) Verify the "Source code" folder on the "Solution Explorer", if it doesn't contain any "source code" file then :
Right click on "Source code" > Add > Existing Item > Choose the file You want to build and run.
Good luck ;)
If you want to correct this without uncheking the assembly reuse checkbox this is what worked for me:
Dynamically Created for a Row in a Table
See below the Link
http://msdn.microsoft.com/en-us/library/7bewx260(v=vs.100).aspx
None of the other solutions worked for me. I resolved this issue by using the commands below.
For 32 bit machine:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319>aspnet_regiis –i
For 64 bit machine:
C:\WINDOWS\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis –i
The issue is because the web.config file is not installed correctly.
Please Click Once application --> Properties --> Signing -> Unchecked the Sign the ClickOnce manifests.
Problem will be solved.
Note: Be aware that this solution removes security from your project. Seek assitance from a more learned colleague before doing so.
This seems a little more elegant
'populate DT from .csv file
Dim items = (From line In IO.File.ReadAllLines("C:YourData.csv") _
Select Array.ConvertAll(line.Split(","c), Function(v) _
v.ToString.TrimStart(""" ".ToCharArray).TrimEnd(""" ".ToCharArray))).ToArray
Dim Your_DT As New DataTable
For x As Integer = 0 To items(0).GetUpperBound(0)
Your_DT.Columns.Add()
Next
For Each a In items
Dim dr As DataRow = Your_DT.NewRow
dr.ItemArray = a
Your_DT.Rows.Add(dr)
Next
Your_DataGrid.DataSource = Your_DT
Check if your website on IIS is not stop.
I fixed it put my web site to run. :D
An alternate method that limits the scope of the lambda rather than giving it access to the whole this
is to pass in a local reference to the member variable, e.g.
auto& localGrid = grid;
int i;
for_each(groups.cbegin(),groups.cend(),[localGrid,&i](pair<int,set<int>> group){
i++;
cout<<i<<endl;
});
I am using Visual Studio 2013 and I have the same issue but it occurs when I try to open a solution that was made using Visual Studio 2010.
The solution for me is to open the solution file (.sln), using notepad and change this line:
[# Visual Studio 2010]
to this:
[# Visual Studio 2013]
Ghost Doc (Free)
It takes a while to configure it properly, but it can be quite useful.
I was importing also some projects from VS2010 to VS 2012. I had the same errors. The errors disappeared when I set back Properties > Config. Properties > General > Platform Toolset to v100 (VS2010). That might not be the correct approach, however.
Working with VS 2013. Try the following Tools -> Options -> Debugging -> Output Window -> Module Load Messages -> Off It will disable the display of modules loaded.
Visual studio’s smart indenting does automatically indenting, but we can select a block or all the code for indentation.
Select all the code: Ctrl+a
Use either of the two ways to indentation the code:
Shift+Tab,
Ctrl+k+f.
Instead of searching fr the GUIDs, you can simply delete the GUIds tags. Then try opening the project again. The second time opening you should get a more reasonable error message.
For instance my issue was that I did not install SharePoint Developer Tools when I installed Visual Studio 2010 on my development Virtual Machine. So when I tried opennign the project after deleting the GUIDs, VS2010 told me the path it was looking for did not exist.
Therefore VS2010 was looking for a SharePoint library that was not installed. I simply had to run the install again, and then add that feature.
Highlight block of text, then:
Comment Block: Ctrl + K + C
Uncomment Block: Ctrl + K + U
Tested in Visual Studio 2012
Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.
Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).
I had this problem because a dll I was using had Sqlite as a dependency (configured in NuGet with only the Sqlite core package.). The project compiles and copies all the Sqlite dll-s except the 'SQLite.Interop.dll' (both x86 and x64 folder).
The solution was very simple: just add the System.Data.SQLite.Core package as a dependency (with NuGet) to the project you are building/running and the dll-s will be copied.
Just to throw in my 2 cents. My issue was solved by opening Task Manager and killing the application. It was running in the background without any indication that it was running at all (no item in the task bar, no ui, nothing), but I am not sure why this happened. Obviously the debugger was not running and I only had a single instance of VS opened at the time. It amazes me that this is still happening in this VS 2017.
Perhaps I can add a build step that looks for the application running the background and kills it before starting the new one.
You can use the files from debug folder,however if you look at app debug informations with some inspection software,you can clearly see "Symbols File Name" which can reveals not wanted informations in path to the original exe file.
Since this is the top result on Google:
If your connection works initially, but you begin seeing this error after many successful connections, it may be this issue.
In summary: if you open and close a connection, Windows reserves the TCP port for future use for some stupid reason. After doing this many times, it runs out of available ports.
The article gives a registry hack to fix the issue...
Here are my registry settings on XP/2003:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort 0xFFFF (DWORD) HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\MaxUserPort\TcpTimedWaitDelay 60 (DWORD)
You need to create them. By default they don't exists.
On Vista/2008 you can use netsh to change it to something like:
netsh int ipv4 set dynamicport tcp start=10000 num=50000
...but the real solution is to use connection pooling, so that "opening" a connection really reuses an existing connection. Most frameworks do this automatically, but in my case the application was handling connections manually for some reason.
For me this was thrown when running unit tests under MSTest
(VS2015). Had to add
<startup useLegacyV2RuntimeActivationPolicy="true">
</startup>
in
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\TE.ProcessHost.Managed.exe.config
"Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows."
Source: http://dev.mysql.com/downloads/connector/net/6.6.html
Visual Studio 2015:
Project
=>
Your Application Properties
. Each argument can be separated using space. If you have a space in between for the same argument, put double quotes as shown in the example below.
static void Main(string[] args)
{
if(args == null || args.Length == 0)
{
Console.WriteLine("Please specify arguments!");
}
else
{
Console.WriteLine(args[0]); // First
Console.WriteLine(args[1]); // Second Argument
}
}
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
The TypeInitializationException
that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.
TypeInitializationException is also called static constructors.
Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)
private void initListView()
{
// Add columns
lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}
You can also use the other overload, Add(string). E.g:
lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");
Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx
Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.
var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);
You can also store objects in the item's Tag property.
item2.Tag = person;
And then you can extract it
var person = item2.Tag as Person;
Let me know if you have any questions and I hope this helps!
I don't see any mention of flexbox in here, so I will illustrate:
HTML
<div class="wrapper">
<div class="main">top</div>
<div class="footer">bottom</div>
</div>
CSS
.wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.main {
flex: 1;
}
.footer {
flex: 0;
}
Use response.write method in the code-behind.
I was getting this when the app deployed. In my case, I chose "This is a full trust application" on the project security tab, and that fixed it.
Use Either Debug.WriteLine()
or Trace.WriteLine()
. If in release mode, only the latter will appear in the output window, in debug mode, both will.
@Kumar
"W7 prompts everytime to run this program "devenv.exe" , anyway to get rid of that ?"
Yes. You can prevent Windows from prompting you by going to Control Panel/User Accounts/Change User Account Control settings and move the slider down.
I could recommend the following trick: Create a special boost.props
file
This procedure has the value that boost is included only in projects where you want to explicitly include it. When you have a new project that uses boost, do:
EDIT (following edit from @jim-fred):
The resulting boost.props
file looks something like this...
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ImportGroup Label="PropertySheets" />
<PropertyGroup Label="UserMacros">
<BOOST_DIR>D:\boost_1_53_0\</BOOST_DIR>
</PropertyGroup>
<PropertyGroup>
<IncludePath>$(BOOST_DIR);$(IncludePath)</IncludePath>
<LibraryPath>$(BOOST_DIR)stage\lib\;$(LibraryPath)</LibraryPath>
</PropertyGroup>
</Project>
It contains a user macro for the location of the boost directory (in this case, D:\boost_1_53_0) and two other parameters: IncludePath and LibraryPath. A statement #include <boost/thread.hpp>
would find thread.hpp in the appropriate directory (in this case, D:\boost_1_53_0\boost\thread.hpp). The 'stage\lib\' directory may change depending on the directory installed to.
This boost.props file could be located in the D:\boost_1_53_0\
directory.
I had the same issue and deleting the store and reading didn't work. I had to do the following.
Get a copy of OpenSSL. It is available for Windows. Or use a Linux box as they all pretty much all have it.
Run the following to export to a key file:
openssl pkcs12 -in certfile.pfx -out backupcertfile.key
openssl pkcs12 -export -out certfiletosignwith.pfx -keysig -in backupcertfile.key
Then in the project properties you can use the PFX file.
Apart from @Kragen mentioned, If you are debugging a web project
close the visual studio and try deleting the temporary files at C:\Windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files
I had a similar problem and none of the solutions above worked, so I went with an old standby that always works:
That almost always works if you've spent 10 minutes at it and can't get it.
Note that for similar problems with older versions (2008, 2005) you can usually get away with just changing the version in the .csproj and either changing the version in the .sln or discarding it, but this doesn't seem to work for 2013.
see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017
If it does not exist, add a new file called .editorconfig for your project
manipulate editor config to use your preferred behaviour.
I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.tmpl.html]
indent_size = 4
[*.scss]
indent_size = 2
Max has the best solution for when you always want to start both projects, but you can also right click a project and choose menu Debug ? Start New Instance.
This is an option when you only occasionally need to start the second project or when you need to delay the start of the second project (maybe the server needs to get up and running before the client tries to connect, or something).
found two different solutions which worked in slightly different way:
1. This solution is inspired by the answer from alexanderb [link]. Unfortunately it did not work for us - some dll's were not copied to the OutDir. We found out that replacing ResolveReferences
with Build
target solves the problem - now all necessary files are copied into the OutDir location.
msbuild /target:Build;_WPPCopyWebApplication /p:Configuration=Release;OutDir=C:\Tmp\myApp\ MyApp.csprojDisadvantage of this solution was the fact that OutDir contained not only files for publish.
2. The first solution works well but not as we expected. We wanted to have the publish functionality as it is in Visual Studio IDE - i.e. only the files which should be published will be copied into the Output directory. As it has been already mentioned first solution copies much more files into the OutDir - the website for publish is then stored in _PublishedWebsites/{ProjectName}
subfolder. The following command solves this - only the files for publish will be copied to desired folder. So now you have directory which can be directly published - in comparison with the first solution you will save some space on hard drive.
msbuild /target:Build;PipelinePreDeployCopyAllFilesToOneFolder /p:Configuration=Release;_PackageTempDir=C:\Tmp\myApp\;AutoParameterizationWebConfigConnectionStrings=false MyApp.csproj
AutoParameterizationWebConfigConnectionStrings=false
parameter will guarantee that connection strings will not be handled as special artifacts and will be correctly generated - for more information see link.
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
Try this: Open IIS Manager, change application pool's advance setting, change Enable 32 bit Application to false.
In Visual studio use all your header filer below "stdafx.h".
You probably don't have the System.Configuration dll added to the project references. It is not there by default, and you have to add it manually.
Right-click on the References and search for System.Configuration in the .net assemblies.
Check to see if it is in your references...
Right-click and select Add Reference...
Find System.Configuration in the list of .Net Assemblies, select it, and click Ok...
The assembly should now appear in your references...
I'm assuming you're using VS2010 (that's what you've tagged the question as) I had problems getting them to add automatically to the toolbox as in VS2008/2005. There's actually an option to stop the toolbox auto populating!
Go to Tools > Options > Windows Forms Designer > General
At the bottom of the list you'll find Toolbox > AutoToolboxPopulate which on a fresh install defaults to False. Set it true and then rebuild your solution.
Hey presto they user controls in you solution should be automatically added to the toolbox. You might have to reload the solution as well.
I'm using the following trick:
I select the declaration of the class with the data-members and press:
Ctrl+C, Shift+Ctrl+C, Ctrl+V.
The PROGRAM gets the declaration from the clipboard, finds the name of the class, finds all members and their types, generates constructor and copies it all back into the clipboard.
We are doing it with freshmen on my "Programming-I" practice (Charles University, Prague) and most of students gets it done till the end of the hour.
If you want to see the source code, let me know.
Go to the Debug menu and select Options and uncheck "Redirect all Output Window text to Immediate Window"
This is still an issue in VS Community 2015 and 2017 when building either console or windows apps. If the project is created with precompiled headers, the precompiled headers are apparently loaded before any of the #includes, so even if the #define _USE_MATH_DEFINES is the first line, it won't compile. #including math.h instead of cmath does not make a difference.
The only solutions I can find are either to start from an empty project (for simple console or embedded system apps) or to add /Y- to the command line arguments, which turns off the loading of precompiled headers.
For information on disabling precompiled headers, see for example https://msdn.microsoft.com/en-us/library/1hy7a92h.aspx
It would be nice if MS would change/fix this. I teach introductory programming courses at a large university, and explaining this to newbies never sinks in until they've made the mistake and struggled with it for an afternoon or so.
its solved. Use nuget and search for the "ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client".
and install the package. it will resolve the issue for me.
Use the "Go To Find Combo Box" with the ">of" command. CTRL+/ or CTRL+D are the standard hotkeys.
For example, go to the combo box (CTRL+/) and type: >of MyClassName
. As you type, intellisense will refine the options in the dropdown.
In my experience, this is faster than Navigate To and doesn't bring up another dialog to deal with. Also, this combo box has a lot of other nifty little shortcut commands:
Using the Go To Find Combo Box
This textbox used to be the default on the Standard toolbar in Visual Studio. It was removed in Visual Studio 2012, so you have to add it back using menu Tools ? Customize. The hotkeys may have changed too: I'm not sure since mine are all customized.
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
When working with a version control system where all files are read only until checked out (like Perforce), the problem may be that you accidentally submitted into this version control system one of the VS files (like filters, for example) and the file thus cannot be overridden during build.
Just go to your working directory and check that none of VS solution related files and none of temporary created files (like all moc_ and ui_ prefixed files in QT, for example) is read only.
This particular NuGet package has a habit of losing its references in one of our projects. From time to time I will need to run the following command in the Package Manager Console to restore the references and everything is OK again
Update-Package Microsoft.AspNet.Webpages -reinstall
You're probably targeting the Client Profile, in which System.Web.dll
is not available.
You can target the full framework in project's Properties.
The only way that I was able to get over this (reinstall wasn't an option) was to set the project properties->web->start action->"don't open a page. wait for a request from an external application."
BTW, I think that at some point this started because of a mod that I made to machine.config. :) And no, I don't remember what it was. It does seem to be this very apocalyptic bug where once you get it never goes away.
So if you found this page from Google, you should know that you are doomed. :)
I found this MSDN forum post which suggests two solutions to your problem.
First solution (not recommended):
Find the .Net Framework 3.5 and 2.0 folder
Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder
Add the reference to these two assemblies
Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work
Second solution (Use a different class / library):
The user who had posted the question claimed that Uri.EscapeUriString
and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer
.
You could also try to use Json.Net. It's a third party library and pretty powerful.
It happens that none of the above methods work. Key binding is proper, but tool tip simply doesn't show in any case, neither as completion help or on demand.
To fix it just go to Tools\Text Editor\C# (or all languages) and check the 'Parameter Information'. Now it should work
If the report designer is opened, Report Data Pane can be enabled using view menu.
View -> Report Data
You can use the ScriptManager.RegisterStartupScript();
to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();
, you can do this:
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
//----or alternatively and to be more proper
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}
To be exact for you, do this...
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}
ls
by default previews the files sorted by name. (ls
options can be used to sort by date, size, ...)
files = list(os.popen("ls"))
files = [file.strip("\n") for file in files]
Using ls
would have much better performance when the directory contains so many files.
If you want to remove all whitespace:
$str = preg_replace('/\s+/', '', $str);
See the 5th example on the preg_replace documentation. (Note I originally copied that here.)
Edit: commenters pointed out, and are correct, that str_replace
is better than preg_replace
if you really just want to remove the space character. The reason to use preg_replace
would be to remove all whitespace (including tabs, etc.).
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
Yes. There is a simple way to remove everything in iPython. In iPython console, just type:
%reset
Then system will ask you to confirm. Press y. If you don't want to see this prompt, simply type:
%reset -f
This should work..
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
On properties,
Check whether radio button is selected for
Run only when user is logged on
If you selected for the above option then that is the reason why it is failed.
so change the option to
Run whether user is logged on or not
OR
In other case, user might have changed his/her login credentials
At times the error code 409
occurs when you name you folder or files a reserved or blocked name. These could be names like register
, contact
In my case I named a folder contact
, turns out the name was blocked from being used as folder names.
When testing my script on postman
, I was getting this error:
<script>
document.cookie = "humans_21909=1"; document.location.reload(true)
</script>
I changed the folder name from contact to contacts and it worked. The error was gone.
<a class="btn btn-large btn-success" id="fire" href="http://twitter.github.io/bootstrap/examples/marketing-narrow.html#">Send Email</a>
$('#fire').on('click', function (e) {
//your awesome code here
})
by default you would need to use the postgres user:
sudo -u postgres psql postgres
this type of error usually occur when you try to access data through the index in which data data has not been assign. for example
//assign of data in to array
for(int i=0; i<10; i++){
arr[i]=i;
}
//accessing of data through array index
for(int i=10; i>=0; i--){
cout << arr[i];
}
the code will give error (vector subscript out of range) because you are accessing the arr[10] which has not been assign yet.
If you want to move the position of the legend please use the following code:
library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
theme(legend.position="bottom")
This should give you the desired result.
When you use Integrated Windows Authentication (i.e., Active Directory Single Sign-On), you authenticate to AD resources automatically with your AD credentials. You've are already signed in to AD and these credentials are reused automatically. Therefore if your server is IWA-enabled (e.g., VisualSVN Server), the server does not ask you to enter username and password, passing --username
and --password
does not work, and the SVN client does not cache your credentials on disk, too.
When you want to change the user account that's used to contact the server, you need use the Windows Credential Manager on client side. This is also helpful when your computer is not domain joined and you need to store your AD credentials to access your domain resources.
Follow these steps to save the user's domain credentials to Windows Credential Manager on the user's computer:
svn.example.com
).DOMAIN\Username
format.Now when you will contact https://svn.example.com/svn/MyRepo
or a similar URL, the client or web browser will use the credentials saved in the Credential Manager to authenticate to the server.
This error may be actually being show because mysql is already started. Try to see the current status by:
mysql.server status
To understand event handlers, you need to understand delegates. In C#, you can think of a delegate as a pointer (or a reference) to a method. This is useful because the pointer can be passed around as a value.
The central concept of a delegate is its signature, or shape. That is (1) the return type and (2) the input arguments. For example, if we create a delegate void MyDelegate(object sender, EventArgs e)
, it can only point to methods which return void
, and take an object
and EventArgs
. Kind of like a square hole and a square peg. So we say these methods have the same signature, or shape, as the delegate.
So knowing how to create a reference to a method, let's think about the purpose of events: we want to cause some code to be executed when something happens elsewhere in the system - or "handle the event". To do this, we create specific methods for the code we want to be executed. The glue between the event and the methods to be executed are the delegates. The event must internally store a "list" of pointers to the methods to call when the event is raised.* Of course, to be able to call a method, we need to know what arguments to pass to it! We use the delegate as the "contract" between the event and all the specific methods that will be called.
So the default EventHandler
(and many like it) represents a specific shape of method (again, void/object-EventArgs). When you declare an event, you are saying which shape of method (EventHandler) that event will invoke, by specifying a delegate:
//This delegate can be used to point to methods
//which return void and take a string.
public delegate void MyEventHandler(string foo);
//This event can cause any method which conforms
//to MyEventHandler to be called.
public event MyEventHandler SomethingHappened;
//Here is some code I want to be executed
//when SomethingHappened fires.
void HandleSomethingHappened(string foo)
{
//Do some stuff
}
//I am creating a delegate (pointer) to HandleSomethingHappened
//and adding it to SomethingHappened's list of "Event Handlers".
myObj.SomethingHappened += new MyEventHandler(HandleSomethingHappened);
//To raise the event within a method.
SomethingHappened("bar");
(*This is the key to events in .NET and peels away the "magic" - an event is really, under the covers, just a list of methods of the same "shape". The list is stored where the event lives. When the event is "raised", it's really just "go through this list of methods and call each one, using these values as the parameters". Assigning an event handler is just a prettier, easier way of adding your method to this list of methods to be called).
longButton.setOnClickListener {
show(
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1\n2\n3\n4\n5\n6\n7\n8\n9\n0\n" +
"1234567890-12345678901234567890123456789012345678901234567890"
)
}
shortButton.setOnClickListener {
show(
"1234567890\n" +
"1234567890-12345678901234567890123456789012345678901234567890"
)
}
private fun show(msg: String) {
val builder = AlertDialog.Builder(this).apply {
setPositiveButton(android.R.string.ok, null)
setNegativeButton(android.R.string.cancel, null)
}
val dialog = builder.create().apply {
setMessage(msg)
}
dialog.show()
dialog.window?.decorView?.addOnLayoutChangeListener { v, _, _, _, _, _, _, _, _ ->
val displayRectangle = Rect()
val window = dialog.window
v.getWindowVisibleDisplayFrame(displayRectangle)
val maxHeight = displayRectangle.height() * 0.6f // 60%
if (v.height > maxHeight) {
window?.setLayout(window.attributes.width, maxHeight.toInt())
}
}
}
Use shutdown.exe. To avoid problem with passing args, complex execution, execution from WindowForms use PowerShell execute script:
using System.Management.Automation;
...
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("shutdown -a; shutdown -r -t 100;");
// invoke execution on the pipeline (collecting output)
Collection<PSObject> PSOutput = PowerShellInstance.Invoke();
}
System.Management.Automation.dll should be installed on OS and available in GAC.
Sorry for My english.
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
If you just want to remove single character and If you know index of a character you want to remove, you can use following function:
/**
* Remove single character at particular index from string
* @param {*} index index of character you want to remove
* @param {*} str string from which character should be removed
*/
function removeCharAtIndex(index, str) {
var maxIndex=index==0?0:index;
return str.substring(0, maxIndex) + str.substring(index, str.length)
}
Please try this
(function ($) {
$(document).ready(function(){
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
if($('.submitclass').length){
$('.submitclass').click(function(){
$email_id = $('.custom-email-field').val();
if (validateEmail($email_id)) {
var url= $(this).attr('pdf_url');
var link = document.createElement('a');
link.href = url;
link.download = url.split("/").pop();
link.dispatchEvent(new MouseEvent('click'));
}
});
}
});
}(jQuery));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
<div class="form-item form-type-textfield form-item-email-id form-group">
<input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
</div>
<button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>
_x000D_
Or use download attribute to tag in HTML5
In 4.0 version of the .Net framework the ServicePointManager.SecurityProtocol
only offered two options to set:
In the next release of the framework the SecurityProtocolType
enumerator got extended with the newer Tls protocols, so if your application can use th 4.5 version you can also use:
So if you are on .Net 4.5 change your line
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
to
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
so that the ServicePointManager will create streams that support Tls12 connections.
Do notice that the enumeration values can be used as flags so you can combine multiple protocols with a logical OR
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls |
SecurityProtocolType.Tls11 |
SecurityProtocolType.Tls12;
Note
Try to keep the number of protocols you support as low as possible and up-to-date with today security standards. Ssll3 is no longer deemed secure and the usage of Tls1.0 SecurityProtocolType.Tls
is in decline.
Yes, exactly what you're asking for is possible. It is not possible to 'decrypt' an MD5 password without help, but it is possible to re-encrypt an MD5 password into another algorithm, just not all in one go.
What you do is arrange for your users to be able to logon to your new system using the old MD5 password. At the point that they login they have given your login program an unhashed version of the password that you prove matches the MD5 hash that you have. You can then convert this unhashed password to your new hashing algorithm.
Obviously, this is an extended process because you have to wait for your users to tell you what the passwords are, but it does work.
(NB: seven years later, oh well hopefully someone will find it useful)
The result returned by find is an array.
Try this instead:
console.log(user[0]["_id"]);
The C++ semantics of const
are very different from Java final
. If the designers had used const
it would have been unnecessarily confusing.
The fact that const
is a reserved word suggests that the designers had ideas for implementing const
, but they have since decided against it; see this closed bug. The stated reasons include that adding support for C++ style const
would cause compatibility problems.
If you don't mind multiple inheritance (it is not that bad, after all), you may write simple class with private copy constructor and assignment operator and additionally subclass it:
class NonAssignable {
private:
NonAssignable(NonAssignable const&);
NonAssignable& operator=(NonAssignable const&);
public:
NonAssignable() {}
};
class SymbolIndexer: public Indexer, public NonAssignable {
};
For GCC this gives the following error message:
test.h: In copy constructor ‘SymbolIndexer::SymbolIndexer(const SymbolIndexer&)’:
test.h: error: ‘NonAssignable::NonAssignable(const NonAssignable&)’ is private
I'm not very sure for this to work in every compiler, though. There is a related question, but with no answer yet.
UPD:
In C++11 you may also write NonAssignable
class as follows:
class NonAssignable {
public:
NonAssignable(NonAssignable const&) = delete;
NonAssignable& operator=(NonAssignable const&) = delete;
NonAssignable() {}
};
The delete
keyword prevents members from being default-constructed, so they cannot be used further in a derived class's default-constructed members. Trying to assign gives the following error in GCC:
test.cpp: error: use of deleted function
‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
test.cpp: note: ‘SymbolIndexer& SymbolIndexer::operator=(const SymbolIndexer&)’
is implicitly deleted because the default definition would
be ill-formed:
UPD:
Boost already has a class just for the same purpose, I guess it's even implemented in similar way. The class is called boost::noncopyable
and is meant to be used as in the following:
#include <boost/core/noncopyable.hpp>
class SymbolIndexer: public Indexer, private boost::noncopyable {
};
I'd recommend sticking to the Boost's solution if your project policy allows it. See also another boost::noncopyable
-related question for more information.
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Add volley.jar
as library
[MyProjectPath]/app/libs/
folderUse the source files from git (a rather manual/general way described here)
git clone https://github.com/git/git
... sry bad one, but couldn't resist ^^)git clone https://android.googlesource.com/platform/frameworks/volley
com
folder from within [path_where_you_typed_git_clone]/volley/src
to your projects app/src/main/java
folder (Integrate it instead, if you already have a com folder there!! ;-))The files show up immediately in Android Studio. For Eclipse you will have to right-click
on the src
folder and press refresh
(or F5
) first.
Use gradle via the "unofficial" maven mirror
In your project's src/build.gradle
file add following volley dependency:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// ...
compile 'com.mcxiaoke.volley:library:1.+'
}
Click on Try Again
which should right away appear on the top of the file, or just Build
it if not
The main "advantage" here is, that this will keep the version up to date for you, whereas in the other two cases you would have to manually update volley.
On the "downside" it is not officially from google, but a third party weekly mirror.
But both of these points, are really relative to what you would need/want.
Also if you don't want updates, just put the desired version there instead e.g. compile 'com.mcxiaoke.volley:library:1.0.7'
.
For me the issue was when I tried to access HTTPContext
in the Controller's constructor while HTTPContext
is not ready yet. When moved inside Index method it worked:
var uri = new Uri(Request.Url.AbsoluteUri);
url = uri.Scheme + "://" + uri.Host + "/";enter code here
Let me suggest you an easier approach,
Instead of divind into GIT's deep consepts and bothering with the editor's crab, you could do the following;
Lets suppose you created a branch named bug1 from master. Made 2 commits to bug1. You only modified 2 files with these changes.
Copy these two files into a text editor. Checkout master. Paste the files. Commit.
That simple.
The first argument to printf()
is always a string value, known as a format control string. This string may be regular text, such as
printf("Hello, World\n"); // \n indicates a newline character
or
char greeting[] = "Hello, World\n";
printf(greeting);
This string may also contain one or more conversion specifiers; these conversion specifiers indicate that additional arguments have been passed to printf()
, and they specify how to format those arguments for output. For example, I can change the above to
char greeting[] = "Hello, World";
printf("%s\n", greeting);
The "%s" conversion specifier expects a pointer to a 0-terminated string, and formats it as text.
For signed decimal integer output, use either the "%d" or "%i" conversion specifiers, such as
printf("%d\n", addNumber(a,b));
You can mix regular text with conversion specifiers, like so:
printf("The result of addNumber(%d, %d) is %d\n", a, b, addNumber(a,b));
Note that the conversion specifiers in the control string indicate the number and types of additional parameters. If the number or types of additional arguments passed to printf()
don't match the conversion specifiers in the format string then the behavior is undefined. For example:
printf("The result of addNumber(%d, %d) is %d\n", addNumber(a,b));
will result in anything from garbled output to an outright crash.
There are a number of additional flags for conversion specifiers that control field width, precision, padding, justification, and types. Check your handy C reference manual for a complete listing.
I found this article very helpful.
http://talk.maemo.org/archive/index.php/t-43663.html
I'll briefly describe the actions to create and change .ui file to .py file, taken from that article.
The file is created and saved, now we will Generate the Python code from it using pyuic!
Hope this helps someone.
I'd place 32-bit and 64-bit sources in different files and then select appropriate source files using the build system.
TextPad will allow you to perform this operation.
example:
test this sentence
Find what: \([^ ]*\) \(.*\)
Replace with: \U\1\E \2
the \U
will cause all following chars to be upper
the \E
will turn off the \U
the result will be:
TEST this sentence
actions
in Vuex are asynchronous. The only way to let the calling function (initiator of action) to know that an action is complete - is by returning a Promise and resolving it later.
Here is an example: myAction
returns a Promise
, makes a http call and resolves or rejects the Promise
later - all asynchronously
actions: {
myAction(context, data) {
return new Promise((resolve, reject) => {
// Do something here... lets say, a http call using vue-resource
this.$http("/api/something").then(response => {
// http success, call the mutator and change something in state
resolve(response); // Let the calling function know that http is done. You may send some data back
}, error => {
// http failed, let the calling function know that action did not work out
reject(error);
})
})
}
}
Now, when your Vue component initiates myAction
, it will get this Promise object and can know whether it succeeded or not. Here is some sample code for the Vue component:
export default {
mounted: function() {
// This component just got created. Lets fetch some data here using an action
this.$store.dispatch("myAction").then(response => {
console.log("Got some data, now lets show something in this component")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
})
}
}
As you can see above, it is highly beneficial for actions
to return a Promise
. Otherwise there is no way for the action initiator to know what is happening and when things are stable enough to show something on the user interface.
And a last note regarding mutators
- as you rightly pointed out, they are synchronous. They change stuff in the state
, and are usually called from actions
. There is no need to mix Promises
with mutators
, as the actions
handle that part.
Edit: My views on the Vuex cycle of uni-directional data flow:
If you access data like this.$store.state["your data key"]
in your components, then the data flow is uni-directional.
The promise from action is only to let the component know that action is complete.
The component may either take data from promise resolve function in the above example (not uni-directional, therefore not recommended), or directly from $store.state["your data key"]
which is unidirectional and follows the vuex data lifecycle.
The above paragraph assumes your mutator uses Vue.set(state, "your data key", http_data)
, once the http call is completed in your action.
In addition to what eugene and stevenl posted, you might encounter problems with using both <>
and <STDIN>
in one script: <>
iterates through (=concatenating) all files given as command line arguments.
However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input
The Material icons use the Material icon font, and the font needs to be included with the page.
Here's the CDN from Google Web Fonts:
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:
* {
padding: initial;
}
if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.
TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free
Even shorter version of the solution from Dominic Zukiewicz:
ServicePointManager.ServerCertificateValidationCallback += (o, c, ch, er) => true;
But this means that you will trust all certificates. For a service that isn't just run locally, something a bit smarter will be needed. In the first instance you could use this code to just test whether it solves your problem.
I have seen IFRAMEs applied very successfully as an easy way to make dynamic context menus, but the target audience of that web-app was only Internet Explorer users.
I would say that it all depends on your requirements. If you wish to make sure your page works equally well on every browser, avoid IFRAMEs. If you are targeting a narrow and well-known audience (eg. on the local Intranet) and you see a benefit in using IFRAMEs then I would say it's OK to do so.
Correct me if wrong...I think request does persist between consecutive pages..
Think you traverse from page 1--> page 2-->page 3.
You have some value set in the request object using setAttribute from page 1, which you retrieve in page 2 using getAttribute,then if you try setting something again in same request object to retrieve it in page 3 then it fails giving you null value as "the request that created the JSP, and the request that gets generated when the JSP is submitted are completely different requests and any attributes placed on the first one will not be available on the second".
I mean something like this in page 2 fails:
Where as the same thing has worked in case of page 1 like:
So I think I would need to proceed with either of the two options suggested by Phill.
You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.
Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.
As an improvement to @Akash Desarda 's answer, you could do
import argparse
from distutils.util import strtobool
parser = argparse.ArgumentParser()
parser.add_argument("--foo",
type=lambda x:bool(strtobool(x)),
nargs='?', const=True, default=False)
args = parser.parse_args()
print(args.foo)
And it supports python test.py --foo
(base) [costa@costa-pc code]$ python test.py
False
(base) [costa@costa-pc code]$ python test.py --foo
True
(base) [costa@costa-pc code]$ python test.py --foo True
True
(base) [costa@costa-pc code]$ python test.py --foo False
False
SELECT
resultIn the Navigator, right click on the table > Table Data Export Wizard
All columns and rows are included by default, so click on Next.
Select File Path, type, Field Separator (by default it is ;
, not ,
!!!) and click on Next.
Click Next > Next > Finish and the file is created in the specified location
Check that All Files are Included in Your Project:
I had this same error pop up after I updated cLion. After hours of tinkering, I noticed one of my files was not included in the project target. After I added it back to the active project, I stopped getting the undefined reference to winmain16, and the code compiled.
Edit: It's also worthwhile to check the build settings within your IDE.
(Not sure if this error is related to having recently updated the IDE - could be causal or simply correlative. Feel free to comment with any insight on that factor!)
Commenting both Fetch
and LazyCollection
sometimes helps to run project.
@Fetch(FetchMode.JOIN)
@LazyCollection(LazyCollectionOption.FALSE)
import org.apache.commons.collections4.ListUtils;
ArrayList<Integer> mainList = .............;
List<List<Integer>> multipleLists = ListUtils.partition(mainList,100);
int i=1;
for (List<Integer> indexedList : multipleLists){
System.out.println("Values in List "+i);
for (Integer value : indexedList)
System.out.println(value);
i++;
}
Set the auto increment field to NULL or 0 if you want it to be auto magically assigned...
In IIS7 with integrated mode, Current
is not available in Application_Start
. There is a similar thread here.
if (File.Exists(Server.MapPath("~/Images/associates/" + Html.DisplayFor(modelItem => item.AssociateImage))))
{
<img src="~/Images/associates/@Html.DisplayFor(modelItem => item.AssociateImage)">
}
else
{
<h5>No image available</h5>
}
I did something like this for checking to see if an image existed before displaying it.
php_value error_log "/var/log/httpd/vhost_php_error_log"
It works for me, but I have to change the permission of the log file.
or Apache will write the log to the its error_log
.
I usually use set_time_limit(30) within the main loop (so each loop iteration is limited to 30 seconds rather than the whole script).
I do this in multiple database update scripts, which routinely take several minutes to complete but less than a second for each iteration - keeping the 30 second limit means the script won't get stuck in an infinite loop if I am stupid enough to create one.
I must admit that my choice of 30 seconds for the limit is somewhat arbitrary - my scripts could actually get away with 2 seconds instead, but I feel more comfortable with 30 seconds given the actual application - of course you could use whatever value you feel is suitable.
Hope this helps!
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
Generally RuntimeExceptions are exceptions that can be prevented programmatically. E.g NullPointerException
, ArrayIndexOutOfBoundException
. If you check for null
before calling any method, NullPointerException
would never occur. Similarly ArrayIndexOutOfBoundException
would never occur if you check the index first. RuntimeException
are not checked by the compiler, so it is clean code.
EDIT : These days people favor RuntimeException
because the clean code it produces. It is totally a personal choice.
Another example for the C++11 standard:
set<int> data;
data.insert(4);
data.insert(5);
for (const int &number : data)
cout << number;
Adapted from Not So Frequently Asked Questions:
#include <algorithm>
#include <cctype>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });
You're really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.
If you really hate tolower()
, here's a specialized ASCII-only alternative that I don't recommend you use:
char asciitolower(char in) {
if (in <= 'Z' && in >= 'A')
return in - ('Z' - 'z');
return in;
}
std::transform(data.begin(), data.end(), data.begin(), asciitolower);
Be aware that tolower()
can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.
I saw very bad regexes in this page.. so i came with my own:
\b((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b
Explanation:
num-group = (0-9|10-99|100-199|200-249|250-255)
<border> + { <num-group> + <dot-cahracter> }x3 + <num-group> + <border>
Here you can verify how it works here
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
Since I don't believe "Please use..." plus some random code that is unrelated to the question
is a good answer, but I do believe the spirit was correct, I decided to answer this correctly.
When you are using Sql Bulk Copy, it attempts to align your input data directly with the data on the server. So, it takes the Server Table and performs a SQL statement similar to this:
INSERT INTO [schema].[table] (col1, col2, col3) VALUES
Therefore, if you give it Columns 1, 3, and 2, EVEN THOUGH your names may match (e.g.: col1, col3, col2). It will insert like so:
INSERT INTO [schema].[table] (col1, col2, col3) VALUES
('col1', 'col3', 'col2')
It would be extra work and overhead for the Sql Bulk Insert to have to determine a Column Mapping. So it instead allows you to choose... Either ensure your Code and your SQL Table columns are in the same order, or explicitly state to align by Column Name.
Therefore, if your issue is mis-alignment of the columns, which is probably the majority of the cause of this error, this answer is for you.
using System.Data;
//...
myDataTable.Columns.Cast<DataColumn>().ToList().ForEach(x =>
bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(x.ColumnName, x.ColumnName)));
This will take your existing DataTable, which you are attempt to insert into your created BulkCopy object, and it will just explicitly map name to name. Of course if, for some reason, you decided to name your DataTable Columns differently than your SQL Server Columns... that's on you.
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
I find it quite overkill enforce the validity of the href attribute with such a complex and cryptic pattern while a simple expression such as
<a\s+(?:[^>]*?\s+)?href="([^"]*)"
would suffice to capture all URLs. If you want to make sure they contain at least a query string, you could just use
<a\s+(?:[^>]*?\s+)?href="([^"]+\?[^"]+)"
st = @"((www\.|https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+ \w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"<a href[^>]*>(.*?)</a>";
st = @"((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)";
st = @"((?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)[\w\d:#@%/;$()~_?\+,\-=\\.&]+)";
st = @"(?:(?:https?|ftp|gopher|telnet|file|notes|ms-help):(?://|\\\\)(?:www\.)?|www\.)";
st = @"(((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+)|(www\.)[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
st = @"href=[""'](?<url>(http|https)://[^/]*?\.(com|org|net|gov))(/.*)?[""']";
st = @"(<a.*?>.*?</a>)";
st = @"(?:hrefs*=)(?:[s""']*)(?!#|mailto|location.|javascript|.*css|.*this.)(?.*?)(?:[s>""'])";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
st = @"(http|https)://([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?)";
st = @"http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?";
st = @"http(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$";
st = @"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*";
my choice is
@"(?<Protocol>\w+):\/\/(?<Domain>[\w.]+\/?)\S*"
Second Use this:
st = "(.*)?(.*)=(.*)";
Basically we had to enable TLS 1.2 for .NET 4.x. Making this registry changed worked for me, and stopped the event log filling up with the Schannel error.
More information on the answer can be found here
Enable TLS 1.2 at the system (SCHANNEL) level:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2]
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
"Enabled"=dword:00000001
(equivalent keys are probably also available for other TLS versions)
Tell .NET Framework to use the system TLS versions:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
This may not be desirable for edge cases where .NET Framework 4.x applications need to have different protocols enabled and disabled than the OS does.
These two approaches produce identical dictionaries, except, as you've noted, where the lexical rules of Python interfere.
Dictionary literals are a little more obviously dictionaries, and you can create any kind of key, but you need to quote the key names. On the other hand, you can use variables for keys if you need to for some reason:
a = "hello"
d = {
a: 'hi'
}
The dict()
constructor gives you more flexibility because of the variety of forms of input it takes. For example, you can provide it with an iterator of pairs, and it will treat them as key/value pairs.
I have no idea why PyCharm would offer to convert one form to the other.
background-image: url("/your-dir/your_image.jpg");
min-height: 100%;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
background-size: cover;}
Use android:divider="#FF0000"
and android:dividerHeight="2px"
for ListView.
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#0099FF"
android:dividerHeight="2px"/>
Conditional Welcome Message
echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';
Nested PHP Shorthand
echo 'Your score is: '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );
In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.
class OuterClass:
def __init__(self):
self.outer_var = 1
self.inner_class = OuterClass.InnerClass(self)
print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)
class InnerClass:
def __init__(self, outer_class):
self.outer_class = outer_class
self.inner_var = 2
print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)
<form action="" onsubmit="additon()" name="form1" id="form1">
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="b"><br>
<input type="submit" value="Submit" name="submit">
</form>
<script>
function additon()
{
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
var sum = parseInt(a) + parseInt(b);
return sum;
}
</script>
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
// *.h file
// ...
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void* mylibrary_mytype_t;
EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);
#undef EXTERNC
// ...
// *.cpp file
mylibrary_mytype_t mylibrary_mytype_init() {
return new MyType;
}
void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
delete typed_ptr;
}
void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
MyType* typed_self = static_cast<MyType*>(untyped_self);
typed_self->doIt(param);
}
Reason #1
There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.
Reason #2
When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars()
function is one such example. Though there are optional arguments to htmlspecialchars()
that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.
awk '$0="prefix"$0' file > new_file
With Perl(in place replacement):
perl -pi 's/^/prefix/' file
Join the table with itself and give it two different aliases (A
and B
in the following example). This allows to compare different rows of the same table.
SELECT DISTINCT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
A.Address <> B.Address
The "less than" comparison <
ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <>
instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A
alias and the B
alias in turn.
The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.
The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to
SELECT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id
WHERE
A.[Adress Code] = 1 AND
B.[Adress Code] = 2 AND
A.Address <> B.Address
I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .
The model has a save
method, which saves all the details necessary to reconstitute the model. An example from the keras documentation:
from keras.models import load_model
model.save('my_model.h5') # creates a HDF5 file 'my_model.h5'
del model # deletes the existing model
# returns a compiled model
# identical to the previous one
model = load_model('my_model.h5')
First
<table border="1">
<tr>
<td style='border:none;'>one</td>
<td style='border:none;'>two</td>
</tr>
<tr>
<td style='border:none;'>one</td>
<td style='border:none;'>two</td>
</tr>
</table>
Second example
<table border="1" cellspacing="0" cellpadding="0">
<tr>
<td style='border-left:none;border-top:none'>one</td>
<td style='border:none;'>two</td>
</tr>
<tr>
<td style='border-left:none;border-bottom:none;border-top:none'>one</td>
<td style='border:none;'>two</td>
</tr>
</table>
Alright. I have found out the file_get_contents() is not causing this problem. There's a different reason which I talk about in another question. Silly me.
See this question: Why Does DOM Change Encoding?
To disable Text you have to set the opacity:0 in Text style like this:
<TouchableOpacity style={{opacity:0}}>
<Text>I'm disabled</Text>
</TouchableOpacity>
The <=>
("Spaceship") operator will offer combined comparison in that it will :
Return 0 if values on either side are equal
Return 1 if the value on the left is greater
Return -1 if the value on the right is greater
The rules used by the combined comparison operator are the same as the currently used comparison operators by PHP viz. <
, <=
, ==
, >=
and >
. Those who are from Perl or Ruby programming background may already be familiar with this new operator proposed for PHP7.
//Comparing Integers
echo 1 <=> 1; //output 0
echo 3 <=> 4; //output -1
echo 4 <=> 3; //output 1
//String Comparison
echo "x" <=> "x"; //output 0
echo "x" <=> "y"; //output -1
echo "y" <=> "x"; //output 1
You can try this script in the header of HTML code:
<script>
$.extend( $.mobile , {
ajaxEnabled: false,
hashListeningEnabled: false
});
</script>
import re
regex = ur"\[P\] (.+?) \[/P\]+?"
line = "President [P] Barack Obama [/P] met Microsoft founder [P] Bill Gates [/P], yesterday."
person = re.findall(regex, line)
print(person)
yields
['Barack Obama', 'Bill Gates']
The regex ur"[\u005B1P\u005D.+?\u005B\u002FP\u005D]+?"
is exactly the same
unicode as u'[[1P].+?[/P]]+?'
except harder to read.
The first bracketed group [[1P]
tells re that any of the characters in the list ['[', '1', 'P']
should match, and similarly with the second bracketed group [/P]]
.That's not what you want at all. So,
1
in front of P
.)[P]
, escape the brackets with a
backslash: \[P\]
..+?
.You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
Don't change the name of the dockerfile if you want to use the autobuilder at hub.docker.com. Don't use an extension for docker files, leave it null. File name should just be: (no extension at all)
Dockerfile
Stripe has a PHP library to accept credit cards without needing a merchant account: https://github.com/stripe/stripe-php
Check out the documentation and FAQ, and feel free to drop by our chatroom if you have more questions.
You should use the following code from the support library instead:
ContextCompat.getDrawable(context, R.drawable.***)
Using this method is equivalent to calling:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return resources.getDrawable(id, context.getTheme());
} else {
return resources.getDrawable(id);
}
As of API 21, you should use the getDrawable(int, Theme)
method instead of getDrawable(int)
, as it allows you to fetch a drawable object associated with a particular resource ID for the given screen density/theme. Calling the deprecated getDrawable(int)
method is equivalent to calling getDrawable(int, null)
.
MacOS: composer is available on brew now (Tested on Php7+):
brew install composer
Install instructions on the Composer Docs page are quite to the point otherwise.
Use a resize sensor from the css-element-queries library:
https://github.com/marcj/css-element-queries
new ResizeSensor(jQuery('#myElement'), function() {
console.log('myelement has been resized');
});
It uses a event based approach and doesn't waste your cpu time. Works in all browsers incl. IE7+.
You need turn on the POP mail and IMAP mail feature in setting of the email you are using to send mail. Good luck!
contents = open(filename).read()
When we insert any line break with a programming language the char code for this is "\n". php does output that but html can't display that due to htmls line break is
. so easy way to do this job is replacing all the "\n" with "
". so the code should be
str_replace("\n","<br/>",$str);
after adding this code you wont have to use pre tag for all the output oparation.
You can do it with an confirm()
message using Javascript.
I have created a libray for pick image from camera or galley and cropping also
Try this,
ImagePro.Java
public class ImagePro
{
public static String TAG = "ImagePro";
Activity activity;
Uri mImageCaptureUri;
public static int CAMERA_CODE = 64;
public static int GALLERY_CODE = 74;
public static int CROPPING_CODE = 84;
private final static int REQUEST_PERMISSION_REQ_CODE = 704;
public ImagePro(Activity activity) {
this.activity = activity;
this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
}
}
private void LogToast(String message) {
try {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, message);
}
private void Toast(String message) {
try {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void Log(String message) {
Log.d(TAG, message);
}
/**
* This function return captured image path
*
* @param requestCode on activity result requestCode
* @param resultCode on activity result resultCode
* @param intent on activity result intent
* @return ImageDetails values
*/
public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) {
ImageDetails imageDetails = new ImageDetails();
if(resultCode == Activity.RESULT_OK) {
if(requestCode == CAMERA_CODE) {
imageDetails.setUri(mImageCaptureUri);
imageDetails.setPath(mImageCaptureUri.getPath());
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri);
} catch (IOException e) {
LogToast(e.getMessage());
e.printStackTrace();
}
imageDetails.setBitmap(bitmap);
imageDetails.setFile(new File(mImageCaptureUri.getPath()));
} else if(requestCode == GALLERY_CODE) {
Uri uri = intent.getData();
imageDetails.setUri(uri);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
} catch (IOException e) {
LogToast(e.getMessage());
e.printStackTrace();
}
imageDetails.setBitmap(bitmap);
imageDetails.setFile(new File(uri.getPath()));
imageDetails.setPath(uri.getPath());
} else if(requestCode == CROPPING_CODE) {
try {
if(outPutFile.exists()){
imageDetails.setUri(Uri.fromFile(outPutFile));
imageDetails.setFile(outPutFile);
imageDetails.setPath(outPutFile.getPath());
Bitmap photo = decodeFile(outPutFile);
imageDetails.setBitmap(photo);
}
else {
LogToast("Error while save image");
}
} catch (Exception e) {
e.printStackTrace();
LogToast(e.getMessage());
}
}
} else {
LogToast("user cancelled.");
}
return imageDetails;
}
/**
* Open image pick dialog.<br/>
* CAMERA_CODE</br>
* GALLERY_CODE
*/
public void openImagePickOption() {
final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Capture Photo")) {
captureImage();
} else if (items[item].equals("Choose from Gallery")) {
pickImage();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
/**
* decode from file to bitmap
* @param f file
* @return Bitmap data
*/
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 512;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
Log(e.getMessage());
}
return null;
}
/**
* Capture image using camera <br/>
* REQUEST_CODE = ImagePro.CAMERA_CODE
*/
public void captureImage() {
if(activity != null) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
mImageCaptureUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
activity.startActivityForResult(intent, CAMERA_CODE);
} else {
LogToast("Activity not assigned");
}
}
/**
* pick image from gallery
*/
public void pickImage() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activity.startActivityForResult(i, GALLERY_CODE);
}
/**
* cropping the uri image
* @param uri - open cropping dialog using the uri data
*/
public void croppingImage(Uri uri) {
CroppingIMG(uri);
}
int CROP_IMG_X=512;
int CROP_IMG_Y=512;
public void croppingImage(Uri uri, int cropX, int cropY) {
CROP_IMG_X = cropX;
CROP_IMG_Y = cropY;
CroppingIMG(uri);
}
File outPutFile=null;
private void CroppingIMG(Uri uri) {
final ArrayList<CroppingOption> cropOptions = new ArrayList<>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = activity.getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
LogToast("Can't find image croping app");
} else {
intent.setData(uri);
intent.putExtra("outputX", CROP_IMG_X);
intent.putExtra("outputY", CROP_IMG_Y);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
//Create output file here
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
activity.startActivityForResult(i, CROPPING_CODE);
} else {
for (ResolveInfo res : list) {
final CroppingOption co = new CroppingOption();
co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Choose Cropping App");
builder.setCancelable(false);
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
@Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
activity.getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
/**
* Capture image using camera<br/>
* REQUEST_CODE = User defined code<br/>
* <br/>
* @param iRequestCode User defined code
*/
public void captureImage(int iRequestCode) {
CAMERA_CODE = iRequestCode;
captureImage();
}
/**
* get path, bitmap, file and uri from image details object
*/
public class ImageDetails {
String path="";
Bitmap bitmap=null;
File file=null;
Uri uri=null;
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
/**
* Created by DP on 7/12/2016.
*/
public class CroppingOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
public class CropingOptionAdapter extends ArrayAdapter {
private ArrayList<CroppingOption> mOptions;
private LayoutInflater mInflater;
public CropingOptionAdapter(Context context, ArrayList<CroppingOption> options) {
super(context, R.layout.croping_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.croping_selector, null);
CroppingOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);
return convertView;
}
return null;
}
}
}
MainActivity.java
ImagePro imagePro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePro = new ImagePro(this);
}
public void onClickUploadImageButton(View view) {
imagePro.openImagePickOption();
}
onActivityResult
if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data);
ivCrop.setImageBitmap(imageDetails.getBitmap());
//imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile
}
Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.
Ajax call:
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'html',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data == '') ? 'error' : 'success')
.html(data).show(500);
if (data == '') {
$('#message').html("Format your email correcly");
$('#demoForm').show(500);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
post.php
<?php
sleep(1);
function processEmail($email) {
if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
// your logic here (ex: add into database)
return true;
}
return false;
}
if (processEmail($_POST['email'])) {
echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}
This answer follows on to owlstead and Mat's responses. It applies to SE/EE installations, not ME/mobile/Android SSL.
Since no one has yet mentioned it, I'll mention the "production way" to fix this: Follow the steps from the AuthSSLProtocolSocketFactory class in HttpClient to update your trust store & key stores.
keytool -import -alias "my server cert" -file server.crt -keystore my.truststore
keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore
keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore
(self-sign or get your cert signed)
Import the trusted CA root certificate
keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore
keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
keytool -list -v -keystore my.keystore
If you don't have a server certificate, generate one in JKS format, then export it as a CRT file. Source: keytool documentation
keytool -genkey -alias server-alias -keyalg RSA -keypass changeit
-storepass changeit -keystore my.keystore
keytool -export -alias server-alias -storepass changeit
-file server.crt -keystore my.keystore
public static int[] removeDuplicates(int[] arr) {
int end = arr.length;
HashSet<Integer> set = new HashSet<Integer>(end);
for(int i = 0 ; i < end ; i++){
set.add(arr[i]);
}
return set.toArray();
}
javac
is the Java compiler. java
is the JVM and what you use to execute a Java program. You do not execute .java
files, they are just source files.
Presumably there is .jar
somewhere (or a directory containing .class
files) that is the product of building it in Eclipse:
java/src/com/mypackage/Main.java java/classes/com/mypackage/Main.class java/lib/mypackage.jar
From directory java
execute:
java -cp lib/mypackage.jar Main arg1 arg2
If you're looking to replace more than a single character, and are dealing only with std::string
, then this snippet would work, replacing sNeedle in sHaystack with sReplace, and sNeedle and sReplace do not need to be the same size. This routine uses the while loop to replace all occurrences, rather than just the first one found from left to right.
while(sHaystack.find(sNeedle) != std::string::npos) {
sHaystack.replace(sHaystack.find(sNeedle),sNeedle.size(),sReplace);
}
remove_indices = [1,2,3]
somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
Example:
In [9]: remove_indices = [1,2,3]
In [10]: somelist = range(10)
In [11]: somelist = [i for j, i in enumerate(somelist) if j not in remove_indices]
In [12]: somelist
Out[12]: [0, 4, 5, 6, 7, 8, 9]
or:
using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...
This functionality has been added to the IDE now (working Pycharm 2018.3)
Just click the EnvFile
tab in the run configuration, click Enable EnvFile
and click the + icon to add an env file
Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.
Try this:
There are several ways to do this. You can use ref
parameters:
int Foo(ref Bar bar) { }
This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an int
and (potentially) modify bar
.
Another similar approach is to use an out
parameter. An out
parameter is identical to a ref
parameter with an additional, compiler enforced rule. This rule is that if you pass an out
parameter into a function, that function is required to set its value prior to returning. Besides that rule, an out
parameter works just like a ref
parameter.
The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:
class FooBar
{
public int i { get; set; }
public Bar b { get; set; }
}
FooBar Foo(Bar bar) { }
This final approach is simpler and easier to read and understand.
In setup.py under setup( :
setup(
name = 'foo library'
...
package_data={
'foolibrary.folderA': ['*'], # All files from folder A
'foolibrary.folderB': ['*.txt'] #All text files from folder B
},
The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()
//** Returns now in ISO format in Central Time */
export function getNowISO() {
return `${moment().toISOString(true).substring(0, 23)}Z`
}
_x000D_
This will leave you with an exact ISO-formatted, localized string.
Important note: Moment now suggests using other packages for new projects.
There is one important, and useful, distinction between the two.
Because .ForEach uses a for
loop to iterate the collection, this is valid (edit: prior to .net 4.5 - the implementation changed and they both throw):
someList.ForEach(x => { if(x.RemoveMe) someList.Remove(x); });
whereas foreach
uses an enumerator, so this is not valid:
foreach(var item in someList)
if(item.RemoveMe) someList.Remove(item);
tl;dr: Do NOT copypaste this code into your application!
These examples aren't best practice, they are just to demonstrate the differences between ForEach()
and foreach
.
Removing items from a list within a for
loop can have side effects. The most common one is described in the comments to this question.
Generally, if you are looking to remove multiple items from a list, you would want to separate the determination of which items to remove from the actual removal. It doesn't keep your code compact, but it guarantees that you do not miss any items.
Yes, you can write virtual "functions" in Java.
I use this one line of code, it should do it:
<input type="password"
onmousedown="this.type='text'"
onmouseup="this.type='password'"
onmousemove="this.type='password'">
Adding one more scalable solution.
lists = [lst1, lst2, lst3, lst4]
df = pd.concat([pd.Series(x) for x in lists], axis=1)
Looking at the dates for which it doesn't work -- those where the day is less than or equal to 12 -- I'm wondering whether it's parsing the dates as being in YYYY-DD-MM format?
Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in
<![CDATA[ ...raw html... ]]>
Example:
<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>
Then, in your code:
TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));
IMHO, this is several orders of magnitude nicer to work with :-)
Put all the commands on to a script and it can be run like
ssh <remote-user>@<remote-host> "bash -s" <./remote-commands.sh
If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:
Given test:
use v5.14;
say 1;
say 2;
say 3;
Start a listener on whatever host and port on terminal 1 (here localhost:12345
):
$ nc -v -l localhost -p 12345
For readline support use rlwrap (you can use on perl -d
too):
$ rlwrap nc -v -l localhost -p 12345
And start the test on another terminal (say terminal 2):
$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test
Input/Output on terminal 1:
Connection from 127.0.0.1:42994
Loading DB routines from perl5db.pl version 1.49
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(test:2): say 1;
DB<1> n
main::(test:3): say 2;
DB<1> select $DB::OUT
DB<2> n
2
main::(test:4): say 3;
DB<2> n
3
Debugged program terminated. Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
DB<2>
Output on terminal 2:
1
Note the sentence if you want output on debug terminal
select $DB::OUT
If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.
Use single quotation marks ('
):
var val = '@ViewBag.ForSection';
alert(val);
Just replace with "/" for file path :
open("description_files/program_description.txt","r")
You need to add the Servlet API to your classpath. In Tomcat 6.0, this is in a JAR called servlet-api.jar
in Tomcat's lib
folder. You can either add a reference to that JAR to the project's classpath, or put a copy of the JAR in your Eclipse project and add it to the classpath from there.
If you want to leave the JAR in Tomcat's lib
folder:
servlet-api.jar
and select it.Or, if you copy the JAR into your project:
servlet-api.jar
in your project and select it.I see many perfect answers are up on the board, but still would like to upload my piece of code too,
awk -F"/" '{print $3 " " $5 " " $7}' sam | sed 's/ cat.* =//g'
Actually i wanted to achieve exactly that in PHP but none of the answers here were very helpful so here's my – pretty straightforward – solution using MySQLi:
// Database variables
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '1234';
$DB_SRC = 'existing_db';
$DB_DST = 'newly_created_db';
// MYSQL Connect
$mysqli = new mysqli( $DB_HOST, $DB_USER, $DB_PASS ) or die( $mysqli->error );
// Create destination database
$mysqli->query( "CREATE DATABASE $DB_DST" ) or die( $mysqli->error );
// Iterate through tables of source database
$tables = $mysqli->query( "SHOW TABLES FROM $DB_SRC" ) or die( $mysqli->error );
while( $table = $tables->fetch_array() ): $TABLE = $table[0];
// Copy table and contents in destination database
$mysqli->query( "CREATE TABLE $DB_DST.$TABLE LIKE $DB_SRC.$TABLE" ) or die( $mysqli->error );
$mysqli->query( "INSERT INTO $DB_DST.$TABLE SELECT * FROM $DB_SRC.$TABLE" ) or die( $mysqli->error );
endwhile;
I incurred this error once.
It turns out I had named my program ProgramMame.ccp instead of ProgramName.cpp
easy to do ...
Hope this may help
This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.
set.py:
import sys
sys.path.append("/tmp/TEST")
loop.py
import sys
import time
while True:
print sys.path
time.sleep(1)
run: python loop.py &
This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py
. Each has a different set of environment variables. Observe that the output from loop.py
does not change because set.py
does not change loop.py
's environment.
A note on importing
Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append...
.
You may think about factories
class XyFactory {
public function createXyObject ($other) {
$new = new XyObject($other->someValue);
// Do other things, that let $new look like $other (except the used class)
return $new;
}
}
Otherwise user250120s solution is the only one, which comes close to class casting.
check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html
one needs to use something like
cmd.CommandText = "BEGIN foo@v; END;"
worked for me in vb.net, c#
I personally use Style It for inline-style in React or keep my style separately in a CSS or SASS file...
But if you are really interested doing it inline, look at the library, I share some of the usages below:
In the component:
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
return (
<Style>
{`
.intro {
font-size: 40px;
}
`}
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
</Style>
);
}
}
export default Intro;
Output:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 40px;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
Also you can use JavaScript variables with hover in your CSS as below :
import React from 'react';
import Style from 'style-it';
class Intro extends React.Component {
render() {
const fontSize = 13;
return Style.it(`
.intro {
font-size: ${ fontSize }px; // ES2015 & ES6 Template Literal string interpolation
}
.package {
color: blue;
}
.package:hover {
color: aqua;
}
`,
<p className="intro">CSS-in-JS made simple -- just Style It.</p>
);
}
}
export default Intro;
And the result as below:
<p class="intro _scoped-1">
<style type="text/css">
._scoped-1.intro {
font-size: 13px;
}
._scoped-1 .package {
color: blue;
}
._scoped-1 .package:hover {
color: aqua;
}
</style>
CSS-in-JS made simple -- just Style It.
</p>
If you were looking for what to use in android, it is:
String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens)
for example:
String joined = TextUtils.join(";", MyStringArray);
Unfortunately - it could be many things - and lots of app servers and other java 'wrappers' are prone to play with properties and their 'own' take on keychains and what not. So it may be looking at something totally different.
Short of truss-ing - I'd try:
java -Djavax.net.debug=all -Djavax.net.ssl.trustStore=trustStore ...
to see if that helps. Instead of 'all' one can also set it to 'ssl', key manager and trust manager - which may help in your case. Setting it to 'help' will list something like below on most platforms.
Regardless - do make sure you fully understand the difference between the keystore (in which you have the private key and cert you prove your own identity with) and the trust store (which determines who you trust) - and the fact that your own identity also has a 'chain' of trust to the root - which is separate from any chain to a root you need to figure out 'who' you trust.
all turn on all debugging
ssl turn on ssl debugging
The following can be used with ssl:
record enable per-record tracing
handshake print each handshake message
keygen print key generation data
session print session activity
defaultctx print default SSL initialization
sslctx print SSLContext tracing
sessioncache print session cache tracing
keymanager print key manager tracing
trustmanager print trust manager tracing
pluggability print pluggability tracing
handshake debugging can be widened with:
data hex dump of each handshake message
verbose verbose handshake message printing
record debugging can be widened with:
plaintext hex dump of record plaintext
packet print raw SSL/TLS packets
Source: # See http://download.oracle.com/javase/1.5.0/docs/guide/security/jsse/JSSERefGuide.html#Debug
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
Using inline styles:
<input type="text" style="text-align: right"/>
or, put it in a style sheet, like so:
<style>
.rightJustified {
text-align: right;
}
</style>
and reference the class:
<input type="text" class="rightJustified"/>
What is the difference?
From the documentation:
- - (Boolean)
instance_of?(class)
- Returns
true
ifobj
is an instance of the given class.
and:
- - (Boolean)
is_a?(class)
- (Boolean)kind_of?(class)
- Returns
true
ifclass
is the class ofobj
, or ifclass
is one of the superclasses ofobj
or modules included inobj
.
If that is unclear, it would be nice to know what exactly is unclear, so that the documentation can be improved.
When should I use which?
Never. Use polymorphism instead.
Why are there so many of them?
I wouldn't call two "many". There are two of them, because they do two different things.
I just came across a similar problem. Try
require './st.rb'
This should do the trick.
Well I did a bit of searching around the internet for you and I found this handy link.
Easiest way to find duplicate values in a JavaScript array
You can adapt the sample code that is provided in the above link, courtesy of "swilliams" to your solution.
try this:
$('div[id^="player_"]')
From http://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily:
Set the default value for the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell
to 0
document.write(`<td width='74'><button id='button' type='button' onclick='myfunction(\``+ name + `\`)'>click</button></td>`)
Better to use `` than "". This is a more dynamic answer.
Necromancing.
In .NET Core/NetStandard2, you can use Nito.AsyncEx.AsyncContext.Run
instead of System.Windows.Threading.Dispatcher.InvokeAsync
:
class AsyncPropertyTest
{
private static async System.Threading.Tasks.Task<int> GetInt(string text)
{
await System.Threading.Tasks.Task.Delay(2000);
System.Threading.Thread.Sleep(2000);
return int.Parse(text);
}
public static int MyProperty
{
get
{
int x = 0;
// https://stackoverflow.com/questions/6602244/how-to-call-an-async-method-from-a-getter-or-setter
// https://stackoverflow.com/questions/41748335/net-dispatcher-for-net-core
// https://github.com/StephenCleary/AsyncEx
Nito.AsyncEx.AsyncContext.Run(async delegate ()
{
x = await GetInt("123");
});
return x;
}
}
public static void Test()
{
System.Console.WriteLine(System.DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff"));
System.Console.WriteLine(MyProperty);
System.Console.WriteLine(System.DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss.fff"));
}
}
If you simply chose System.Threading.Tasks.Task.Run
or System.Threading.Tasks.Task<int>.Run
, then it wouldn't work.
you should examine the specification before using 'remainder' operator % :
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.17.3
// bad enough implementation of isEven method, for fun. so any worse?
boolean isEven(int num)
{
num %= 10;
if(num == 1)
return false;
else if(num == 0)
return true;
else
return isEven(num + 2);
}
isEven = isEven(a);
In case it helps anyone, I had this exact same problem and discovered that it was caused by the "Do Not Track Plus" Chrome Extension (version 2.0.8). When I disabled that extension, the image loaded without error.
These days, you can leverage the .NET library from VBA. The following works for me in Excel 2016. Returns the hash as uppercase hex.
Public Function SHA1(ByVal s As String) As String
Dim Enc As Object, Prov As Object
Dim Hash() As Byte, i As Integer
Set Enc = CreateObject("System.Text.UTF8Encoding")
Set Prov = CreateObject("System.Security.Cryptography.SHA1CryptoServiceProvider")
Hash = Prov.ComputeHash_2(Enc.GetBytes_4(s))
SHA1 = ""
For i = LBound(Hash) To UBound(Hash)
SHA1 = SHA1 & Hex(Hash(i) \ 16) & Hex(Hash(i) Mod 16)
Next
End Function
$("element").data('bs.modal').isShown
won't work if the modal hasn't been shown before. You will need to add an extra condition:
$("element").data('bs.modal')
so the answer taking into account first appearance:
if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
...
}
In my case, I execute taskkill /f /im dongleserver.exe
,
where dongleserver.exe
is my program's exe file.
Then I can able to reinstall my program already.
PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2
You can use this constant when you read or write text files on the server's filesystem.
Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.
If line endings matter, explicitly specify the line endings instead of using the constant. For example:
\r\n
\r\n
as row separatorIf this is for a non-Rails project, I'd use String#index
:
"foobar".index("foo") == 0 # => true
in cmd window type:
type nul > your_file.txt
This will create 0 bytes in your_file.txt file.
Another way of doing it is by using the echo command:
echo.> your_file.txt
echo. - will create a file with one empty line in it.
Edited on 2019-04-01:
If you need to preserve the content of the file use >>
instead of >
> Creates a new file
>> Preserves content of the file
Example
type nul >> your_file.txt
Edited on 2020-04-07
You can also use call command.
Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call.
Example:
call >> your_file.txt
Uri to String
Uri uri;
String stringUri;
stringUri = uri.toString();
String to Uri
Uri uri;
String stringUri;
uri = Uri.parse(stringUri);
More on Windows... variable java.home is not always the same location as the binary that is run.
As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm's program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.
One way to hunt down the location of the java.exe binary, add the following line to PeterMmm's code to keep the program running a while longer:
try{Thread.sleep(60000);}catch(Exception e) {}
Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select 'open file location', this opens the exact location of the Java binary. In this case it would be System32.
var files = Directory.GetFiles(@"E:\ftproot\sales");
Sometimes onsubmit
wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
There is a package called yum-utils
that builds on YUM and contains a tool called repoquery
that can do this.
$ repoquery --help | grep -E "list\ files"
-l, --list list files in this package/group
Combined into one example:
$ repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz
On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, repoquery -l rpm
prints nothing.
If you are having this issue, try adding the --installed
flag: repoquery --installed -l rpm
.
DNF
Update:To use dnf
instead of yum-utils
, use the following command:
$ dnf repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz
Is this what you are trying to do?
# Our data
text <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13",
"F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)
# Split into individual elements by the '.' character
# Remember to escape it, because '.' by itself matches any single character
elems <- unlist( strsplit( text , "\\." ) )
# We know the dataframe should have 4 columns, so make a matrix
m <- matrix( elems , ncol = 4 , byrow = TRUE )
# Coerce to data.frame - head() is just to illustrate the top portion
head( as.data.frame( m ) )
# V1 V2 V3 V4
#1 F US CLE V13
#2 F US CA6 U13
#3 F US CA6 U13
#4 F US CA6 U13
#5 F US CA6 U13
#6 F US CA6 U13
SELECT CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
WHEN SERVERPROPERTY('EditionID') = -2117995310 THEN 'Developer'
WHEN SERVERPROPERTY('EditionID') = 610778273 THEN 'Windows Embedded SQL'
WHEN SERVERPROPERTY('EditionID') = 4161255391 THEN 'Express with Advanced Services'
END AS 'Edition';
The modern approach uses java.time classes.
Instant.now() // Capture current moment in UTC.
.truncatedTo( ChronoUnit.SECONDS ) // Lop off any fractional second.
.plus( 8 , ChronoUnit.HOURS ) // Add eight hours.
.atZone( ZoneId.of( "America/Montreal" ) ) // Adjust from UTC to the wall-clock time used by the people of a certain region (a time zone). Returns a `ZonedDateTime` object.
.format( // Generate a `String` object representing textually the value of the `ZonedDateTime` object.
DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" )
.withLocale( Locale.US ) // Specify a `Locale` to determine the human language and cultural norms used in localizing the text being generated.
) // Returns a `String` object.
23/01/2017 15:34:56
FYI, the old Calendar
and Date
classes are now legacy. Supplanted by the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
Instant
Capture the current moment in UTC with the Instant
class.
Instant instantNow = Instant.now();
instant.toString(): 2017-01-23T12:34:56.789Z
If you want only whole seconds, without any fraction of a second, truncate.
Instant instant = instantNow.truncatedTo( ChronoUnit.SECONDS );
instant.toString(): 2017-01-23T12:34:56Z
The Instant
class can do math, adding an amount of time. Specify the amount of time to add by the ChronoUnit
enum, an implementation of TemporalUnit
.
instant = instant.plus( 8 , ChronoUnit.HOURS );
instant.toString(): 2017-01-23T20:34:56Z
ZonedDateTime
To see that same moment through the lens of a particular region’s wall-clock time, apply a ZoneId
to get a ZonedDateTime
.
Specify a proper time zone name in the format of continent/region
, such as America/Montreal
, Africa/Casablanca
, or Pacific/Auckland
. Never use the 3-4 letter abbreviation such as EST
or IST
as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
zdt.toString(): 2017-01-23T15:34:56-05:00[America/Montreal]
You can generate a String in your desired format by specifying a formatting pattern in a DateTimeFormatter
object.
Note that case matters in the letters of your formatting pattern. The Question’s code had hh
which is for 12-hour time while uppercase HH
is 24-hour time (0-23) in both java.time.DateTimeFormatter
as well as the legacy java.text.SimpleDateFormat
.
The formatting codes in java.time are similar to those in the legacy SimpleDateFormat
but not exactly the same. Carefully study the class doc. Here, HH
happens to work identically.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu HH:mm:ss" ).withLocale( Locale.US );
String output = zdt.format( f );
Rather than hard-coding a formatting pattern, consider letting java.time fully localize the generation of the String
text by calling DateTimeFormatter.ofLocalizedDateTime
.
And, by the way, be aware that time zone and Locale
have nothing to do with one another; orthogonal issues. One is about content, the meaning (the wall-clock time). The other is about presentation, determining the human language and cultural norms used in presenting that meaning to the user.
Instant instant = Instant.parse( "2017-01-23T12:34:56Z" );
ZoneId z = ZoneId.of( "Pacific/Auckland" ); // Notice that time zone is unrelated to the `Locale` used in localizing.
ZonedDateTime zdt = instant.atZone( z );
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( Locale.CANADA_FRENCH ); // The locale determines human language and cultural norms used in generating the text representing this date-time object.
String output = zdt.format( f );
instant.toString(): 2017-01-23T12:34:56Z
zdt.toString(): 2017-01-24T01:34:56+13:00[Pacific/Auckland]
output: mardi 24 janvier 2017 à 01:34:56 heure avancée de la Nouvelle-Zélande
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.
Joda-Time makes this kind of work much easier.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
DateTime later = DateTime.now().plusHours( 8 );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd/MM/yyyy HH:mm:ss" );
String laterAsText = formatter.print( later );
System.out.println( "laterAsText: " + laterAsText );
When run…
laterAsText: 19/12/2013 02:50:18
Beware that this syntax uses default time zone. A better practice is to use an explicit DateTimeZone instance.
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
When trying to translate Excel file with .xlsx suffix, you need to add additional jar, xmlbeansxxx.jar. xxxx is version, such as xmlbeans-2.3.0.jar
If you want auto-indent just like Emacs does it on TAB, i.e. indent the current line and move the cursor to the first non-whitespace character, do this:
Insert the following macro code:
reindent-line caret-line-first-column caret-begin-line
Click "Set Shortcut" and press TAB
I like @jesterjunk answer, however, a number is not always just digits. Consider those valid numbers: "123.5, 123,567.789, 12233234+E12"
So I just updated the regular expression:
var regex = /[\d|,|.|e|E|\+]+/g;
var string = "you can enter maximum 5,123.6 choices";
var matches = string.match(regex); // creates array from matches
document.write(matches); //5,123.6
Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:
Public Sub SubA()
On Error Goto ProcError
Connection.Open
Open File for Writing
SomePreciousResource.GrabIt
ProcExit:
Connection.Close
Connection = Nothing
Close File
SomePreciousResource.Release
Exit Sub
ProcError:
MsgBox Err.Description
Resume ProcExit
End Sub
lst = [('candy','30','100'), ('apple','10','200'), ('baby','20','300')]
lst.sort(key=lambda x:x[1])
print(lst)
It will print as following:
[('apple', '10', '200'), ('baby', '20', '300'), ('candy', '30', '100')]
$("body").on("custom-scroll", ".myDiv", function(){
console.log("Scrolled :P");
})
$("#btn").on("click", function(){
$("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
listenForScrollEvent($(".myDiv"));
});
function listenForScrollEvent(el){
el.on("scroll", function(){
el.trigger("custom-scroll");
})
}
see this post - Bind scroll Event To Dynamic DIV?
Indeed you would not be able to write the last line.
But you probably don't want to create the object, just for the sake or creating it. You probably want to call some method on your newly created instance.
You'll then need something like an interface :
public interface ITask
{
void Process(object o);
}
public class Task<T> : ITask
{
void ITask.Process(object o)
{
if(o is T) // Just to be sure, and maybe throw an exception
Process(o as T);
}
public void Process(T o) { }
}
and call it with :
Type d1 = Type.GetType("TaskA"); //or "TaskB"
Type[] typeArgs = { typeof(Item) };
Type makeme = d1.MakeGenericType(typeArgs);
ITask task = Activator.CreateInstance(makeme) as ITask;
// This can be Item, or any type derived from Item
task.Process(new Item());
In any case, you won't be statically cast to a type you don't know beforehand ("makeme" in this case). ITask allows you to get to your target type.
If this is not what you want, you'll probably need to be a bit more specific in what you are trying to achieve with this.
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
If you're looking for ES6 OOP implementation of Stack and Queue data-structure with some basic operations (based on linked lists) then it may look like this:
Queue.js
import LinkedList from '../linked-list/LinkedList';
export default class Queue {
constructor() {
this.linkedList = new LinkedList();
}
isEmpty() {
return !this.linkedList.tail;
}
peek() {
if (!this.linkedList.head) {
return null;
}
return this.linkedList.head.value;
}
enqueue(value) {
this.linkedList.append(value);
}
dequeue() {
const removedHead = this.linkedList.deleteHead();
return removedHead ? removedHead.value : null;
}
toString(callback) {
return this.linkedList.toString(callback);
}
}
Stack.js
import LinkedList from '../linked-list/LinkedList';
export default class Stack {
constructor() {
this.linkedList = new LinkedList();
}
/**
* @return {boolean}
*/
isEmpty() {
return !this.linkedList.tail;
}
/**
* @return {*}
*/
peek() {
if (!this.linkedList.tail) {
return null;
}
return this.linkedList.tail.value;
}
/**
* @param {*} value
*/
push(value) {
this.linkedList.append(value);
}
/**
* @return {*}
*/
pop() {
const removedTail = this.linkedList.deleteTail();
return removedTail ? removedTail.value : null;
}
/**
* @return {*[]}
*/
toArray() {
return this.linkedList
.toArray()
.map(linkedListNode => linkedListNode.value)
.reverse();
}
/**
* @param {function} [callback]
* @return {string}
*/
toString(callback) {
return this.linkedList.toString(callback);
}
}
And LinkedList implementation that is used for Stack and Queue in examples above may be found on GitHub here.
THE MOST ELEGANT METHOD :D
There is one easiest way to do that, no need any directives for that.
"element-that-toggle-your-dropdown" should be button tag. Use any method in (blur) attribute. That's all.
<button class="element-that-toggle-your-dropdown"
(blur)="isDropdownOpen = false"
(click)="isDropdownOpen = !isDropdownOpen">
</button>
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
The click event is not bound to your new element, use a jQuery.on
to handle the click.
The ubuntu package name is qt5-default
, not qt
.
You can add a PPA that provides a relatively current version of SmartGit(as well as SmartGitHg, the predecessor of SmartGit).
To add the PPA run:
sudo add-apt-repository ppa:eugenesan/ppa
sudo apt-get update
To install smartgit
(after adding the PPA) run:
sudo apt-get install smartgit
To install smartgithg
(after adding the PPA) run:
sudo apt-get install smartgithg
This should add a menu option for you
For more information, see Eugene San PPA.
This repository contains collection of customized, updated, ported and backported packages for two last LTS releases and latest pre-LTS release
I know that I am late to party but performed test before actually implement the solution.
I did perform test against inbuilt MD5 class and also md5sum.exe. In my case inbuilt class took 13 second where md5sum.exe too around 16-18 seconds in every run.
DateTime current = DateTime.Now;
string file = @"C:\text.iso";//It's 2.5 Gb file
string output;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(file))
{
byte[] checksum = md5.ComputeHash(stream);
output = BitConverter.ToString(checksum).Replace("-", String.Empty).ToLower();
Console.WriteLine("Total seconds : " + (DateTime.Now - current).TotalSeconds.ToString() + " " + output);
}
}
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function generateRandomSpaces() {
$output = '';
$i = rand(1, 10);
for ($j = 0; $j <= $i; $j++) {
$output .= " ";
}
return $output;
}
// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
$array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces();
}
// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
$trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";
// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk : " . $time . " seconds\n";
// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
foreach ($array as $index => $elem) {
$array[$index] = trim($elem);
}
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";
// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
for ($j = 0; $j < count($array) - 1; $j++) {
$array[$j] = trim($array[$j]);
}
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";
The output of the code above is:
Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds
This values of course may change but I would say foreach is the best option.
While you can use a virtualenv
, you don't need to. The trick is passing the PEP370 --user
argument to the setup.py
script. With the latest version of pip
, one way to do it is:
pip install --user mercurial
This should result in the hg
script being installed in $HOME/.local/bin/hg
and the rest of the hg package in $HOME/.local/lib/pythonx.y/site-packages/
.
Note, that the above is true for Python 2.6. There has been a bit of controversy among the Python core developers about what is the appropriate directory location on Mac OS X for PEP370-style user
installations. In Python 2.7 and 3.2, the location on Mac OS X was changed from $HOME/.local
to $HOME/Library/Python
. This might change in a future release. But, for now, on 2.7 (and 3.2, if hg
were supported on Python 3), the above locations will be $HOME/Library/Python/x.y/bin/hg
and $HOME/Library/Python/x.y/lib/python/site-packages
.
I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):
$.fn.hasAttribute = function(tagName, attrName){
var result = [];
$.each($(tagName), function(index, value) {
var attr = $(this).attr(attrName);
if (typeof attr !== 'undefined' && attr !== false)
result.push($(this));
});
return result;
}
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
use this to clear the previous keyboard buffer before scanning the string it will solve your problem scanner.nextLine();//this is to clear the keyboard buffer
If you want to set the Cache-Control header, there's nothing in the IIS7 UI to do this, sadly.
You can however drop this web.config in the root of the folder or site where you want to set it:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="7.00:00:00" />
</staticContent>
</system.webServer>
</configuration>
That will inform the client to cache content for 7 days in that folder and all subfolders.
You can also do this by editing the IIS7 metabase via appcmd.exe
, like so:
\Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMode:UseMaxAge \Windows\system32\inetsrv\appcmd.exe set config "Default Web Site/folder" -section:system.webServer/staticContent -clientCache.cacheControlMaxAge:"7.00:00:00"
I've got a rather indirect way. Your data should have an unique id.
First, setting a formatter
$.extend(true, $.fn.fmatter, {
numdata: function(cellvalue, options, rowdata){
return '<span class="numData" data-num="'+rowdata.num+'">'+rowdata.num+'</span>';
}
});
Use this formatter in ColModel. To retrieve ID (e.g. selected row)
var grid = $("#grid"),
rowId = grid.getGridPara('selrow'),
num = grid.find("#"+rowId+" span.numData").attr("data-num");
(or you can directly use .data() for latest jquery 1.4.4)
Don't know if this will be everybody's answer, but after some digging, here's what we came up with.
The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent
After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).
The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.
So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.
Make sure you provide a number, typically a double is used. Math.Round can take 1-3 arguments, the first argument is the variable you wish to round, the second is the number of decimal places and the third is the type of rounding.
double pay = 200 + bonus;
double pay = Math.Round(pay);
// Rounds to nearest even number, rounding 0.5 will round "down" to zero because zero is even
double pay = Math.Round(pay, 2, MidpointRounding.ToEven);
// Rounds up to nearest number
double pay = Math.Round(pay, 2, MidpointRounding.AwayFromZero);
$computername = $env:computername
[System.Net.Dns]::GetHostAddresses($computername) | where {$_.AddressFamily -notlike "InterNetworkV6"} | foreach {echo $_.IPAddressToString }
I ran into a real problem where it was indeed evil. Essentially a developer returned a reference to an object in a vector. That was Bad!!!
The full details I wrote about in Janurary: http://developer-resource.blogspot.com/2009/01/pros-and-cons-of-returing-references.html
SELECT last_value, increment_by from "other_schema".id_seq;
for adding a seq to a column where the schema is not public try this.
nextval('"other_schema".id_seq'::regclass)
First: your code did not work because you were using the positional operator $
which only identifies an element to update in an array but does not even explicitly specify its position in the array.
What you need is the filtered positional operator $[<identifier>]
. It would update all elements that match an array filter condition.
Solution:
db.collection.update({"events.profile":10}, { $set: { "events.$[elem].handled" : 0 } },
{
multi: true,
arrayFilters: [ { "elem.profile": 10 } ]
})
What the code does:
{"events.profile":10}
filters your collection and return the documents matching the filter
The $set
update operator: modifies matching fields of documents it acts on.
{multi:true}
It makes .update()
modifies all documents matching the filter hence behaving like updateMany()
{ "events.$[elem].handled" : 0 } and arrayFilters: [ { "elem.profile": 10 } ]
This technique involves the use of the filtered positional array with arrayFilters. the filtered positional array here $[elem]
acts as a placeholder for all elements in the array fields that match the conditions specified in the array filter.
I think you can do this which get your local file path
if not os.path.isdir(f_dir):
os.mkdirs(f_dir)
try:
approot = os.path.dirname(os.path.abspath(__file__))
except NameError:
approot = os.path.dirname(os.path.abspath(sys.argv[1]))
my_dir= os.path.join(approot, 'f_dir')
You can use set_xticklabels()
ax.set_xticklabels(df['Names'], rotation=90, ha='right')
I prefer the VBA-solution for professional solutions.
With the replace-procedure part in the question search and replace WHOLE WORDS ONLY, I use the following VBA-procedure:
''
' Evaluate Formula-Text in Excel
'
Function wm_Eval(myFormula As String, ParamArray variablesAndValues() As Variant) As Variant
Dim i As Long
'
' replace strings by values
'
For i = LBound(variablesAndValues) To UBound(variablesAndValues) Step 2
myFormula = RegExpReplaceWord(myFormula, variablesAndValues(i), variablesAndValues(i + 1))
Next
'
' internationalisation
'
myFormula = Replace(myFormula, Application.ThousandsSeparator, "")
myFormula = Replace(myFormula, Application.DecimalSeparator, ".")
myFormula = Replace(myFormula, Application.International(xlListSeparator), ",")
'
' return value
'
wm_Eval = Application.Evaluate(myFormula)
End Function
''
' Replace Whole Word
'
' Purpose : replace [strFind] with [strReplace] in [strSource]
' Comment : [strFind] can be plain text or a regexp pattern;
' all occurences of [strFind] are replaced
Public Function RegExpReplaceWord(ByVal strSource As String, _
ByVal strFind As String, _
ByVal strReplace As String) As String
' early binding requires reference to Microsoft VBScript
' Regular Expressions:
' with late binding, no reference needed:
Dim re As Object
Set re = CreateObject("VBScript.RegExp")
re.Global = True
're.IgnoreCase = True ' <-- case insensitve
re.Pattern = "\b" & strFind & "\b"
RegExpReplaceWord = re.Replace(strSource, strReplace)
Set re = Nothing
End Function
Usage of the procedure in an excel sheet looks like:
MySQL 5.7 Now supports a native JSON data type similar to MongoDB and other schemaless document data stores:
JSON support
Beginning with MySQL 5.7.8, MySQL supports a native JSON type. JSON values are not stored as strings, instead using an internal binary format that permits quick read access to document elements. JSON documents stored in JSON columns are automatically validated whenever they are inserted or updated, with an invalid document producing an error. JSON documents are normalized on creation, and can be compared using most comparison operators such as =, <, <=, >, >=, <>, !=, and <=>; for information about supported operators as well as precedence and other rules that MySQL follows when comparing JSON values, see Comparison and Ordering of JSON Values.
MySQL 5.7.8 also introduces a number of functions for working with JSON values. These functions include those listed here:
- Functions that create JSON values: JSON_ARRAY(), JSON_MERGE(), and JSON_OBJECT(). See Section 12.16.2, “Functions That Create JSON Values”.
- Functions that search JSON values: JSON_CONTAINS(), JSON_CONTAINS_PATH(), JSON_EXTRACT(), JSON_KEYS(), and JSON_SEARCH(). See Section 12.16.3, “Functions That Search JSON Values”.
- Functions that modify JSON values: JSON_APPEND(), JSON_ARRAY_APPEND(), JSON_ARRAY_INSERT(), JSON_INSERT(), JSON_QUOTE(), JSON_REMOVE(), JSON_REPLACE(), JSON_SET(), and JSON_UNQUOTE(). See Section 12.16.4, “Functions That Modify JSON Values”.
- Functions that provide information about JSON values: JSON_DEPTH(), JSON_LENGTH(), JSON_TYPE(), and JSON_VALID(). See Section 12.16.5, “Functions That Return JSON Value Attributes”.
In MySQL 5.7.9 and later, you can use column->path as shorthand for JSON_EXTRACT(column, path). This works as an alias for a column wherever a column identifier can occur in an SQL statement, including WHERE, ORDER BY, and GROUP BY clauses. This includes SELECT, UPDATE, DELETE, CREATE TABLE, and other SQL statements. The left hand side must be a JSON column identifier (and not an alias). The right hand side is a quoted JSON path expression which is evaluated against the JSON document returned as the column value.
See Section 12.16.3, “Functions That Search JSON Values”, for more information about -> and JSON_EXTRACT(). For information about JSON path support in MySQL 5.7, see Searching and Modifying JSON Values. See also Secondary Indexes and Virtual Generated Columns.
More info:
This seems to work for me.
var combindedString = new string(list.ToArray());
You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:
cursor.execute('INSERT INTO images VALUES(?)', (img,))
Without the comma, (img)
is just a grouped expression, not a tuple, and thus the img
string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.
>>> len(img)
74
>>> len((img,))
1
If you find it easier to read, you can also use a list literal:
cursor.execute('INSERT INTO images VALUES(?)', [img])
Empty returns true if the var is not set. But isset returns true even if the var is not empty.
I use following to clear session and clear aspnet_sessionID
:
HttpContext.Current.Session.Clear();
HttpContext.Current.Session.Abandon();
HttpContext.Current.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
var dateObject = $("#datePickerInput").datepicker('getDate');
$.datepicker.formatDate('dd MM, yy', dateObject);
There is also a smaller one yet called "input-mini".
I used a temp table and finally got this to work. Here is the logic that is used once you create the temp table:
UPDATE your_table, temp
SET your_table.value = temp.value
WHERE your_table.id = temp.id
The alert()
dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.
You'd need to use a custom modal to achieve that.
The following lines work just fine...
var headerHeight = $( '#header' ).height();
var footerHeight = $( '#footer' ).height();
var footerTop = $( '#footer' ).offset().top;
var height = ( footerTop - ( headerHeight + footerHeight ) );
$( '#content' ).height( height );
You could use a batch file with the following script:
@echo off
SET count=1
FOR /f "tokens=*" %%G IN ('dir "%CD%\src\*.java" /b /s') DO (type "%%G") >> lines.txt
SET count=1
FOR /f "tokens=*" %%G IN ('type lines.txt') DO (set /a lines+=1)
echo Your Project has currently totaled %lines% lines of code.
del lines.txt
PAUSE
You can turn off specific rule for a file by using /*eslint [<rule: "off"], >]*/
/* eslint no-console: "off", no-mixed-operators: "off" */
Version: [email protected]
No there is no built-in support for this.
You have to make your own "INIFileReader". Maybe something like this?
var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));
Console.WriteLine(data["ServerName"]);
Edit: Updated to reflect Paul's comment.
//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]
The reason why I add this answer is that I want to explain the relationship of .
and text()
.
The first thing is when using []
, there are only two types of data:
[number]
to select a node from node-set[bool]
to filter a node-set from node-setIn this case, the value is evaluated to boolean by function boolean()
, and there is a rule:
Filters are always evaluated with respect to a context.
When you need to compare text()
or .
with a string "Data"
, it first uses string()
function to transform those to string type, than gets a boolean result.
There are two important rule about string()
:
The string()
function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.
text()
is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]
.
When it is evaluated by string(["Data"])
, it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.
If you want the string()
function to concatenate all child text, you must then pass a single node instead of a node-set.
For example, we get a node-set ['a', 'b']
, you can pass there parent node to string(parent)
, this will return 'ab'
, and of cause string(.)
in you case will return an concatenated string "Data"
.
Both way will get same result only when there is a text node.
Multiplatform, stable, best solution:
use fkill to kill process which is taking your port:
fkill -f :8080
To install fkill use command: npm i -g fkill
What Works For Me is :
if ( !refreshed()) {
//Your Submit Here
if (isset( $_GET['refresh'])) {
setcookie("refresh",$_GET['refresh'], time() + (86400 * 5), "/");
}
}
}
function refreshed()
{
if (isset($_GET['refresh'])) {
$token = $_GET['refresh'];
if (isset($_COOKIE['refresh'])) {
if ($_COOKIE['refresh'] != $token) {
return false;
} else {
return true;
}
} else {
return false;
}
} else {
return false;
}
}
function createToken($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
?>
And in your Form
<form action="?refresh=<?php echo createToken(3)?>">
</form>
add this to beginning of prog(mac):
module.paths.push('/usr/local/lib/node_modules');
This worked for me:
$("#element1").droppable(
{
drop: function(event, ui)
{
var currentPos = ui.helper.position();
alert("left="+parseInt(currentPos.left)+" top="+parseInt(currentPos.top));
}
});
InetAddress.getLocalHost().getHostName()
is the more portable way.
exec("hostname")
actually calls out to the operating system to execute the hostname
command.
Here are a couple other related answers on SO:
EDIT: You should take a look at A.H.'s answer or Arnout Engelen's answer for details on why this might not work as expected, depending on your situation. As an answer for this person who specifically requested portable, I still think getHostName()
is fine, but they bring up some good points that should be considered.
Getting away from all these graph structures, I just love the simple Ring-Buffer.
When properly implemented you can seriously reduce your memory footprint while maintaining performance and sometimes even improving it.