For us, it was after install EF 5 on an existing core project.
On the PC of my colleague, after a publish, he was having this DLL file :
mscordaccore_amd64_amd64_4.700.20.20201.dll
And me, this one :
mscordaccore_amd64_amd64_4.700.20.36602.dll
After his publish to release, the website returned the HTTP Error 500.30
.
After my own publish to release, the website was working fine.
You can add some code like this
ListView.builder{
shrinkWrap: true,
}
This issue is based on your installed version of visual studio and Windows, you can follow the following steps:-
downgraded your PCL by the following command
Install-Package Xamarin.Forms -Version 2.5.1.527436
You can use Configuration to resolve this.
Ex (Startup.cs):
You can pass by DI to the controllers after this implementation.
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var microserviceName = Configuration["microserviceName"];
services.AddSingleton(Configuration);
...
}
For me, I had ~6 different Nuget packages to update and when I selected Microsoft.AspNetCore.All first, I got the referenced error.
I started at the bottom and updated others first (EF Core, EF Design Tools, etc), then when the only one that was left was Microsoft.AspNetCore.All it worked fine.
I just had this with 15.8.3 after uninstalling some .NET Core 1.x preview SDKs, my application would not compile and showed the error.
It was fixed by installing the latest x86 version of the SDK even though I'm on Windows 10 x64.
I presume this is because VS 2017 is still a x86 program and though the programs run as x64 the compiler was looking for an appropriate x86 SDK
I had this, but, it was because I had added a NuGet package that had updated the binding redirects. Once I removed the package, the redirects were still there. I removed all of them, and then ran update-package -reinstall. This added the correct redirects.
same issue...resolved by dong the following
1.) close pm manager 2.) close Visual Studio 3.) Open Visual Studio 4.) Open pm manager
seems the trick is to close PM Manager before closing VS
try this if you are using JWT pip install djangorestframework-jwt
Change the "package source" in nuget to All
Details:
None of the above helped in my case.
My problem was that I restricted to only one private feed. Once I changed the "package source" to All
, my problem was solved. I believe the crux of the matter is that my private pkg has a dependency on other pkgs from nuget.org.
I hope this can help someone
Try below code,
UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor blackColor];
[view1 setFrame:CGRectMake(0, 0, 50, 50)];
UIView *view2 = [[UIView alloc]init];
view2.backgroundColor = [UIColor greenColor];
[view2 setFrame:CGRectMake(0, 100, 100, 100)];
NSArray *subView = [NSArray arrayWithObjects:view1,view2, nil];
[self.stack1 initWithArrangedSubviews:subView];
Hope it works. Please let me know if you need anymore clarification.
Disable Windows Defender Service. Turning this off immediately caused all of my unit tests to show up in Test Explorer.
I know this is an old question, but I recently ran into this same issue. It ended up being a Proguard problem (when I set minifyEnabled
to false
it stopped happening.)
To stop it, with proguard enabled, I added the following to my proguard rules file, thanks to a solution I found elsewhere (after discovering that the problem was proguard)
-dontwarn android.support.v7.**
-keep class android.support.v7.** { *; }
-keep interface android.support.v7.** { *; }
Not sure if they're necessary, but I also added these lines:
-keep class com.google.** { *; }
-keep interface com.google.** { *; }
The button code should be moved to the PlaceholderFragment()
class. There you will call the layout fragment_main.xml
in the onCreateView
method. Like so
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button) view.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
return view;
}
I ran into the same problem, and I'm not sure why, but it turned out to be that the script link generated by Scripts.Render did not have a .js extension. Because it also does not have a Type attribute the browser was just unable to use it (chrome and firefox).
To resolve this, I changed my bundle configuration to generate compiled files with a js extension, e.g.
var coreScripts = new ScriptBundle("~/bundles/coreAssets.js")
.Include("~/scripts/jquery.js");
var coreStyles = new StyleBundle("~/bundles/coreStyles.css")
.Include("~/css/bootstrap.css");
Notice in new StyleBundle(...
instead of saying ~/bundles/someBundle
, I am saying ~/bundlers/someBundle.js
or ~/bundles/someStyles.css
..
This causes the link generated in the src attribute to have .js or .css on it when optimizations are enabled, as such the browsers know based on the file extension what mime/type to use on the get request and everything works.
If I take off the extension, everything breaks. That's because @Scripts and @Styles doesn't render all the necessary attributes to understand a src to a file with no extension.
Install .NET framework as below, it will work .NET version 4.5 as well.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Some time only give aspnet_regiis.exe -i
don't work so give aspnet_regiis.exe -ir
in above path.
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
Make sure the package version is equal across the solution. I just downgraded & upgraded Microsoft.AspNet.Mvc
package across the solution and the problem solved.
One option would be to include function.cpp
in your UnitTest1
project, but that may not be the most ideal solution structure. The short answer to your problem is that when building your UnitTest1
project, the compiler and linker have no idea that function.cpp
exists, and also have nothing to link that contains a definition of multiple
. A way to fix this is making use of linking libraries.
Since your unit tests are in a different project, I'm assuming your intention is to make that project a standalone unit-testing program. With the functions you are testing located in another project, it's possible to build that project to either a dynamically or statically linked library. Static libraries are linked to other programs at build time, and have the extension .lib
, and dynamic libraries are linked at runtime, and have the extension .dll
. For my answer I'll prefer static libraries.
You can turn your first program into a static library by changing it in the projects properties. There should be an option under the General tab where the project is set to build to an executable (.exe
). You can change this to .lib
. The .lib
file will build to the same place as the .exe
.
In your UnitTest1
project, you can go to its properties, and under the Linker tab in the category Additional Library Directories, add the path to which MyProjectTest
builds. Then, for Additional Dependencies under the Linker - Input tab, add the name of your static library, most likely MyProjectTest.lib
.
That should allow your project to build. Note that by doing this, MyProjectTest
will not be a standalone executable program unless you change its build properties as needed, which would be less than ideal.
Username you get like this:
var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;
I had just upgraded to VS 2013 from VS 2012 and the current user identity (HttpContext.User.Identity) was coming through as anonymous.
I tried changing the IIS express applicationhost.config, no difference.
The solution was to look at the properties of the web project, hit F4 to get the project properties when you have the top level of the project selected. Do not right click on the project and select properties, this is something entirely different.
Change Anonymous Authentication to be Disabled and Windows Authentication to be Enabled.
Works like gravy :)
This should works
.center-div {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<div class="center-div">Center Div</div>
_x000D_
This way I solved my problem. Hope it helps others. In my case I created a class, a field, their getter & setter and then provide the object instead of string.
Use this
public static class EncryptedData {
private String encryptedData;
public String getEncryptedData() {
return encryptedData;
}
public void setEncryptedData(String encryptedData) {
this.encryptedData = encryptedData;
}
}
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getEncryptedData().getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
Instead of this
@PutMapping(value = MY_IP_ADDRESS)
public ResponseEntity<RestResponse> updateMyIpAddress(@RequestBody final EncryptedData encryptedData) {
try {
Path path = Paths.get(PUBLIC_KEY);
byte[] bytes = Files.readAllBytes(path);
PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(base64.decode(bytes));
PrivateKey privateKey = KeyFactory.getInstance(CRYPTO_ALGO_RSA).generatePrivate(ks);
Cipher cipher = Cipher.getInstance(CRYPTO_ALGO_RSA);
cipher.init(Cipher.PRIVATE_KEY, privateKey);
String decryptedData = new String(cipher.doFinal(encryptedData.getBytes()));
String[] dataArray = decryptedData.split("|");
Method updateIp = Class.forName("com.cuanet.client.helper").getMethod("methodName", String.class,String.class);
updateIp.invoke(null, dataArray[0], dataArray[1]);
} catch (Exception e) {
LOG.error("Unable to update ip address for encrypted data: "+encryptedData, e);
}
return null;
}
Okay, it took me a while to see this, but there's no way this compiles:
return String.(ConfigurationManager.AppSettings[paramName]);
You're not even calling a method on the String
type. Just do this:
return ConfigurationManager.AppSettings[paramName];
The AppSettings
KeyValuePair already returns a string. If the name doesn't exist, it will return null
.
Based on your edit you have not yet added a Reference to the System.Configuration
assembly for the project you're working in.
The following example shows the general best practice to implement IDisposable
interface. Reference
Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory for two garbage cycles (Note: Read how Finalization works). Below example elaborate all above.
public class DisposeExample
{
// A base class that implements IDisposable.
// By implementing IDisposable, you are announcing that
// instances of this type allocate scarce resources.
public class MyResource: IDisposable
{
// Pointer to an external unmanaged resource.
private IntPtr handle;
// Other managed resource this class uses.
private Component component = new Component();
// Track whether Dispose has been called.
private bool disposed = false;
// The class constructor.
public MyResource(IntPtr handle)
{
this.handle = handle;
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
// Dispose(bool disposing) executes in two distinct scenarios.
// If disposing equals true, the method has been called directly
// or indirectly by a user's code. Managed and unmanaged resources
// can be disposed.
// If disposing equals false, the method has been called by the
// runtime from inside the finalizer and you should not reference
// other objects. Only unmanaged resources can be disposed.
protected virtual void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// If disposing is false,
// only the following code is executed.
CloseHandle(handle);
handle = IntPtr.Zero;
// Note disposing has been done.
disposed = true;
}
}
// Use interop to call the method necessary
// to clean up the unmanaged resource.
[System.Runtime.InteropServices.DllImport("Kernel32")]
private extern static Boolean CloseHandle(IntPtr handle);
// Use C# destructor syntax for finalization code.
// This destructor will run only if the Dispose method
// does not get called.
// It gives your base class the opportunity to finalize.
// Do not provide destructors in types derived from this class.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
}
public static void Main()
{
// Insert code here to create
// and use the MyResource object.
}
}
I suggest to use the inherits
helper that comes with the standard util
module: http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor
There is an example of how to use it on the linked page.
When you create an IIS application only the /bin
or /App_Code
folder is in the root directory of the IIS app. So just remember put all the code in the root /bin
or /App_code
directory (see http://blogs.msdn.com/b/chrsmith/archive/2006/08/10/wcf-service-nesting-in-iis.aspx).
Make sure that the service name and the contract contain full name(e.g namespace.ClassName
), and the service name and interface is the same as the name attribute of the service tag and contract of endpoint in web.config.
I had the duplicit definition of connection string in my WCF service. I was able to debug the service and to see the inner error message (not displayed by default):
ConfigurationErrorsException: The entry 'xxxEntities' has
already been added. (C:\Users\WcfService\web.config line 35).
which was after web.config transformation (note duplicit values)
<connectionStrings>
<add name="xxxEntities" connectionString="metadata=res://*/ ...
<add name="xxxEntities" connectionString="metadata=res://*/ ...
Hence removing unwanted connection string solved my problem.
I had the same issue. For me I noticed that the https is using another Certificate which was invalid in terms of expiration date. Not sure why it happened. I changed the Https port number and a new self signed cert. WCFtestClinet could connect to the server via HTTPS!
Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections
node in Web.config
file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.
So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.
Connection in APPConfig
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com" providerName="System.Data.SqlClient" />
</connectionStrings>
In Class.Cs
public string ConnectionString
{
get
{
return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
}
}
Also try aspnet_regiis -u
then aspnet_regiis -i
on below path
C:\Windows\Microsoft.NET\Framework\v4.0.30319
Now restart the IIS and check
Hope this will help !
You can create a method that looks like this:
public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
{
DataTable TempTable = RecordDT_;
System.Data.DataView view = new System.Data.DataView(TempTable);
System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
return selected;
}
You can return as many columns as possible.. just add the columns as call parameters as shown below:
public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)
and also add the parameters to this line:
System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);
Then simply implement the function as:
DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);
Thanks...
I've updated VS 2012 to the Latest Update . ie visual studio update 3. That fixed the issue for me.
Swift 5 solution based on Masa solution above - changes in relation to it:
keyboardFrameEndUserInfoKey
instead of
keyboardFrameBeginUserInfoKey
, because
keyboardFrameBeginUserInfoKey
can on first show return other value
as described for example here: keyboard height varies when appearingUIResponder.keyboardWillShowNotification
/UIResponder.keyboardWillHideNotification
instead of NSNotification.Name.UIKeyboardDidShow
/NSNotification.Name.UIKeyboardDidHide
Code:
override func viewDidLoad() {
super.viewDidLoad()
registerForKeyboardNotifications()
}
func registerForKeyboardNotifications() {
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardAppear(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(onKeyboardDisappear(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func onKeyboardAppear(_ notification: NSNotification) {
guard let info = notification.userInfo, let kbSize = (info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.size else { return }
let insets = UIEdgeInsets(top: 0, left: 0, bottom: kbSize.height, right: 0)
scrollView.contentInset = insets
scrollView.scrollIndicatorInsets = insets
//Other changes if needed
}
deinit {
NotificationCenter.default.removeObserver(self)
}
Since JsonSerializer is deprecated in .Net 4.0+ I used http://www.newtonsoft.com/json to solve this issue.
NuGet- > Install-Package Newtonsoft.Json
One way to do this... As text length increases try to change (decrease) the fontsize of the label text using
Label.adjustsFontSizeToFitWidth = YES;
dynamic myDynamic = new { PropertyOne = true, PropertyTwo = false};
It appears that Microsoft.Web.Infrastructure.dll is not being installed in the GAC, even if .net (4.0 or 4.5 or other) are installed successfully on Windows Server. On localhost (typically Windows client), it seems like it is being in the GAC when the tools/platform (Visual Studio etc.) are installed.
As one possible fix, please try the following:
Run the following command in the Package Manager Console. (If you are using Visual Studio, this can be reached via menu options "Tools --> Library Package Manager --> Package Manager Console:)
PM> Install-Package Microsoft.Web.Infrastructure
You will see the following messages if it is successfully installed.
Successfully installed 'Microsoft.Web.Infrastructure 1.0.0.0'.
Successfully added 'Microsoft.Web.Infrastructure 1.0.0.0' to Web.
You will notice that Microsoft.Web.Infrastructure.dll has now been added as a Reference (can be seen in the references folder of your project in in Solution Explorer)
If you look at the properties of this reference you will notice that "Copy Local" has been set to "True" by default.
Now when you "Publish " your project, Microsoft.Web.Infrastructure.dll will be deployed.
For Nginx, the only thing that worked for me was adding this header:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
Along with the Access-Control-Allow-Origin header:
add_header 'Access-Control-Allow-Origin' '*';
Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.
I have deleted System.Web.dll from Bin frolder of my site.
You can also use:
driver.switch_to.frame(0)
(0)
being the first iframe on the html.
to switch back to the default content:
driver.switch_to.default_content()
Description: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.
Details: To enable the details of this specific error message to be viewable on remote machines, please create a tag within a "web.config" configuration file located in the root directory of the current web application. This tag should then have its "mode" attribute set to "Off".
If you install the IIS after the installation of .Net FrameWork. You need install the .net framework again for IIS. So all we need to do is run aspnet_regiis -i
. Hope it is helpful.
I installed EntityFramework 6.2
instead of 6.3
and it worked.
Perhaps it is the .NetCoreApp v2.1
or .NETFramework v4.6.1
.
WebDriver driver=new FirefoxDriver();
driver.get("http://www.java-examples.com/java-string-examples");
Thread.sleep(3000);
//Switch to nested frame
driver.switchTo().frame("aswift_2").switchTo().frame("google_ads_frame3");
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
A few things to check:
Override the paintComponent method of your panel so you can custom draw. Like this:
@Override
public void paintComponent(Graphics g) {
Graphics2D gr = (Graphics2D) g; //this is if you want to use Graphics2D
//now do the drawing here
...
}
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
Handy Swift 4 extension, in case it's helpful to someone else. Works even if the current view controller does not display a navigation bar.
import UIKit
extension UINavigationController {
static public func navBarHeight() -> CGFloat {
let nVc = UINavigationController(rootViewController: UIViewController(nibName: nil, bundle: nil))
let navBarHeight = nVc.navigationBar.frame.size.height
return navBarHeight
}
}
Usage:
UINavigationController.navBarHeight()
If the error happens with error column "File" as SGEN, then the fix needs to be in a file sgen.exe.config
, next to sgen.exe
. For example, for VS 2015, create C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\sgen.exe.config
. Minimum file contents: <configuration><startup useLegacyV2RuntimeActivationPolicy="true"/></configuration>
Source: SGEN Mixed mode assembly
When I look at the solutions, it seems the problem is always something that prevents the spring library to be loaded. It could be a dependency problem or a deployment problem.
In my case, it was the maven repository that somehow got corrupt. What solved the problem was to remove the folder `C:\Users(my name).m2\repository' and rebuild.
If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings xdt:Transform="Replace">
<!-- production environment config --->
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
Information for this answer are brought from this answer and this blog post.
notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).
Changing the Process Model Identity to LocalSystem fixed this issue for me. You can find this setting if you right click on the application pool and chose "Advanced Settings". I'm running IIS 7.5.
I just solved a similar problem with an ASP.Net application.
Symptoms: I could log in to my app using a local user, but not a domain user, even if the machine was correctly joined to the domain (as you say in your Additional Note). In the Security event viewer, there was an event with ID=4625 "Domain sid inconsistent".
Solution: I found the solution here. The problem was that my test machines where cloned virtual machines (Windows Server 2008 R2; one Domain Controller, and one web server). Both had the same machine SID, which apparently caused problems. Here is what I did:
You loose some settings in the process (user preferences, static IP, recreate the self-signed certificate), but now that I have recreated them, everything is working correctly.
To accomplish this using autolayout, try setting a variable width constraint:
You may also need to adjust your Content Hugging Priority
and Content Compression Resistance Priority
to get the results you need.
UILabel is completely automatically self-sizing:
This UILabel is simply set to be centered on the screen (two constraints only, horizontal/vertical):
It changes widths totally automatically:
You do not need to set any width or height - it's totally automatic.
Notice the small yellow squares are simply attached ("spacing" of zero). They automatically move as the UILabel resizes.
Adding a ">=" constraint sets a minimum width for the UILabel:
This worked for me. Repeatedly calls a function updating the graph every time.
import matplotlib.pyplot as plt
import matplotlib.animation as anim
def plot_cont(fun, xmax):
y = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
def update(i):
yi = fun()
y.append(yi)
x = range(len(y))
ax.clear()
ax.plot(x, y)
print i, ': ', yi
a = anim.FuncAnimation(fig, update, frames=xmax, repeat=False)
plt.show()
"fun" is a function that returns an integer. FuncAnimation will repeatedly call "update", it will do that "xmax" times.
It worked for by following process:
Add Reference:
system.net
system.web
also, include the namespace
using system.net
using system.web
Just copy the parent view's frame to the child-view then add it. After that autoresizing will work. Actually you should only copy the size CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height)
childView.frame = CGRectMake(0, 0, parentView.frame.size.width, parentView.frame.size.height);
[parentView addSubview:childView];
Generally what's meant by that is a fairly intimate familiarity with one (or probably more) of the .NET languages (C#, VB.NET, etc.) and one (or less probably more) of the .NET stacks (WinForms, ASP.NET, WPF, etc.).
As for a specific "formal definition", I don't think you'll find one beyond that. The job description should be specific about what they're looking for. I wouldn't consider a job listing that asks for a ".NET developer" and provides no more detail than that to be sufficiently descriptive.
yes there are some telltale signs for common CMSs like Drupal, Joomla, Pligg, and RoR etc .. .. ASP.NET stuff is easy to spot too .. but as the framework becomes more obscure it gets harder to deduce ..
What I usually is compare the site i am snooping with another site that I know is built using a particular tech. That sometimes works ..
Note: I wrote this answer when Entity Framework 4 was actual. The point of this answer was not to get into trivial .Any()
vs .Count()
performance testing. The point was to signal that EF is far from perfect. Newer versions are better... but if you have part of code that's slow and it uses EF, test with direct TSQL and compare performance rather than relying on assumptions (that .Any()
is ALWAYS faster than .Count() > 0
).
While I agree with most up-voted answer and comments - especially on the point Any
signals developer intent better than Count() > 0
- I've had situation in which Count is faster by order of magnitude on SQL Server (EntityFramework 4).
Here is query with Any
that thew timeout exception (on ~200.000 records):
con = db.Contacts.
Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated
&& !a.NewsletterLogs.Any(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr)
).OrderBy(a => a.ContactId).
Skip(position - 1).
Take(1).FirstOrDefault();
Count
version executed in matter of milliseconds:
con = db.Contacts.
Where(a => a.CompanyId == companyId && a.ContactStatusId <= (int) Const.ContactStatusEnum.Reactivated
&& a.NewsletterLogs.Count(b => b.NewsletterLogTypeId == (int) Const.NewsletterLogTypeEnum.Unsubscr) == 0
).OrderBy(a => a.ContactId).
Skip(position - 1).
Take(1).FirstOrDefault();
I need to find a way to see what exact SQL both LINQs produce - but it's obvious there is a huge performance difference between Count
and Any
in some cases, and unfortunately it seems you can't just stick with Any
in all cases.
EDIT: Here are generated SQLs. Beauties as you can see ;)
ANY
:
exec sp_executesql N'SELECT TOP (1) [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created] FROM ( SELECT [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created], row_number() OVER (ORDER BY [Project2].[ContactId] ASC) AS [row_number] FROM ( SELECT [Extent1].[ContactId] AS [ContactId], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[ContactName] AS [ContactName], [Extent1].[FullName] AS [FullName], [Extent1].[ContactStatusId] AS [ContactStatusId], [Extent1].[Created] AS [Created] FROM [dbo].[Contact] AS [Extent1] WHERE ([Extent1].[CompanyId] = @p__linq__0) AND ([Extent1].[ContactStatusId] <= 3) AND ( NOT EXISTS (SELECT 1 AS [C1] FROM [dbo].[NewsletterLog] AS [Extent2] WHERE ([Extent1].[ContactId] = [Extent2].[ContactId]) AND (6 = [Extent2].[NewsletterLogTypeId]) )) ) AS [Project2] ) AS [Project2] WHERE [Project2].[row_number] > 99 ORDER BY [Project2].[ContactId] ASC',N'@p__linq__0 int',@p__linq__0=4
COUNT
:
exec sp_executesql N'SELECT TOP (1) [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created] FROM ( SELECT [Project2].[ContactId] AS [ContactId], [Project2].[CompanyId] AS [CompanyId], [Project2].[ContactName] AS [ContactName], [Project2].[FullName] AS [FullName], [Project2].[ContactStatusId] AS [ContactStatusId], [Project2].[Created] AS [Created], row_number() OVER (ORDER BY [Project2].[ContactId] ASC) AS [row_number] FROM ( SELECT [Project1].[ContactId] AS [ContactId], [Project1].[CompanyId] AS [CompanyId], [Project1].[ContactName] AS [ContactName], [Project1].[FullName] AS [FullName], [Project1].[ContactStatusId] AS [ContactStatusId], [Project1].[Created] AS [Created] FROM ( SELECT [Extent1].[ContactId] AS [ContactId], [Extent1].[CompanyId] AS [CompanyId], [Extent1].[ContactName] AS [ContactName], [Extent1].[FullName] AS [FullName], [Extent1].[ContactStatusId] AS [ContactStatusId], [Extent1].[Created] AS [Created], (SELECT COUNT(1) AS [A1] FROM [dbo].[NewsletterLog] AS [Extent2] WHERE ([Extent1].[ContactId] = [Extent2].[ContactId]) AND (6 = [Extent2].[NewsletterLogTypeId])) AS [C1] FROM [dbo].[Contact] AS [Extent1] ) AS [Project1] WHERE ([Project1].[CompanyId] = @p__linq__0) AND ([Project1].[ContactStatusId] <= 3) AND (0 = [Project1].[C1]) ) AS [Project2] ) AS [Project2] WHERE [Project2].[row_number] > 99 ORDER BY [Project2].[ContactId] ASC',N'@p__linq__0 int',@p__linq__0=4
Seems that pure Where with EXISTS works much worse than calculating Count and then doing Where with Count == 0.
Let me know if you guys see some error in my findings. What can be taken out of all this regardless of Any vs Count discussion is that any more complex LINQ is way better off when rewritten as Stored Procedure ;).
Just call the method pack() after setting the ContentPane
, (java 1.7
, maybe older) like this:
JFrame frame = new JFrame();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
....
frame.setContentPane(panel1);
frame.pack();
...
frame.setContentPane(panel2);
frame.pack();
...
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");
May or may not require a '/' at the front of the path.
With jQuery it can be like this:
var escapedValue = $('<div/>').text(value).html();
From related question Escaping HTML strings with jQuery
As mentioned in comment double quotes and single quotes are left as-is for this implementation. That means this solution should not be used if you need to make element attribute as a raw html string.
If you already know the name of the program (let's assume program
) to terminate after the timeout (as an example 3
seconds), I can contribute a simple and somewhat dirty alternative solution:
(sleep 3 && killall program) & ./program
This works perfectly if I call benchmark processes with system calls.
Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:
create table foo (
bar int[] default '{}'
);
select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]
create index on foo using gin (bar); -- allows to use an index in the above query
But as the prior answer suggests, it will be better to normalize properly.
You can change this one parent attribute ="android:style/Theme.Holo.Light.DarkActionBar"
If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.
For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:
.row {
zoom: 1;
margin-left: -20px;
}
.row > [class*="span"] {
display: inline;
float: left;
margin-left: 20px;
}
.span4 {
width: 220px;
}
To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).
For example, to allow for the left border on the sidebar, they added this CSS in the <head>
after the the main <link href="../bootstrap.css" rel="stylesheet">
.
.content .span4 {
margin-left: 0;
padding-left: 19px;
border-left: 1px solid #eee;
}
You'll see they've reduced padding-left
by 1px
to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.
I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.
You can always use one of the typeOf functions on JavaScript blogs such as Chris West's. Using a definition such as the following for the typeOf()
function would work:
function typeOf(o){return {}.toString.call(o).slice(8,-1)}
This function (which is declared in the global namespace, can be used like this:
alert("onsubmit is a " + typeOf(elem.onsubmit));
If it is a function, "Function" will be returned. If it is a string, "String" will be returned. Other possible values are shown here.
I had a problem with go get
using private repository on gitlab from our company.
I lost a few minutes trying to find a solution. And I did find this one:
You need to get a private token at:
https://gitlab.mycompany.com/profile/account
Configure you git to add extra header with your private token:
$ git config --global http.extraheader "PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN
Configure your git to convert requests from http to ssh:
$ git config --global url."[email protected]:".insteadOf "https://gitlab.mycompany.com/"
Finally you can use your go get
normally:
$ go get gitlab.com/company/private_repo
I used base64 for the overcoming the same problem, i.e. people can see my password over my shoulder.
Here is what I did - I created a new "db_auth.cfg" file and created parameters with one being my db password. I set the permission as 750 for the file.
DB_PASSWORD=Z29vZ2xl
In my shell script I used the "source" command to get the file and then decode it back to use in my script.
source path_to_the_file/db_auth.cfg
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
I hope this helps.
You can retrieve the value of an attribute by its name, enabling you to get the value of a custom attribute such as an attribute from a Directive:
<button (click)="toggle($event)" id="btn1" myCustomAttribute="somevalue"></button>
toggle( event: Event ) {
const eventTarget: Element = event.target as Element;
const elementId: string = eventTarget.id;
const attribVal: string = eventTarget.attributes['myCustomAttribute'].nodeValue;
}
I've gone back and tested and re-tested this, it appears that the only way I can get it to work (since I have some files in the img folder and some in js/css, etc...) is not to use a relative path to my image in the html and have everything referenced to the bundle folder. What a shame :(.
<img src="myimage.png" />
You have a mismatch of two different collations in your table. You can check what collations each column in your table(s) has by using this query:
SELECT
col.name, col.collation_name
FROM
sys.columns col
WHERE
object_id = OBJECT_ID('YourTableName')
Collations are needed and used when ordering and comparing strings. It's generally a good idea to have a single, unique collation used throughout your database - don't use different collations within a single table or database - you're only asking for trouble....
Once you've settled for one single collation, you can change those tables / columns that don't match yet using this command:
ALTER TABLE YourTableName
ALTER COLUMN OffendingColumn
VARCHAR(100) COLLATE Latin1_General_CI_AS NOT NULL
Marc
UPDATE: to find the fulltext indices in your database, use this query here:
SELECT
fti.object_Id,
OBJECT_NAME(fti.object_id) 'Fulltext index',
fti.is_enabled,
i.name 'Index name',
OBJECT_NAME(i.object_id) 'Table name'
FROM
sys.fulltext_indexes fti
INNER JOIN
sys.indexes i ON fti.unique_index_id = i.index_id
You can then drop the fulltext index using:
DROP FULLTEXT INDEX ON (tablename)
Bro, moment.js is awesome for this: The diff method is what you want: http://momentjs.com/docs/#/displaying/difference/
The below function return array of years from the year to the current year.
const getYears = (from = 2017) => {_x000D_
const diff = moment(new Date()).diff(new Date(`01/01/${from}`), 'years') ;_x000D_
return [...Array(diff >= 0 ? diff + 1 : 0).keys()].map((num) => {_x000D_
return from + num;_x000D_
});_x000D_
}_x000D_
_x000D_
console.log(getYears(2016));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
The order in which you use middleware in Express matters: middleware declared earlier will get called first, and if it can handle a request, any middleware declared later will not get called.
If express.static
is handling the request, you need to move your middleware up:
// need cookieParser middleware before we can do anything with cookies
app.use(express.cookieParser());
// set a cookie
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined) {
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly: true });
console.log('cookie created successfully');
} else {
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// let static middleware do its job
app.use(express.static(__dirname + '/public'));
Also, middleware needs to either end a request (by sending back a response), or pass the request to the next middleware. In this case, I've done the latter by calling next()
when the cookie has been set.
Update
As of now the cookie parser is a seperate npm package, so instead of using
app.use(express.cookieParser());
you need to install it separately using npm i cookie-parser
and then use it as:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
a few other managed wrappers for you to check out
Writing your own interop wrappers can be a time-consuming and difficult process in .NET. There are some advantages to writing a C++ library for the interop - particularly as it allows you to greatly simplify the interface that the C# code. However, if you are only needing a subset of the library, it might make your life easier to just do the interop in C#.
Remove the \s
from your new regex and it should work - whitespace is already included in "anything but alphanumerics".
Note that you may want to add a +
after the ]
so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'')
to trim off underscores at the start or end of the string.
An other solution is to use the special variable ansible_limit
which is the contents of the --limit
CLI option for the current execution of Ansible.
- hosts: "{{ ansible_limit | default(omit) }}"
If the --limit
option is omitted, then Ansible issues a warning, but does nothing since no host matched.
[WARNING]: Could not match supplied host pattern, ignoring: None
PLAY ****************************************************************
skipping: no hosts matched
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
There is an extension for that, but I have no usage experience yet:
http://ipython.scipy.org/ipython/ipython/attachment/ticket/154/ipy_autoreload.py
That's a bit of informal terminology.
As far as Git is concerned, every other repository is just a remote.
Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.
The terms are not restricted to Git repositories.
For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.
<?php
$browser_ver = get_browser(null,true);
//echo $browser_ver['browser'];
if($browser_ver['browser'] == 'IE') {
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>pdf print test</title>
<style>
html { height:100%; }
</style>
<script>
function printIt(id) {
var pdf = document.getElementById("samplePDF");
pdf.click();
pdf.setActive();
pdf.focus();
pdf.print();
}
</script>
</head>
<body style="margin:0; height:100%;">
<embed id="samplePDF" type="application/pdf" src="/pdfs/2010/dash_fdm350.pdf" width="100%" height="100%" />
<button onClick="printIt('samplePDF')">Print</button>
</body>
</html>
<?php
} else {
?>
<HTML>
<script Language="javascript">
function printfile(id) {
window.frames[id].focus();
window.frames[id].print();
}
</script>
<BODY marginheight="0" marginwidth="0">
<iframe src="/pdfs/2010/dash_fdm350.pdf" id="objAdobePrint" name="objAdobePrint" height="95%" width="100%" frameborder=0></iframe><br>
<input type="button" value="Print" onclick="javascript:printfile('objAdobePrint');">
</BODY>
</HTML>
<?php
}
?>
My grep that works after trying out stuff in this thread:
echo "hi how are you " | grep -shoP ".*? "
Just make sure you append a space to each one of your lines
(Mine was a line by line search to spit out words)
A)
Object* o;
o = new Object();
`` B)
Object* o = new Object();
I think A and B has no difference. In both the cases o is a pointer to class Object. statement new Object() creates an object of class Object from heap memory. Assignment statement assigns the address of allocated memory to pointer o.
One thing I would like to mention that size of allocated memory from heap is always the sizeof(Object) not sizeof(Object) + sizeof(void *).
None of the above worked so with a bit of tinkering here's code that did for me
Intent i = new Intent(Intent.ACTION_DIAL);
String p = "tel:" + getString(R.string.phone_number);
i.setData(Uri.parse(p));
startActivity(i);
Creating a virtual environment for Jupyter Notebooks
A minimal Python install is
sudo apt install python3.7 python3.7-venv python3.7-minimal python3.7-distutils python3.7-dev python3.7-gdbm python3-gdbm-dbg python3-pip
Then you can create and use the environment
/usr/bin/python3.7 -m venv test
cd test
source test/bin/activate
pip install jupyter matplotlib seaborn numpy pandas scipy
# install other packages you need with pip/apt
jupyter notebook
deactivate
You can make a kernel for Jupyter with
ipython3 kernel install --user --name=test
To print keys on one line as csv:
echo '{"b":"2","a":"1"}' | jq -r 'keys | [ .[] | tostring ] | @csv'
Output:
"a","b"
For csv completeness ... to print values on one line as csv:
echo '{"b":"2","a":"1"}' | jq -rS . | jq -r '. | [ .[] | tostring ] | @csv'
Output:
"1","2"
This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.
To do it for your whole collection you can also use a loop (based on Niels example):
db.status.find().forEach(function(doc){
doc._id=doc.UserId; db.status_new.insert(doc);
});
db.status_new.renameCollection("status", true);
In this case UserId was the new ID I wanted to use
First you to add a class then remove id
<script type="text/javascript">
$(document).ready(function(){
$("#page_navigation1").addClass("page_navigation");
$("#add").click(function(){
$(".page_navigation").attr("id","page_navigation1");
});
$("#remove").click(function(){
$(".page_navigation").removeAttr("id");
});
});
</script>
If you're on 32-bit machine don't allow more than 3584 MB of RAM and it will run.
Update:
As noted by @iX3, Typescript 2.4 has support for enum strings.
See:Create an enum with string values in Typescript
Original answer:
For String member values, TypeScript only allows numbers as enum member values. But there are a few solutions/hacks you can implement;
Solution 1:
copied from: https://blog.rsuter.com/how-to-implement-an-enum-with-string-values-in-typescript/
There is a simple solution: Just cast the string literal to any before assigning:
export enum Language {
English = <any>"English",
German = <any>"German",
French = <any>"French",
Italian = <any>"Italian"
}
solution 2:
copied from: https://basarat.gitbooks.io/typescript/content/docs/types/literal-types.html
You can use a string literal as a type. For example:
let foo: 'Hello';
Here we have created a variable called foo that will only allow the literal value 'Hello' to be assigned to it. This is demonstrated below:
let foo: 'Hello';
foo = 'Bar'; // Error: "Bar" is not assignable to type "Hello"
They are not very useful on their own but can be combined in a type union to create a powerful (and useful) abstraction e.g.:
type CardinalDirection =
"North"
| "East"
| "South"
| "West";
function move(distance: number, direction: CardinalDirection) {
// ...
}
move(1,"North"); // Okay
move(1,"Nurth"); // Error!
var mydate = "2017-06-28T00:00:00";
var weekDayName = moment(mydate).format('dddd');
console.log(weekDayName);
mydate is the input date. The variable weekDayName get the name of the day. Here the output is
Wednesday
var mydate = "2017-08-30T00:00:00";_x000D_
console.log(moment(mydate).format('dddd'));_x000D_
console.log(moment(mydate).format('ddd'));_x000D_
console.log('Day in number[0,1,2,3,4,5,6]: '+moment(mydate).format('d'));_x000D_
console.log(moment(mydate).format('MMM'));_x000D_
console.log(moment(mydate).format('MMMM'));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
Store IDs of the objects in a hash table mapping to the specific object. Enumerate through all the objects and find their parent if it exists and update its parent pointer accordingly.
class MyObject
{ // The actual object
public int ParentID { get; set; }
public int ID { get; set; }
}
class Node
{
public List<Node> Children = new List<Node>();
public Node Parent { get; set; }
public MyObject AssociatedObject { get; set; }
}
IEnumerable<Node> BuildTreeAndGetRoots(List<MyObject> actualObjects)
{
Dictionary<int, Node> lookup = new Dictionary<int, Node>();
actualObjects.ForEach(x => lookup.Add(x.ID, new Node { AssociatedObject = x }));
foreach (var item in lookup.Values) {
Node proposedParent;
if (lookup.TryGetValue(item.AssociatedObject.ParentID, out proposedParent)) {
item.Parent = proposedParent;
proposedParent.Children.Add(item);
}
}
return lookup.Values.Where(x => x.Parent == null);
}
Yes, you can run commands on the Ansible host. You can specify that all tasks in a play run on the Ansible host, or you can mark individual tasks to run on the Ansible host.
If you want to run an entire play on the Ansible host, then specify hosts: 127.0.0.1
and connection:local
in the play, for example:
- name: a play that runs entirely on the ansible host
hosts: 127.0.0.1
connection: local
tasks:
- name: check out a git repository
git: repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Local Playbooks in the Ansible documentation for more details.
If you just want to run a single task on your Ansible host, you can use local_action
to specify that a task should be run locally. For example:
- name: an example playbook
hosts: webservers
tasks:
- ...
- name: check out a git repository
local_action: git repo=git://foosball.example.org/path/to/repo.git dest=/local/path
See Delegation in the Ansible documentation for more details.
Edit: You can avoid having to type connection: local
in your play by adding this to your inventory:
localhost ansible_connection=local
(Here you'd use "localhost" instead of "127.0.0.1" to refer to the play).
Edit: In newer versions of ansible, you no longer need to add the above line to your inventory, ansible assumes it's already there.
Something (hopefully) reasonably efficient:
public class FileCompare
{
public static bool FilesEqual(string fileName1, string fileName2)
{
return FilesEqual(new FileInfo(fileName1), new FileInfo(fileName2));
}
/// <summary>
///
/// </summary>
/// <param name="file1"></param>
/// <param name="file2"></param>
/// <param name="bufferSize">8kb seemed like a good default</param>
/// <returns></returns>
public static bool FilesEqual(FileInfo file1, FileInfo file2, int bufferSize = 8192)
{
if (!file1.Exists || !file2.Exists || file1.Length != file2.Length) return false;
var buffer1 = new byte[bufferSize];
var buffer2 = new byte[bufferSize];
using (var stream1 = file1.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var stream2 = file2.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
while (true)
{
var bytesRead1 = stream1.Read(buffer1, 0, bufferSize);
var bytesRead2 = stream2.Read(buffer2, 0, bufferSize);
if (bytesRead1 != bytesRead2) return false;
if (bytesRead1 == 0) return true;
if (!ArraysEqual(buffer1, buffer2, bytesRead1)) return false;
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="array1"></param>
/// <param name="array2"></param>
/// <param name="bytesToCompare"> 0 means compare entire arrays</param>
/// <returns></returns>
public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0)
{
if (array1.Length != array2.Length) return false;
var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare;
var tailIdx = length - length % sizeof(Int64);
//check in 8 byte chunks
for (var i = 0; i < tailIdx; i += sizeof(Int64))
{
if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false;
}
//check the remainder of the array, always shorter than 8 bytes
for (var i = tailIdx; i < length; i++)
{
if (array1[i] != array2[i]) return false;
}
return true;
}
}
This is showing some path issue:
pip install graphviz
So this worked for me:
sudo apt-get install graphviz
I changed my layout XML file name and found out later that of the XML file (widget provider in this case) still refers to the old layout XML which doesn't exist, and that prevented the auto generation/correction of R class.
Command where or frame can be used. where command will give more info with the function name
It seems odd that this directory was not created at install - have you manually changed the path of the socket file in the my.cfg?
Have you tried simply creating this directory yourself, and restarting the service?
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
You may enjoy package friendlyeval
which presents a simplified tidy eval API and documentation for newer/casual dplyr
users.
You are creating strings that you wish mutate
to treat as column names. So using friendlyeval
you could write:
multipetal <- function(df, n) {
varname <- paste("petal", n , sep=".")
df <- mutate(df, !!treat_string_as_col(varname) := Petal.Width * n)
df
}
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
Which under the hood calls rlang
functions that check varname
is legal as column name.
friendlyeval
code can be converted to equivalent plain tidy eval code at any time with an RStudio addin.
Void refers to the type. Basically the type of data that it points to is unknown.
Null refers to the value. It's essentially a pointer to nothing, and is invalid to use.
The .NET Data Providers consist of a number of classes used to connect to a data source, execute commands, and return recordsets. The Command Object in ADO.NET provides a number of Execute methods that can be used to perform the SQL queries in a variety of fashions.
A stored procedure is a pre-compiled executable object that contains one or more SQL statements. In many cases stored procedures accept input parameters and return multiple values . Parameter values can be supplied if a stored procedure is written to accept them. A sample stored procedure with accepting input parameter is given below :
CREATE PROCEDURE SPCOUNTRY
@COUNTRY VARCHAR(20)
AS
SELECT PUB_NAME FROM publishers WHERE COUNTRY = @COUNTRY
GO
The above stored procedure is accepting a country name (@COUNTRY VARCHAR(20)) as parameter and return all the publishers from the input country. Once the CommandType is set to StoredProcedure, you can use the Parameters collection to define parameters.
command.CommandType = CommandType.StoredProcedure;
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
The above code passing country parameter to the stored procedure from C# application.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlDataAdapter adapter ;
SqlCommand command = new SqlCommand();
SqlParameter param ;
DataSet ds = new DataSet();
int i = 0;
connetionString = "Data Source=servername;Initial Catalog=PUBS;User ID=sa;Password=yourpassword";
connection = new SqlConnection(connetionString);
connection.Open();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SPCOUNTRY";
param = new SqlParameter("@COUNTRY", "Germany");
param.Direction = ParameterDirection.Input;
param.DbType = DbType.String;
command.Parameters.Add(param);
adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show (ds.Tables[0].Rows[i][0].ToString ());
}
connection.Close();
}
}
}
The text size can be set with a vw
unit, which means the "viewport width". That way the text size will follow the size of the browser window:
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_responsive_text
For my personal project I used vw and @meida. It works perfectly.
.mText {
font-size: 6vw;
}
@media only screen and (max-width: 1024px) {
.mText {
font-size: 10vw;
}
}
.sText {
font-size: 4vw;
}
@media only screen and (max-width: 1024px) {
.sText {
font-size: 7vw;
}
}
In Swift 3, you can simply change the title of a button by:
button.setTitle("Title", for: .normal)
and you disable the button by:
button.isEnabled = false
.normal
is the same as UIControlState.normal
because the type is inferred.
Taking some answers one step further - if you do the following you can check if any element within the radio group has been checked:
if ($('input[name="yourRadioNames"]:checked').val()){
(checked) or if (!$('input[name="yourRadioNames"]:checked').val()){
(not checked)
That's known as an Arrow Function, part of the ECMAScript 2015 spec...
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(f => f.length);_x000D_
_x000D_
console.log(bar); // 1,2,3
_x000D_
Shorter syntax than the previous:
// < ES6:_x000D_
var foo = ['a', 'ab', 'abc'];_x000D_
_x000D_
var bar = foo.map(function(f) {_x000D_
return f.length;_x000D_
});_x000D_
console.log(bar); // 1,2,3
_x000D_
The other awesome thing is lexical this
... Usually, you'd do something like:
function Foo() {_x000D_
this.name = name;_x000D_
this.count = 0;_x000D_
this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
var self = this;_x000D_
setInterval(function() {_x000D_
// this is the Window, not Foo {}, as you might expect_x000D_
console.log(this); // [object Window]_x000D_
// that's why we reassign this to self before setInterval()_x000D_
console.log(self.count);_x000D_
self.count++;_x000D_
}, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
But that could be rewritten with the arrow like this:
function Foo() {_x000D_
this.name = name;_x000D_
this.count = 0;_x000D_
this.startCounting();_x000D_
}_x000D_
_x000D_
Foo.prototype.startCounting = function() {_x000D_
setInterval(() => {_x000D_
console.log(this); // [object Object]_x000D_
console.log(this.count); // 1, 2, 3_x000D_
this.count++;_x000D_
}, 1000)_x000D_
}_x000D_
_x000D_
new Foo();
_x000D_
For more, here's a pretty good answer for when to use arrow functions.
I use the Branches options, and then right click on the "remote/origin" folder and then click on "delete branches from remote", see the image below:
Use this
data: '{"username":"' + username + '"}',
I try a lot of syntax to work with laravel it work for me for laravel 4.2 + ajax.
Take a look at the PropertyPlaceholderConfigurer, I find it clearer to use than annotation.
e.g.
@Configuration
public class PropertiesConfiguration {
@Bean
public PropertyPlaceholderConfigurer properties() {
final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
// ppc.setIgnoreUnresolvablePlaceholders(true);
ppc.setIgnoreResourceNotFound(true);
final List<Resource> resourceLst = new ArrayList<Resource>();
resourceLst.add(new ClassPathResource("myapp_base.properties"));
resourceLst.add(new FileSystemResource("/etc/myapp/overriding.propertie"));
resourceLst.add(new ClassPathResource("myapp_test.properties"));
resourceLst.add(new ClassPathResource("myapp_developer_overrides.properties")); // for Developer debugging.
ppc.setLocations(resourceLst.toArray(new Resource[]{}));
return ppc;
}
To load 3 cores for 5 seconds:
seq 3 | xargs -P0 -n1 timeout 5 yes > /dev/null
This results in high kernel (sys) load from the many write() system calls.
If you prefer mostly userland cpu load:
seq 3 | xargs -P0 -n1 timeout 5 md5sum /dev/zero
If you just want the load to continue until you press Ctrl-C:
seq 3 | xargs -P0 -n1 md5sum /dev/zero
You can set the datatable as a datasource to many elements.
For eg
gridView
repeater
datalist
etc etc
If you need to extract data from each row then you can use
table.rows[rowindex][columnindex]
or
if you know the column name
table.rows[rowindex][columnname]
If you need to iterate the table then you can either use a for loop or a foreach loop like
for ( int i = 0; i < table.rows.length; i ++ )
{
string name = table.rows[i]["columnname"].ToString();
}
foreach ( DataRow dr in table.Rows )
{
string name = dr["columnname"].ToString();
}
It is saying you have an instance variable (the var is only visible/accessible when you have an instance of that class) and you are trying to use it in the context of a static scope (class method).
You can make your instance variable a class variable by adding static/class attribute.
You instantiate an instance of your class and call the instance method on that variable.
Solution based on Ashish answer with Java
private void setUI(){
mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_messaging, R.id.nav_me)
.setDrawerLayout(drawer)
.build();
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.addOnDestinationChangedListener(navDestinationChange);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
private NavController.OnDestinationChangedListener navDestinationChange = new NavController.OnDestinationChangedListener(){
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
if(R.id.nav_home==destination.getId()){
destination.setLabel("News");
}
}
};
You can use the tree
command with its d
switch to accomplish this.
% tree -d tstdir
tstdir
|-- d1
| `-- d11
| `-- d111
`-- d2
`-- d21
`-- d211
6 directories
see man tree
for more info.
From your shell run:
pip2 install unicodecsv
And (unlike the original question) presuming you're using Python's built in csv
module, turn
import csv
into
import unicodecsv as csv
in your code.
I'm updating my answer...
antMatcher()
is a method of HttpSecurity
, it doesn't have anything to do with authorizeRequests()
. Basically, http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
The authorizeRequests().antMatchers()
is then used to apply authorization to one or more paths you specify in antMatchers()
. Such as permitAll()
or hasRole('USER3')
. These only get applied if the first http.antMatcher()
is matched.
first, in C:\users\your PC
write npm uninstall -g create-react-app
then, create your project folder with npx create-react-app folder-name
.
Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.
You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.
Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.
I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.
Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.
I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.
In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.
Good luck!
The vscode codebase does not use relative paths, but everything works fine for them
Really depends on your module loader. If you are using systemjs
with baseurl
then it would work. VSCode uses its own custom module loader (based on an old version of requirejs).
Use relative paths as that is what commonjs
supports. If you move files around you will get a typescript compile time error (a good thing) so you will be better off than a great majority of pure js projects out there (on npm).
You can open up to 3 files in the same view by pressing [CTRL] + [^]
<div class='block1'>
<p style="float:left">text</p>
<div class='block2' style="float:right">block2</div>
<p style="float:left; clear:left">text2</p>
</div>
You can clear:both
or clear:left
depending on the exact context.
Also, you will have to play around with width
to get it to work correctly...
As @Izabela Orlowska pointed out: In my case the problem occurred due to some files that could not be found inside the gradle cache folder. (Windows OS)
The default gradle path was inside my user folder. the path contained umlauts and a space.
I moved the gradle folder by setting GRADLE_HOME
and GRADLE_USER_HOME
environment variable to some newly created folder without umlauts or spaces in path.
This fixed the problem for me.
Hmmm. Lots of good answers. Here is my few cents on it.
attr_accessor
is a simple method that helps us in cleaning(DRY-ing) up the repeating getter and setter
methods.
So that we can focus more on writing business logic and not worry about the setters and getters.
Here's a solution, but I don't know if it's the best....
Select
Coalesce(Case When Len(listing.Offer_Text) = 0 Then Null Else listing.Offer_Text End, company.Offer_Text, '') As Offer_Text,
from tbl_directorylisting listing
Inner Join tbl_companymaster company
On listing.company_id= company.company_id
No problem. You're running your code under the debugger, and the debugger is telling you that it doesn't have debugging information for the system libraries.
If you really need that (usually for stack traces), you can download it from Microsoft's symbol servers, but for now you don't need to worry.
You can also use replaceAll(search, replaceWith)
[MDN].
Then, make sure you have a string by wrapping one type of quotes by a different type:
'a "b" c'.replaceAll('"', "'")
// result: "a 'b' c"
'a "b" c'.replaceAll(`"`, `'`)
// result: "a 'b' c"
// Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
'a "b" c'.replaceAll(/\"/g, "'")
// result: "a 'b' c"
Important(!) if you choose regex:
when using a
regexp
you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".
<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>
or
$sidemenus = mysql_fetch_array($results);
then
<?php echo $sidemenu['mname']."<br />";?>
Edit:
In the newer version of pandas, you can pass the sheet name as a parameter.
file_name = # path to file + file name
sheet = # sheet name or sheet number or list of sheet numbers and names
import pandas as pd
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(5)) # print first 5 rows of the dataframe
Check the docs for examples on how to pass sheet_name
:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html
Old version:
you can use pandas
package as well....
When you are working with an excel file with multiple sheets, you can use:
import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names
>>> [u'Sheet1', u'Sheet2', u'Sheet3']
df = xl.parse("Sheet1")
df.head()
df.head()
will print first 5 rows of your Excel file
If you're working with an Excel file with a single sheet, you can simply use:
import pandas as pd
df = pd.read_excel(path + filename)
print df.head()
[Updated (previous answer no longer applied)]
For fetching the latest version:
sudo add-apt-repository ppa:longsleep/golang-backports
sudo apt update
sudo apt install golang-go
Also see the wiki
Use the start
command with the /b
flag to run a command/application without opening a new window. For example, this runs dotnet run
in the background:
start /b dotnet run
You can pass parameters to the command/application too. For example, I'm starting 3 instances of this C# project, with parameter values of x
, y
, and z
:
CTRL + BREAK
In my experience, this stops all of the background commands/programs you have started in that cmd
instance.
According to the Microsoft docs:
CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.
Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.
I very often use count(/html/body) = 0
, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.
<xsl:choose>
<xsl:when test="/html/body">
<!-- Found the node(s) -->
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
<!-- No node exists -->
</xsl:otherwise>
</xsl:choose>
Your code is very vague and not understandable, but I can provide you with an alternative.
First of all, if you want temp
to go through the whole string, you can do something like this:
char *temp;
for (temp = your_string; *temp; ++temp)
/* do something with *temp */
The term *temp
as the for
condition simply checks whether you have reached the end of the string or not. If you have, *temp
will be '\0'
(NUL
) and the for
ends.
Now, inside the for, you want to find the bits that compose *temp
. Let's say we print the bits:
for (as above)
{
int bit_index;
for (bit_index = 7; bit_index >= 0; --bit_index)
{
int bit = *temp >> bit_index & 1;
printf("%d", bit);
}
printf("\n");
}
To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7
to bit_index = sizeof(*temp)*8-1
** Sub queries may have a bad impact on performance when used with large datasets **
Original query
SELECT wp_posts.*
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
AND wp_posts.post_type = 'post'
GROUP BY wp_posts.post_author
ORDER BY wp_posts.post_date DESC;
Modified query
SELECT p.post_status,
p.post_type,
Max(p.post_date),
p.post_author
FROM wp_posts P
WHERE p.post_status = "publish"
AND p.post_type = "post"
GROUP BY p.post_author
ORDER BY p.post_date;
becasue i'm using max
in the select clause
==> max(p.post_date)
it is possible to avoid sub select queries and order by the max column after the group by.
With Python's time
module you can't get microseconds with %f
.
For those who still want to go with time
module only, here is a workaround:
now = time.time()
mlsec = repr(now).split('.')[1][:3]
print time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), time.localtime(now))
You should get something like 2017-01-16 16:42:34.625 EET (yes, I use milliseconds as it's fairly enough).
To break the code into details, paste the below code into a Python console:
import time
# Get current timestamp
now = time.time()
# Debug now
now
print now
type(now)
# Debug strf time
struct_now = time.localtime(now)
print struct_now
type(struct_now)
# Print nicely formatted date
print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
# Get miliseconds
mlsec = repr(now).split('.')[1][:3]
print mlsec
# Get your required timestamp string
timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
print timestamp
For clarification purposes, I also paste my Python 2.7.12 result here:
>>> import time
>>> # get current timestamp
... now = time.time()
>>> # debug now
... now
1484578293.519106
>>> print now
1484578293.52
>>> type(now)
<type 'float'>
>>> # debug strf time
... struct_now = time.localtime(now)
>>> print struct_now
time.struct_time(tm_year=2017, tm_mon=1, tm_mday=16, tm_hour=16, tm_min=51, tm_sec=33, tm_wday=0, tm_yday=16, tm_isdst=0)
>>> type(struct_now)
<type 'time.struct_time'>
>>> # print nicely formatted date
... print time.strftime("%Y-%m-%d %H:%M:%S %Z", struct_now)
2017-01-16 16:51:33 EET
>>> # get miliseconds
... mlsec = repr(now).split('.')[1][:3]
>>> print mlsec
519
>>> # get your required timestamp string
... timestamp = time.strftime("%Y-%m-%d %H:%M:%S.{} %Z".format(mlsec), struct_now)
>>> print timestamp
2017-01-16 16:51:33.519 EET
>>>
In case you want to sort dates with descending order the minus sign doesn't work with Dates.
out <- DF[rev(order(as.Date(DF$end))),]
However you can have the same effect with a general purpose function: rev(). Therefore, you mix rev and order like:
#init data
DF <- data.frame(ID=c('ID3', 'ID2','ID1'), end=c('4/1/09 12:00', '6/1/10 14:20', '1/1/11 11:10')
#change order
out <- DF[rev(order(as.Date(DF$end))),]
Hope it helped.
This can also be done in the GUI. Here's an example adding a multi-column unique constraint to an existing table.
Click OK in each window and you're done.
You can use native function Date.toLocaleTimeString()
:
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
I found it on http://www.w3schools.com/jsref/jsref_tolocaletimestring.asp
var d = new Date();_x000D_
var n = d.toLocaleTimeString();_x000D_
alert("The time is: \n"+n);
_x000D_
While there isn't anything you can do about the box in some circumstances, you can intercept someone clicking on a link. For me, this was worth the effort for most scenarios and as a fallback, I've left the unload event.
I've used Boxy instead of the standard jQuery Dialog, it is available here: http://onehackoranother.com/projects/jquery/boxy/
$(':input').change(function() {
if(!is_dirty){
// When the user changes a field on this page, set our is_dirty flag.
is_dirty = true;
}
});
$('a').mousedown(function(e) {
if(is_dirty) {
// if the user navigates away from this page via an anchor link,
// popup a new boxy confirmation.
answer = Boxy.confirm("You have made some changes which you might want to save.");
}
});
window.onbeforeunload = function() {
if((is_dirty)&&(!answer)){
// call this if the box wasn't shown.
return 'You have made some changes which you might want to save.';
}
};
You could attach to another event, and filter more on what kind of anchor was clicked, but this works for me and what I want to do and serves as an example for others to use or improve. Thought I would share this for those wanting this solution.
I have cut out code, so this may not work as is.
document.oncontextmenu = function() {return false;}; //disable the browser context menu
$('selector-name')[0].oncontextmenu = function(){} //set jquery element context menu
Many of the solutions have focused on complicating things.
Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.
If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.
This ensures you are maintaining shared state / context without reloading your entire app as is done with
import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)
// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
{link.label}
</NavLink>
// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
Button without using withRouter
</NavLink>
Based on the answer given by Lam Vinh, here is a simple batch file that works for me on my 1st gen Nexus 7. It prompts the user to enter the package name and then the database name (without the .sqlite extension) and puts it in c:\temp. This assumes you have the Android sdk set in the environment variables.
@echo off
cd c:\temp\
set /p UserInputPackage= Enter the package name:
set /p UserInputDB= Enter the database name:
@echo on
adb shell "run-as %UserInputPackage% chmod 666 /data/data/%UserInputPackage%/databases/%UserInputDB%.sqlite"
adb pull /data/data/%UserInputPackage%/databases/%UserInputDB%.sqlite
@echo off
pause
The official docker tutorial says:
A data volume is a specially-designated directory within one or more containers that bypasses the Union File System. Data volumes provide several useful features for persistent or shared data:
Volumes are initialized when a container is created. If the container’s base image contains data at the specified mount point,
that existing data is copied into the new volume upon volume
initialization. (Note that this does not apply when mounting a host
directory.)Data volumes can be shared and reused among containers.
Changes to a data volume are made directly.
Changes to a data volume will not be included when you update an image.
Data volumes persist even if the container itself is deleted.
In Dockerfile
you can specify only the destination of a volume inside a container. e.g. /usr/src/app
.
When you run a container, e.g. docker run --volume=/opt:/usr/src/app my_image
, you may but do not have to specify its mounting point (/opt
) on the host machine. If you do not specify --volume
argument then the mount point will be chosen automatically, usually under /var/lib/docker/volumes/
.
//Note for Linq Users/Coders
This should give you the exact comparison for checking if a date falls within range when working with input from a user - date picker for example:
((DateTime)ri.RequestX.DateSatisfied).Date >= startdate.Date &&
((DateTime)ri.RequestX.DateSatisfied).Date <= enddate.Date
where startdate and enddate are values from a date picker.
There is also a SURROGATE KEY: it occurs if one non prime attribute depends on another non prime attribute. that time you don't now to choose which key as primary key to split up your table. In that case use a surrogate key instead of a primary key. Usually this key is system defined and always have numeric values and its value often automatically incremented for new rows. Eg : ms acces = auto number & my SQL = identity column & oracle = sequence.
In general, one doesn't expand out log(a + b)
; you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:
log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
(In fact, this identity is often used when implementing log
in math libraries).
This is a Pythonic way to do it:
import httplib
import yaml
c = httplib.HTTPConnection(address)
c.request('GET', url_path)
r = c.getresponse()
# get the date into a datetime object
lmd = r.getheader('last-modified')
if lmd != None:
cur_data = { url: datetime.strptime(lmd, '%a, %d %b %Y %H:%M:%S %Z') }
else:
print "Hmmm, no last-modified data was returned from the URL."
print "Returned header:"
print yaml.dump(dict(r.getheaders()), default_flow_style=False)
The rest of the script includes an example of archiving a page and checking for changes against the new version, and alerting someone by email.
Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...
In other words...
No, first things first.
Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.
Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.
In this case, the usual suspects are: OCP, SRP, and, as always, KIS.
But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.
What am I talking about?
private double TranslateMeasurementIntoLinear(double actualMeasurement);
It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.
To make this fairy tale short: We need a simple way to test private methods--without ado.
First: Happy new year everyone!
Second: Rehearse your architect lessons.
Third: The "public" modifier is religion, not a solution.
Try CSS:
img {
object-fit: cover;
height: 48px;
}
PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.
First check whether the file exists in SDCard. If the file doesnot exists in SDcard then you can set image using setImageResource() methodand passing default image from drawable folder
Sample Code
File imageFile = new File(absolutepathOfImage);//absolutepathOfImage is absolute path of image including its name
if(!imageFile.exists()){//file doesnot exist in SDCard
imageview.setImageResource(R.drawable.defaultImage);//set default image from drawable folder
}
I know its an old post, but just in case anyone is looking here. I added this to my style.xml and it worked for me.
<!-- This is the main theme parent -->
<style name="MyTabStyle">
<item name="android:actionBarTabTextStyle">@style/MyTabTextStyle</item>
</style>
<style name="MyTabTextStyle" parent="@android:style/Widget.ActionBar.TabText">
<item name="android:textAppearance">@android:style/TextAppearance.Medium</item>
<item name="android:textSize">14sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@color/pressed_skylogtheme</item>
</style>
Use genfromtxt
instead. It's a much more general method than loadtxt
:
import numpy as np
print np.genfromtxt('col.txt',dtype='str')
Using the file col.txt
:
foo bar
cat dog
man wine
This gives:
[['foo' 'bar']
['cat' 'dog']
['man' 'wine']]
If you expect that each row has the same number of columns, read the first row and set the attribute filling_values
to fix any missing rows.
You can't.
"The Samsung Emulator has the same functionality as the Generic Android Emulator, but varies with the size and appearance of the device."
The problem with Samsung is that they don't use a generic android image, they have custom apps and they react in custom ways and do weird things you wouldn't expect and when you're trying to fix bugs that's what you want. You cannot get that. You need access to a physical device to get the right ecosystem to hunt down the bugs and map out which intents work and how they work on that device. And sometimes there are errors that only occur on Samsung devices because some of the core rendering code is different as well. I've had errors where all Android devices except Samsung would work flawlessly but the scheme itself could not work on Samsung and had to be scrapped. The only thing Samsung allows is skinning and that won't properly note the changes in the rendering pipeline or how the samsung ecosystem deals with intents.
You can make the device look similar, that's worthless. I don't care what it looks like, I care whether this bug still affects that particular model or whether the tweak to the intents I made rectified the issue and I can't learn that from a pretty picture as the border to the same device.
Just came across this problem myself, and the only solution I could find that worked in all my test browsers (IE6, IE7, Firefox) was the following:
The code:
<div style="width: 100%">
<div style="padding-right: 6px;">
<input type="text" style="width: 100%; padding: 2px; margin: 0;
border : solid 1px #999" />
</div>
</div>
Here, the total horizontal overflow for the input element is 6px - 2x(padding + border) - so we set a padding-right for the inner DIV of 6px.
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
Try this
<div *ngFor="let piece of allPieces; let i=index">
{{i}} // this will give index
</div>
answer = None
while True:
answer = raw_input("Do you like pie?")
if answer in ("yes", "no"): break
print "That is not a yes or a no"
Would give you what you want with no goto statement.
This code works for me:
#!/bin/sh
argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
echo "foo"
else
echo "bar"
fi
I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.
man test
for more details.
In the latest and greatest Hibernate, I was able to resolve the dependency by including the hibernate-jpa-2.0-api-1.0.0.Final.jar within lib/jpa directory. I didn't find the ejb-persistence jar in the most recent download.
you can also use a namedQuery named findAll for all your entities and call it in your generic FindAll with
entityManager.createNamedQuery(persistentClass.getSimpleName()+"findAll").getResultList();
In xcode 8 you can directly choose image from the selection window (NEW)...
You just need to type - "image" and you will get a suggestion box then select -"Image Literal" from list (see in attached picture) and
then tap on the square you will be able to see all images(see in
second attached picture) which are in your image assets... or select
other image from there.
Its a simple xml design. It looks like iOS switch, check this below image
You need to create custom_thumb.xml and custom_track.xml
This is my switch,I need a very big switch so added layout_width/layout_height parameter
<androidx.appcompat.widget.SwitchCompat
android:id="@+id/swOnOff"
android:layout_width="@dimen/_200sdp"
android:layout_marginStart="@dimen/_50sdp"
android:layout_marginEnd="@dimen/_50sdp"
android:layout_marginTop="@dimen/_30sdp"
android:layout_gravity="center"
app:showText="true"
android:textSize="@dimen/_20ssp"
android:fontFamily="@font/opensans_bold"
app:track="@drawable/custom_track"
android:thumb="@drawable/custom_thumb"
android:layout_height="@dimen/_120sdp"/>
Now create custom_thumb.xml
<?xml version="1.0" encoding="utf-8"?>
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="oval">
<solid android:color="#ffffff"/>
<size android:width="@dimen/_100sdp"
android:height="@dimen/_100sdp"/>
<stroke android:width="1dp"
android:color="#8c8c8c"/>
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="oval">
<solid android:color="#ffffff"/>
<size android:width="@dimen/_100sdp"
android:height="@dimen/_100sdp"/>
<stroke android:width="1dp"
android:color="#34c759"/>
</shape>
</item>
</selector>
Now create custom_track.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false">
<shape android:shape="rectangle">
<corners android:radius="@dimen/_100sdp" />
<solid android:color="#ffffff" />
<stroke android:color="#8c8c8c" android:width="1dp"/>
<size android:height="20dp" />
</shape>
</item>
<item android:state_checked="true">
<shape android:shape="rectangle">
<corners android:radius="@dimen/_100sdp" />
<solid android:color="#34c759" />
<stroke android:color="#8c8c8c" android:width="1dp"/>
<size android:height="20dp" />
</shape>
</item>
</selector>
The following will return true if the element is an input:
$("#elementId").is("input")
or you can use the following to get the name of the tag:
$("#elementId").get(0).tagName
The second way is a tad more efficient, but a much better way is to execute them in batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
}
statement.executeBatch();
}
}
You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
int i = 0;
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.
If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.
public void executeBatch(List<Entity> entities) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(SQL)) {
// ...
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
}
This works for me on [{"id":"data"},{"id":"data"}]
function getObjects(obj, key, val)
{
var newObj = false;
$.each(obj, function()
{
var testObject = this;
$.each(testObject, function(k,v)
{
//alert(k);
if(val == v && k == key)
{
newObj = testObject;
}
});
});
return newObj;
}
All,
Here a little bit twist with mysql-community-server 5.7 I share some steps, how to reset mysql5.7 root password or set password. it will work centos7 and RHEL7 as well.
step1. 1st stop your databases
service mysqld stop
step2. 2nd modify /etc/my.cnf file add "skip-grant-tables"
vi /etc/my.cnf
[mysqld] skip-grant-tables
step3. 3rd start mysql
service mysqld start
step4. select mysql default database
mysql -u root
mysql>use mysql;
step4. set a new password
mysql> update user set authentication_string=PASSWORD("yourpassword") where User='root'
;
step5 restart mysql database
service mysqld restart
mysql -u root -p
enjoy :)
Note: this answer is relevant to resetting form fields, not clearing fields - see update.
You can use JavaScript's native reset()
method to reset the entire form to its default state.
Example provided by Ryan:
$('#myForm')[0].reset();
Note: This may not reset certain fields, such as type="hidden"
.
As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger()
:
$('#myForm').trigger("reset");
If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.
Use []
notation for string representations of properties:
console.log(obj[name]);
Otherwise it's looking for the "name" property, rather than the "a" property.
As David and Remou pointed out, vbCrLf
if you want a carriage-return-linefeed combination. Otherwise, Chr(13)
and Chr(10)
(although some VB-derivatives have vbCr
and vbLf
; VBScript may well have those, worth checking before using Chr
).
A generic piece of code that will work for multiple columns. This can also be used if there is a need to conditionally implement search functionality in the application.
search_key = "abc"
search_args = [col.ilike('%%%s%%' % search_key) for col in ['col1', 'col2', 'col3']]
query = Query(table).filter(or_(*search_args))
session.execute(query).fetchall()
Note: the %%
are important to skip % formatting the query.
Start to Create a Pull Request via the git hosting service you're using. If the branch has been fully merged into the base branch, you'll be unable to create the new PR.
You don't need to actually make the pull request, just use the first step where you pick branches.
For example, on GitHub:
There isn't anything to compare
This doesn't use git on the command line, but I often find it's helpful to use the other tools at your disposal with a clear mental model rather than attempt to remember another arcane git command.
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.text_entry, null);
//text_entry is an Layout XML file containing two text field to display in alert dialog
final EditText input1 = (EditText) textEntryView.findViewById(R.id.EditText1);
final EditText input2 = (EditText) textEntryView.findViewById(R.id.EditText2);
input1.setText("DefaultValue", TextView.BufferType.EDITABLE);
input2.setText("DefaultValue", TextView.BufferType.EDITABLE);
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setIcon(R.drawable.icon)
.setTitle("Enter the Text:")
.setView(textEntryView)
.setPositiveButton("Save",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.i("AlertDialog","TextEntry 1 Entered "+input1.getText().toString());
Log.i("AlertDialog","TextEntry 2 Entered "+input2.getText().toString());
/* User clicked OK so do some stuff */
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
alert.show();
You can try this as well for numeric input with length restriction
<input type="tel" maxlength="4" />
If you have
<div>
<input type="checkbox" class="check-with-label" id="idinput" />
<label class="label-for-check" for="idinput">My Label</label>
</div>
you can do
.check-with-label:checked + .label-for-check {
font-weight: bold;
}
See this working. Note that this won't work in non-modern browsers.
You can zip the two with something like this [like jQuery does]:
function toggleMyDiv() {
if (document.getElementById("myDiv").style.display=="block"){
document.getElementById("myDiv").style.display="none"
}
else{
document.getElementById("myDiv").style.display="block";
}
}
..and use the same function in the two buttons - or generally in the page for both functions.
This is case, when object are better - because you can set up your object to hold x and y , set up defaults etc.
Approach with array is near to create object ( In fact, object is bunch of parameters and functions which will work over object, and function taking array will work over some bunch ov parameters )
Cerainly you can always do some tricks to set null or something like this as default
I have no File -> Source Control menu in Visual Studio because I've never used TFS with this installation of Visual Studio.
My problem was I was opening a solution from the internet and the original author had forgotten to remove the TFS bindings, so every time I open the solution I'd get an annoying popup saying
"Go Offline
The Team Foundation Server http://some-other-guys-tfs-server/
is currently unavailable.
The solution will be opened offline."
To get rid of this, I deleted the .suo next to the .sln file, and then opened the .sln file in Notepad and deleted this entire section:
GlobalSection(TeamFoundationVersionControl) = preSolution
SccNumberOfProjects = 2
SccEnterpriseProvider = {xxxxx}
SccTeamFoundationServer = http://some-other-guys-tfs-server/
SccLocalPath0 = .
SccProjectUniqueName1 = xxDemo\\xxDemo.csproj
SccProjectName1 = xxDemo
SccLocalPath1 = xxDemo
EndGlobalSection
Save the .sln in Notepad and then open in Visual Studio, problem solved.
Update: Saveen Reddy has created a tool to do this. I haven't tried it though.
Unit Testing - As the name suggests, this method tests at the object level. Individual software components are tested for any errors. Knowledge of the program is needed for this test and the test codes are created to check if the software behaves as it is intended to.
Functional Testing - Is carried out without any knowledge of the internal working of the system. The tester will try to use the system by just following requirements, by providing different inputs and testing the generated outputs. This test is also known as closed-box testing or black-box.
Acceptance Testing - This is the last test that is conducted before the software is handed over to the client. It is carried out to ensure that the developed software meets all the customer requirements. There are two types of acceptance testing - one that is carried out by the members of the development team, known as internal acceptance testing (Alpha testing), and the other that is carried out by the customer or end user known as (Beta testing)
Integration Testing - Individual modules that are already subjected to unit testing are integrated with one another. Generally the two approachs are followed :
1) Top-Down
2) Bottom-Up
try it.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
if you wanna keep OOP form without turning any error off, you can also:
class A
{
public function foo() {
;
}
}
class B extends A
{
/*instead of :
public function foo($a, $b, $c) {*/
public function foo() {
list($a, $b, $c) = func_get_args();
// ...
}
}
Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. C# 7 and C# 8.0 have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.
There is an extension members item in the C# 7 work list so it may be supported in the near future. The current status of extension property can be found on Github under the related item.
However, there is an even more promising topic which is the "extend everything" with a focus on especially properties and static classes or even fields.
As specified in this article, you can use the TypeDescriptor
capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like string Data(this MyClass instance)
as an alias for extension method string GetData(this MyClass instance)
as it stores data into the class.
I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell.
And feel free to contribute as the software of tomorrow will come from the community.
Update: August 2016
As dotnet team published what's new in C# 7.0 and from a comment of Mads Torgensen:
Extension properties: we had a (brilliant!) intern implement them over the summer as an experiment, along with other kinds of extension members. We remain interested in this, but it’s a big change and we need to feel confident that it’s worth it.
It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.
Update: May 2017
The extension members has been closed as duplicate of extension everything issue which is closed too. The main discussion was in fact about Type extensibility in a broad sense. The feature is now tracked here as a proposal and has been removed from 7.0 milestone.
Update: August, 2017 - C# 8.0 proposed feature
While it still remains only a proposed feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:
public interface IEmployee
{
public decimal Salary { get; set; }
}
public class Employee
{
public decimal Salary { get; set; }
}
public extension MyPersonExtension extends Person : IEmployee
{
private static readonly ConditionalWeakTable<Person, Employee> _employees =
new ConditionalWeakTable<Person, Employee>();
public decimal Salary
{
get
{
// `this` is the instance of Person
return _employees.GetOrCreate(this).Salary;
}
set
{
Employee employee = null;
if (!_employees.TryGetValue(this, out employee)
{
employee = _employees.GetOrCreate(this);
}
employee.Salary = value;
}
}
}
IEmployee person = new Person();
var salary = person.Salary;
Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in Mads Torgensen podcast, the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...).
For this, you can still use the TypeDescriptor
/ConditionalWeakTable
technique described earlier and with the property extension, hides it under a nice property.
Syntax is still subject to change as implies this issue. For example, extends
could be replaced by for
which some may feel more natural and less java related.
Update December 2018 - Roles, Extensions and static interface members
Extension everything didn't make it to C# 8.0, because of some of drawbacks explained as the end of this GitHub ticket. So, there was an exploration to improve the design. Here, Mads Torgensen explains what are roles and extensions and how they differs:
Roles allow interfaces to be implemented on specific values of a given type. Extensions allow interfaces to be implemented on all values of a given type, within a specific region of code.
It can be seen at a split of previous proposal in two use cases. The new syntax for extension would be like this:
public extension ULongEnumerable of ulong
{
public IEnumerator<byte> GetEnumerator()
{
for (int i = sizeof(ulong); i > 0; i--)
{
yield return unchecked((byte)(this >> (i-1)*8));
}
}
}
then you would be able to do this:
foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
WriteLine($"{e.Current:X}");
}
And for a static interface:
public interface IMonoid<T> where T : IMonoid<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}
Add an extension property on int
and treat the int
as IMonoid<int>
:
public extension IntMonoid of int : IMonoid<int>
{
public static int Zero => 0;
}
or just study /etc/groups (ok this does probably not work if it uses pam with ldap)
The same as you would in .NET:
$DateStr = $Date.ToString("yyyyMMdd")
Or:
$DateStr = '{0:yyyyMMdd}' -f $Date
Put this method somewhere in Util class. This method attach click listener on textview to Copy Content of textView to a clipText on click of that textView
/**
* Param: cliplabel, textview, context
*/
fun attachClickToCopyText(textView: TextView?, clipLabel: String, context: Context?) {
if (textView != null && null != context) {
textView.setOnClickListener {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText(clipLabel, textView!!.text)
clipboard.primaryClip = clip
Snackbar.make(textView,
"Copied $clipLabel", Snackbar.LENGTH_LONG).show()
}
}
}
If some of your services are balking into ulimits, it's sometimes easier to put appropriate commands into service's init-script. For example, when Apache is reporting
[alert] (11)Resource temporarily unavailable: apr_thread_create: unable to create worker thread
Try to put ulimit -s unlimited
into /etc/init.d/httpd
. This does not require a server reboot.
What you're really asking is a related, but substantially different question: how often do I want to truncate names in order to fit them in the database? The answer depends both on the frequency of different lengths of names as well as the maximum lengths chosen. This concern is balanced by the concerns about resources used by the database. Considering how little overhead difference there is between different max lengths for a varchar field I'd generally err on the side of never being forced to truncate a name and make the field as large as I dared.
All answers in one method
static boolean checkEmulator()
{
try
{
String buildDetails = (Build.FINGERPRINT + Build.DEVICE + Build.MODEL + Build.BRAND + Build.PRODUCT + Build.MANUFACTURER + Build.HARDWARE).toLowerCase();
if (buildDetails.contains("generic")
|| buildDetails.contains("unknown")
|| buildDetails.contains("emulator")
|| buildDetails.contains("sdk")
|| buildDetails.contains("genymotion")
|| buildDetails.contains("x86") // this includes vbox86
|| buildDetails.contains("goldfish")
|| buildDetails.contains("test-keys"))
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
try
{
TelephonyManager tm = (TelephonyManager) App.context.getSystemService(Context.TELEPHONY_SERVICE);
String non = tm.getNetworkOperatorName().toLowerCase();
if (non.equals("android"))
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
try
{
if (new File ("/init.goldfish.rc").exists())
return true;
}
catch (Throwable t) {Logger.catchedError(t);}
return false;
}
I needed to do this for a sales report that allows the user to choose a date range. The solution is similar to another answer, but I wanted to provide my example just to show you the practical real world use that I applied this to:
var reportHeader = `Product Sales History Report for ${$('#FromDate').val()} to ${$('#ToDate').val()}.` ;
```
You can also use this approach in case you want to pass some http parameters and send a json request:
(note: I have added in some extra code just incase it helps any other future readers)
public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {
//add the http parameters you wish to pass
List<NameValuePair> postParameters = new ArrayList<>();
postParameters.add(new BasicNameValuePair("param1", "param1_value"));
postParameters.add(new BasicNameValuePair("param2", "param2_value"));
//Build the server URI together with the parameters you wish to pass
URIBuilder uriBuilder = new URIBuilder("http://google.ug");
uriBuilder.addParameters(postParameters);
HttpPost postRequest = new HttpPost(uriBuilder.build());
postRequest.setHeader("Content-Type", "application/json");
//this is your JSON string you are sending as a request
String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";
//pass the json string request in the entity
HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
postRequest.setEntity(entity);
//create a socketfactory in order to use an http connection manager
PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", plainSocketFactory)
.build();
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);
connManager.setMaxTotal(20);
connManager.setDefaultMaxPerRoute(20);
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setSocketTimeout(HttpClientPool.connTimeout)
.setConnectTimeout(HttpClientPool.connTimeout)
.setConnectionRequestTimeout(HttpClientPool.readTimeout)
.build();
// Build the http client.
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(connManager)
.setDefaultRequestConfig(defaultRequestConfig)
.build();
CloseableHttpResponse response = httpclient.execute(postRequest);
//Read the response
String responseString = "";
int statusCode = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
HttpEntity responseHttpEntity = response.getEntity();
InputStream content = responseHttpEntity.getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = buffer.readLine()) != null) {
responseString += line;
}
//release all resources held by the responseHttpEntity
EntityUtils.consume(responseHttpEntity);
//close the stream
response.close();
// Close the connection manager.
connManager.close();
}
You need to enable these extensions in the php.ini file
Before:
;extension=pdo_mysql
;extension=mysqli
;extension=pdo_sqlite
;extension=sqlite3
After:
extension=pdo_mysql
extension=mysqli
extension=pdo_sqlite
extension=sqlite3
It is advisable that you also activate the fileinfo extension, many packages require this.
Every time you do new Random()
it is initialized using the clock. This means that in a tight loop you get the same value lots of times. You should keep a single Random instance and keep using Next on the same instance.
//Function to get a random number
private static readonly Random random = new Random();
private static readonly object syncLock = new object();
public static int RandomNumber(int min, int max)
{
lock(syncLock) { // synchronize
return random.Next(min, max);
}
}
Edit (see comments): why do we need a lock
here?
Basically, Next
is going to change the internal state of the Random
instance. If we do that at the same time from multiple threads, you could argue "we've just made the outcome even more random", but what we are actually doing is potentially breaking the internal implementation, and we could also start getting the same numbers from different threads, which might be a problem - and might not. The guarantee of what happens internally is the bigger issue, though; since Random
does not make any guarantees of thread-safety. Thus there are two valid approaches:
Random
instances per threadEither can be fine; but mutexing a single instance from multiple callers at the same time is just asking for trouble.
The lock
achieves the first (and simpler) of these approaches; however, another approach might be:
private static readonly ThreadLocal<Random> appRandom
= new ThreadLocal<Random>(() => new Random());
this is then per-thread, so you don't need to synchronize.
You get this message when you've used async in your template, but are referring to an object that isn't an Observable.
So for examples sake, lets' say I had these properties in my class:
job:Job
job$:Observable<Job>
Then in my template, I refer to it this way:
{{job | async }}
instead of:
{{job$ | async }}
You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
If the string is Unicode the easiest way is:
import base64
a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))
# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'
b = base64.b64decode(a).decode("utf-8", "ignore")
print(b)
# b :complex string: ñáéíóúÑ
There is no way to get a position which you really want.
For associative array, to determine last iteration you can use already mentioned counter variable, or determine last item's key first:
end($array);
$last = key($array);
foreach($array as $key => value)
if($key == $last) ....
a) Modify Visual Studio Code default virtual env path setting. It's called "python.venvPath". You do this by going into code->settings and scroll down for python settings.
b) Restart VS Code
c) Now if you do Shift + Command + P and type Python: Select Interpreter you should see list of your virtual environments.
You can also use the required module.
require('./componentName.css');
const React = require('react');
I've just come up with a fairly reasonable solution that lets you define the files to build and have directories be automatically created. First, define a variable ALL_TARGET_FILES
that holds the file name of every file that your makefile will be build. Then use the following code:
define depend_on_dir
$(1): | $(dir $(1))
ifndef $(dir $(1))_DIRECTORY_RULE_IS_DEFINED
$(dir $(1)):
mkdir -p $$@
$(dir $(1))_DIRECTORY_RULE_IS_DEFINED := 1
endif
endef
$(foreach file,$(ALL_TARGET_FILES),$(eval $(call depend_on_dir,$(file))))
Here's how it works. I define a function depend_on_dir
which takes a file name and generates a rule that makes the file depend on the directory that contains it and then defines a rule to create that directory if necessary. Then I use foreach
to call
this function on each file name and eval
the result.
Note that you'll need a version of GNU make that supports eval
, which I think is versions 3.81 and higher.
I got here looking for the same thing and I found another solution. If you guys are interested I share this class:
using System;
using System.Management;
using System.Security.Cryptography;
using System.Security;
using System.Collections;
using System.Text;
namespace Security
{
/// <summary>
/// Generates a 16 byte Unique Identification code of a computer
/// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9
/// </summary>
public class FingerPrint
{
private static string fingerPrint = string.Empty;
public static string Value()
{
if (string.IsNullOrEmpty(fingerPrint))
{
fingerPrint = GetHash("CPU >> " + cpuId() + "\nBIOS >> " +
biosId() + "\nBASE >> " + baseId() +
//"\nDISK >> "+ diskId() + "\nVIDEO >> " +
videoId() +"\nMAC >> "+ macId()
);
}
return fingerPrint;
}
private static string GetHash(string s)
{
MD5 sec = new MD5CryptoServiceProvider();
ASCIIEncoding enc = new ASCIIEncoding();
byte[] bt = enc.GetBytes(s);
return GetHexString(sec.ComputeHash(bt));
}
private static string GetHexString(byte[] bt)
{
string s = string.Empty;
for (int i = 0; i < bt.Length; i++)
{
byte b = bt[i];
int n, n1, n2;
n = (int)b;
n1 = n & 15;
n2 = (n >> 4) & 15;
if (n2 > 9)
s += ((char)(n2 - 10 + (int)'A')).ToString();
else
s += n2.ToString();
if (n1 > 9)
s += ((char)(n1 - 10 + (int)'A')).ToString();
else
s += n1.ToString();
if ((i + 1) != bt.Length && (i + 1) % 2 == 0) s += "-";
}
return s;
}
#region Original Device ID Getting Code
//Return a hardware identifier
private static string identifier
(string wmiClass, string wmiProperty, string wmiMustBeTrue)
{
string result = "";
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
if (mo[wmiMustBeTrue].ToString() == "True")
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
}
return result;
}
//Return a hardware identifier
private static string identifier(string wmiClass, string wmiProperty)
{
string result = "";
System.Management.ManagementClass mc =
new System.Management.ManagementClass(wmiClass);
System.Management.ManagementObjectCollection moc = mc.GetInstances();
foreach (System.Management.ManagementObject mo in moc)
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch
{
}
}
}
return result;
}
private static string cpuId()
{
//Uses first CPU identifier available in order of preference
//Don't get all identifiers, as it is very time consuming
string retVal = identifier("Win32_Processor", "UniqueId");
if (retVal == "") //If no UniqueID, use ProcessorID
{
retVal = identifier("Win32_Processor", "ProcessorId");
if (retVal == "") //If no ProcessorId, use Name
{
retVal = identifier("Win32_Processor", "Name");
if (retVal == "") //If no Name, use Manufacturer
{
retVal = identifier("Win32_Processor", "Manufacturer");
}
//Add clock speed for extra security
retVal += identifier("Win32_Processor", "MaxClockSpeed");
}
}
return retVal;
}
//BIOS Identifier
private static string biosId()
{
return identifier("Win32_BIOS", "Manufacturer")
+ identifier("Win32_BIOS", "SMBIOSBIOSVersion")
+ identifier("Win32_BIOS", "IdentificationCode")
+ identifier("Win32_BIOS", "SerialNumber")
+ identifier("Win32_BIOS", "ReleaseDate")
+ identifier("Win32_BIOS", "Version");
}
//Main physical hard drive ID
private static string diskId()
{
return identifier("Win32_DiskDrive", "Model")
+ identifier("Win32_DiskDrive", "Manufacturer")
+ identifier("Win32_DiskDrive", "Signature")
+ identifier("Win32_DiskDrive", "TotalHeads");
}
//Motherboard ID
private static string baseId()
{
return identifier("Win32_BaseBoard", "Model")
+ identifier("Win32_BaseBoard", "Manufacturer")
+ identifier("Win32_BaseBoard", "Name")
+ identifier("Win32_BaseBoard", "SerialNumber");
}
//Primary video controller ID
private static string videoId()
{
return identifier("Win32_VideoController", "DriverVersion")
+ identifier("Win32_VideoController", "Name");
}
//First enabled network card ID
private static string macId()
{
return identifier("Win32_NetworkAdapterConfiguration",
"MACAddress", "IPEnabled");
}
#endregion
}
}
I won't take any credit for this because I found it here It worked faster than I expected for me. Without the graphic card, mac and drive id's I got the unique ID in about 2-3 seconds. With those above included I got it in about 4-5 seconds.
Note: Add reference to System.Management
.
If you want to pass a Uri to another activity, try the method intent.setData(Uri uri) https://developer.android.com/reference/android/content/Intent.html#setData(android.net.Uri)
In another activity, via intent.getData() to obtain the Uri.
There's actually a good reason:
The non-static access does not always work, for reasons of ambiguity.
Suppose we have two classes, A and B, the latter being a subclass of A, with static fields with the same name:
public class A {
public static String VALUE = "Aaa";
}
public class B extends A {
public static String VALUE = "Bbb";
}
Direct access to the static variable:
A.VALUE (="Aaa")
B.VALUE (="Bbb")
Indirect access using an instance (gives a compiler warning that VALUE should be statically accessed):
new B().VALUE (="Bbb")
So far, so good, the compiler can guess which static variable to use, the one on the superclass is somehow farther away, seems somehow logical.
Now to the point where it gets tricky: Interfaces can also have static variables.
public interface C {
public static String VALUE = "Ccc";
}
public interface D {
public static String VALUE = "Ddd";
}
Let's remove the static variable from B, and observe following situations:
B implements C, D
B extends A implements C
B extends A implements C, D
B extends A implements C
where A implements D
B extends A implements C
where C extends D
The statement new B().VALUE
is now ambiguous, as the compiler cannot decide which static variable was meant, and will report it as an error:
error: reference to VALUE is ambiguous
both variable VALUE in C and variable VALUE in D match
And that's exactly the reason why static variables should be accessed in a static way.
A good book on Subversion is Pragmatic Version Control using Subversion where your question is explained, and it gives a lot more information.
Well if you are getting into a linux machine you can use the package manager of that linux distro.
If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)
You could use yum in fedora and do the same.
if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it
Suppose your dataframe is df and you want to change gender from 2 to 1 in participant id 5 then you should determine the row by writing "==" as you can see
df["rowName", "columnName"] <- value
df[df$serial.id==5, "gender"] <- 1
Here is my approach for Bootstrap 2.x. It is just some css. No JavaScript needed:
.accordion-caret .accordion-toggle:hover {
text-decoration: none;
}
.accordion-caret .accordion-toggle:hover span,
.accordion-caret .accordion-toggle:hover strong {
text-decoration: underline;
}
.accordion-caret .accordion-toggle:before {
font-size: 25px;
vertical-align: -3px;
}
.accordion-caret .accordion-toggle:not(.collapsed):before {
content: "?";
margin-right: 0px;
}
.accordion-caret .accordion-toggle.collapsed:before {
content: "?";
margin-right: 0px;
}
Just add class accordion-caret to the accordion-group div, like this:
<div class="accordion-group accordion-caret">
<div class="accordion-heading">
<a class="accordion-toggle" data-toggle="collapse" href="#collapseOne">
<strong>Header</strong>
</a>
</div>
<div id="collapseOne" class="accordion-body collapse in">
<div class="accordion-inner">
Content
</div>
</div>
</div>
android:versionCode — An integer value that represents the version of the application code, relative to other versions.
The value is an integer so that other applications can programmatically evaluate it, for example to check an upgrade or downgrade relationship. You can set the value to any integer you want, however you should make sure that each successive release of your application uses a greater value. The system does not enforce this behavior, but increasing the value with successive releases is normative.
android:versionName — A string value that represents the release version of the application code, as it should be shown to users.
The value is a string so that you can describe the application version as a .. string, or as any other type of absolute or relative version identifier.
As with android:versionCode, the system does not use this value for any internal purpose, other than to enable applications to display it to users. Publishing services may also extract the android:versionName value for display to users.
Typically, you would release the first version of your application with versionCode set to 1, then monotonically increase the value with each release, regardless whether the release constitutes a major or minor release. This means that the android:versionCode value does not necessarily have a strong resemblance to the application release version that is visible to the user (see android:versionName, below). Applications and publishing services should not display this version value to users.
For me the case was completely different. I had created a studio64.exe.vmoptions file in C:\Users\YourUserName\.AndroidStudio3.4\config. In that folder, I had a typo of extra spaces. Due to that I was getting the same error.
I replaced the studio64.exe.vmoptions with the following code.
# custom Android Studio VM options, see https://developer.android.com/studio/intro/studio-config.html
-server
-Xms1G
-Xmx8G
# I have 8GB RAM so it is 8G. Replace it with your RAM size.
-XX:MaxPermSize=1G
-XX:ReservedCodeCacheSize=512m
-XX:+UseCompressedOops
-XX:+UseConcMarkSweepGC
-XX:SoftRefLRUPolicyMSPerMB=50
-da
-Djna.nosys=true
-Djna.boot.library.path=
-Djna.debug_load=true
-Djna.debug_load.jna=true
-Dsun.io.useCanonCaches=false
-Djava.net.preferIPv4Stack=true
-XX:+HeapDumpOnOutOfMemoryError
-Didea.paths.selector=AndroidStudio2.1
-Didea.platform.prefix=AndroidStudio
<content>(?:[^\n]*(\n+))+</content>
After a few futile hours battling with a 'SyntaxError: missing : after property id' message I can now expand on this topic:
border-width is a valid css property but it is not included in the jQuery css oject definition, so .css({border-width: '2px'}) will cause an error, but it's quite happy with .css({'border-width': '2px'}), presumably property names in quotes are just passed on as received.
in a Visual Basic Macro you would use
pName = ActiveWorkbook.Path ' the path of the currently active file
wbName = ActiveWorkbook.Name ' the file name of the currently active file
shtName = ActiveSheet.Name ' the name of the currently selected worksheet
The first sheet in a workbook can be referenced by
ActiveWorkbook.Worksheets(1)
so after deleting the [Report] tab you would use
ActiveWorkbook.Worksheets("Report").Delete
shtName = ActiveWorkbook.Worksheets(1).Name
to "work on that sheet later on" you can create a range object like
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(shtName).[A1]
and continue working on MySheet(rowNum, colNum)
etc. ...
shortcut creation of a range object without defining shtName:
Dim MySheet as Range
MySheet = ActiveWorkbook.Worksheets(1).[A1]
You simply need to remove v-bind (:) from selected and required attributes. Like this :-
<template>_x000D_
<select class="form-control" v-model="selected" required @change="changeLocation">_x000D_
<option selected>Choose Province</option>_x000D_
<option v-for="option in options" v-bind:value="option.id" >{{ option.name }}</option>_x000D_
</select>_x000D_
</template>
_x000D_
You are not binding anything to the vue instance through these attributes thats why it is giving error.
1 - You have to declare in your connection the propertie of enconding UTF8. http://php.net/manual/en/mysqli.set-charset.php.
2 - If you are using mysql commando line to execute a script, you have to use the flag, like:
Cmd: C:\wamp64\bin\mysql\mysql5.7.14\bin\mysql.exe -h localhost -u root -P 3306 --default-character-set=utf8 omega_empresa_parametros_336 < C:\wamp64\www\PontoEletronico\PE10002Corporacao\BancoDeDadosModelo\omega_empresa_parametros.sql
Try adding parentheses around the row in table1
e.g.
DELETE
FROM table1
WHERE (stn, year(datum)) IN (SELECT stn, jaar FROM table2);
The above is Standard SQL-92 code. If that doesn't work, it could be that your SQL product of choice doesn't support it.
Here's another Standard SQL approach that is more widely implemented among vendors e.g. tested on SQL Server 2008:
MERGE INTO table1 AS t1
USING table2 AS s1
ON t1.stn = s1.stn
AND s1.jaar = YEAR(t1.datum)
WHEN MATCHED THEN DELETE;
Since you need to handle the date string before it is converted to a date in your model, I'd override the accessor for that field
Let's say your date field is published_date
. Add this to your model object:
def published_date=(value)
# do sanity checking here
# then hand it back to rails to convert and store
self.write_attribute(:published_date, value)
end
If you have to do group by
using hibernate criteria use projections.groupPropery
like the following,
@Autowired
private SessionFactory sessionFactory;
Criteria crit = sessionFactory.getCurrentSession().createCriteria(studentModel.class);
crit.setProjection(Projections.projectionList()
.add(Projections.groupProperty("studentName").as("name"))
List result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();
return result;
this is how i do it to remember 2,147,483,647
2 - To
1 - A
4 - Far
7 - Savannah
4 - Quarter
8 - Optimus
3 - Trio
6 - Hexed
4 - Forty
7 - Septenary
SQL query to show all tables that have specified column name:
SELECT SCHEMA_NAME(schema_id) + '.' + t.name AS 'Table Name'
FROM sys.tables t
INNER JOIN sys.columns c ON c.object_id = t.object_id
WHERE c.name like '%ColumnName%'
ORDER BY 'Table Name'
I also face this issue but it is resolved in different way. Steps that I follow may be helpful for others.
If your string contains special characters you can hash it to md5 and then convert it to a guid/uniqueidentifier.
SELECT CONVERT(UNIQUEIDENTIFIER, HASHBYTES('MD5','~öü߀a89b1acd95016ae6b9c8aabb07da2010'))
SPAN class code. Stylesheet:
<link rel="stylesheet" type="text/css" href="http://cdn.webrupee.com/font">
Now use the below mentioned code to type Indian Rupee symbol,
<span class="WebRupee">Rs.</span>
Once the popular font families will be updated to Unicode 6.0.0, then you will be able to type Indian Rupee Symbol by typing ₹ in HTML editor.
In 1.0 and 2.0 you can use createElement
prop of Router
to specify how exactly to create your target element. Documentation source
function createWithDefaultProps(Component, props) {
return <Component {...props} myprop="value" />;
}
// and then
<Router createElement={createWithDefaultProps}>
...
</Router>
This is a known bug on Linux Debian. I solved using the create_tables.sql in the official package and changing pma_ with pma__ inside /etc/phpmyadmin/config.inc.php
Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.
Example:
List<Float> unindexedVectors = new ArrayList<Float>();
unindexedVectors.add(2.22f);
unindexedVectors.get(2);
//Loop thro' the entire character array and keep 'i' as the basis of your permutation and keep finding the combination like you swap [ab, ba]
public class Permutation {
//Act as a queue
private List<Character> list;
//To remove the duplicates
private Set<String> set = new HashSet<String>();
public Permutation(String s) {
list = new LinkedList<Character>();
int len = s.length();
for(int i = 0; i < len; i++) {
list.add(s.charAt(i));
}
}
public List<String> getStack(Character c, List<Character> list) {
LinkedList<String> stack = new LinkedList<String>();
stack.add(""+c);
for(Character ch: list) {
stack.add(""+ch);
}
return stack;
}
public String printCombination(String s1, String s2) {
//S1 will be a single character
StringBuilder sb = new StringBuilder();
String[] strArr = s2.split(",");
for(String s: strArr) {
sb.append(s).append(s1);
sb.append(",");
}
for(String s: strArr) {
sb.append(s1).append(s);
sb.append(",");
}
return sb.toString();
}
public void printPerumtation() {
int cnt = list.size();
for(int i = 0; i < cnt; i++) {
Character c = list.get(0);
list.remove(0);
List<String> stack = getStack(c, list);
while(stack.size() > 1) {
//Remove the top two elements
String s2 = stack.remove(stack.size() - 1);
String s1 = stack.remove(stack.size() - 1);
String comS = printCombination(s1, s2);
stack.add(comS);
}
String[] perms = (stack.remove(0)).split(",");
for(String perm: perms) {
set.add(perm);
}
list.add(c);
}
for(String s: set) {
System.out.println(s);
}
}
}
I posted a somewhat similar question a while back, but regarding a model on CI.
Returning two separate query results within a model function
Although your question is not exactly the same, I believe the solution follows the same principle: if you're proposing to do what you mention in your question, there may be something wrong in the way you're coding and some refactoring could be in order.
The take home message is that what you're asking is not the way to go when working with MVC.
The best practice is to either use a Model to place reusable functions and call them in a controller that outputs the data through a view -- or even better use helpers or libraries (for functions that may be needed repeatedly).
I had to right-click the project, and select "Reimport" under the "Run Maven" submenu.
For me what worked by combining all the posts I have read is:
1.Enable OLE automation - if not enabled
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
2.Create a folder where the generated files will be stored:
C:\GREGTESTING
3.Create DocTable that will be used for file generation and store there the blobs in Doc_Content
CREATE TABLE [dbo].[Document](
[Doc_Num] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[Extension] [varchar](50) NULL,
[FileName] [varchar](200) NULL,
[Doc_Content] [varbinary](max) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
INSERT [dbo].[Document] ([Extension] ,[FileName] , [Doc_Content] )
SELECT 'pdf', 'SHTP Notional hire - January 2019.pdf', 0x....(varbinary blob)
Important note!
Don't forget to add in Doc_Content column the varbinary of file you want to generate!
4.Run the below script
DECLARE @outPutPath varchar(50) = 'C:\GREGTESTING'
, @i bigint
, @init int
, @data varbinary(max)
, @fPath varchar(max)
, @folderPath varchar(max)
--Get Data into temp Table variable so that we can iterate over it
DECLARE @Doctable TABLE (id int identity(1,1), [Doc_Num] varchar(100) , [FileName] varchar(100), [Doc_Content] varBinary(max) )
INSERT INTO @Doctable([Doc_Num] , [FileName],[Doc_Content])
Select [Doc_Num] , [FileName],[Doc_Content] FROM [dbo].[Document]
SELECT @i = COUNT(1) FROM @Doctable
WHILE @i >= 1
BEGIN
SELECT
@data = [Doc_Content],
@fPath = @outPutPath + '\' + [Doc_Num] +'_' +[FileName],
@folderPath = @outPutPath + '\'+ [Doc_Num]
FROM @Doctable WHERE id = @i
EXEC sp_OACreate 'ADODB.Stream', @init OUTPUT; -- An instace created
EXEC sp_OASetProperty @init, 'Type', 1;
EXEC sp_OAMethod @init, 'Open'; -- Calling a method
EXEC sp_OAMethod @init, 'Write', NULL, @data; -- Calling a method
EXEC sp_OAMethod @init, 'SaveToFile', NULL, @fPath, 2; -- Calling a method
EXEC sp_OAMethod @init, 'Close'; -- Calling a method
EXEC sp_OADestroy @init; -- Closed the resources
print 'Document Generated at - '+ @fPath
--Reset the variables for next use
SELECT @data = NULL
, @init = NULL
, @fPath = NULL
, @folderPath = NULL
SET @i -= 1
END
Limit the length of characters in a regular expression? ^[a-z]{6,15}$'
Limit length of characters or Numbers in a regular expression? ^[a-z | 0-9]{6,15}$'
I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.
Dockerfile
...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash
Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.
Simply define two properties of parent of that EditText
as :
android:clickable="true"
android:focusableInTouchMode="true"
So when user will touch outside of EditText
area, focus will be removed because focus will be transferred to parent view.
I haven't seen any decompilers that generate C++ code. I've seen a few experimental ones that make a reasonable attempt at generating C code, but they tended to be dependent on matching the code-generation patterns of a particular compiler (that may have changed, it's been awhile since I last looked into this). Of course any symbolic information will be gone. Google for "decompiler".
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString
it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
You can get your result by simply use substr():
Syntax substr(string,start,length)
Example
<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>
Output :
Hello
This is an old qustion, but I had to do it myself recently and I achieved something working so (besides response like mine would save me some time): Basically use ffmpeg to change the container to HLS, most of the IPCams stream h264 and some basic type of PCM, so use something like that:
ffmpeg -v info -i rtsp://ip:port/h264.sdp -c:v copy -c:a copy -bufsize 1835k -pix_fmt yuv420p -flags -global_header -hls_time 10 -hls_list_size 6 -hls_wrap 10 -start_number 1 /var/www/html/test.m3u8
Then use video.js with HLS plugin This will play Live stream nicely There is also a jsfiddle example under second link).
Note: although this is not a native support it doesn't require anything extra on user frontend.
If the file contains only parameter assignments, you can use the following loop in place of sourcing it:
# Instead of source file.txt
while IFS="=" read name value; do
declare "$name=$value"
done < file.txt
This saves you having to quote anything in the file, and is also more secure, as you don't risk executing arbitrary code from file.txt
.
Here is a QuickSort that I wrote for the arrays returned from the GetRows method of ADODB.Recordset.
'Author: Eric Weilnau
'Date Written: 7/16/2003
'Description: QuickSortDataArray sorts a data array using the QuickSort algorithm.
' Its arguments are the data array to be sorted, the low and high
' bound of the data array, the integer index of the column by which the
' data array should be sorted, and the string "asc" or "desc" for the
' sort order.
'
Sub QuickSortDataArray(dataArray, loBound, hiBound, sortField, sortOrder)
Dim pivot(), loSwap, hiSwap, count
ReDim pivot(UBound(dataArray))
If hiBound - loBound = 1 Then
If (sortOrder = "asc" and dataArray(sortField,loBound) > dataArray(sortField,hiBound)) or (sortOrder = "desc" and dataArray(sortField,loBound) < dataArray(sortField,hiBound)) Then
Call SwapDataRows(dataArray, hiBound, loBound)
End If
End If
For count = 0 to UBound(dataArray)
pivot(count) = dataArray(count,int((loBound + hiBound) / 2))
dataArray(count,int((loBound + hiBound) / 2)) = dataArray(count,loBound)
dataArray(count,loBound) = pivot(count)
Next
loSwap = loBound + 1
hiSwap = hiBound
Do
Do While (sortOrder = "asc" and dataArray(sortField,loSwap) <= pivot(sortField)) or sortOrder = "desc" and (dataArray(sortField,loSwap) >= pivot(sortField))
loSwap = loSwap + 1
If loSwap > hiSwap Then
Exit Do
End If
Loop
Do While (sortOrder = "asc" and dataArray(sortField,hiSwap) > pivot(sortField)) or (sortOrder = "desc" and dataArray(sortField,hiSwap) < pivot(sortField))
hiSwap = hiSwap - 1
Loop
If loSwap < hiSwap Then
Call SwapDataRows(dataArray,loSwap,hiSwap)
End If
Loop While loSwap < hiSwap
For count = 0 to Ubound(dataArray)
dataArray(count,loBound) = dataArray(count,hiSwap)
dataArray(count,hiSwap) = pivot(count)
Next
If loBound < (hiSwap - 1) Then
Call QuickSortDataArray(dataArray, loBound, hiSwap-1, sortField, sortOrder)
End If
If (hiSwap + 1) < hiBound Then
Call QuickSortDataArray(dataArray, hiSwap+1, hiBound, sortField, sortOrder)
End If
End Sub
We can find these by looking at Bootstrap's stylesheet, Bootstrap.css. Each \{number}
represents a hexadecimal value, so \2a
is equal to 0x2a
or *
.
As for the font, that can be downloaded from http://glyphicons.com.
.glyphicon-asterisk:before {
content: "\2a";
}
.glyphicon-plus:before {
content: "\2b";
}
.glyphicon-euro:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
This will solve your problem
interface
TArrayStr = Array Of string;
implementation
function SplitString(Text: String): TArrayStr;
var
intIdx: Integer;
intIdxOutput: Integer;
const
Delimiter = ';';
begin
intIdxOutput := 0;
SetLength(Result, 1);
Result[0] := '';
for intIdx := 1 to Length(Text) do
begin
if Text[intIdx] = Delimiter then
begin
intIdxOutput := intIdxOutput + 1;
SetLength(Result, Length(Result) + 1);
end
else
Result[intIdxOutput] := Result[intIdxOutput] + Text[intIdx];
end;
end;
Noticed mine worked on chrome. Got it to work in Firefox
by going to <about:config>
and setting full-screen-api.allow-trusted-requests-only
to false
.
After full screen worked once, I could set that back to true, and full screen still worked which was quite perplexing.
Since Python 2.6.X you might want to use:
"my {0} string: {1}".format("cool", "Hello there!")
There is no solution for this within the .net framework.
http://www.eldos.com/sbb/sftpcompare.php outlines a list of un-free options.
your best free bet is to extend SSH using Granados. http://www.routrek.co.jp/en/product/varaterm/granados.html
declarative program is just a data for its some more-or-less "universal" imperative implementation/vm.
pluses: specifying just a data, in some hardcoded (and checked) format, is simpler and less error-prone than specifying variant of some imperative algorithm directly. some complex specifications just cant be written directly, only in some DSL form. best and freq used in DSLs data structures is sets and tables. because you not have dependencies between elements/rows. and when you havent dependencies you have freedom to modify and ease of support. (compare for example modules with classes - with modules you happy and with classes you have fragile base class problem) all goods of declarativeness and DSL follows immediately from benefits of that data structures (tables and sets). another plus - you can change implementation of declarative language vm, if DSL is more-or-less abstract (well designed). make parallel implementation, for example. or port it to other os etc. all good specifed modular isolating interfaces or protocols gives you such freedom and easyness of support.
minuses: you guess right. generic (and parameterized by DSL) imperative algorithm/vm implementation may be slower and/or memory hungry than specific one. in some cases. if that cases is rare - just forget about it, let it be slow. if it's frequient - you always can extend your DSL/vm for that case. somewhere slowing down all other cases, sure...
P.S. Frameworks is half-way between DSL and imperative. and as all halfway solutions ... they combines deficiences, not benefits. they not so safe AND not so fast :) look at jack-of-all-trades haskell - it's halfway between strong simple ML and flexible metaprog Prolog and... what a monster it is. you can look at Prolog as a Haskell with boolean-only functions/predicates. and how simple its flexibility is against Haskell...
Using =
causes the variable to be assigned a value. If the variable already had a value, it is replaced. This value will be expanded when it is used. For example:
HELLO = world
HELLO_WORLD = $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using :=
is similar to using =
. However, instead of the value being expanded when it is used, it is expanded during the assignment. For example:
HELLO = world
HELLO_WORLD := $(HELLO) world!
# This echoes "world world!"
echo $(HELLO_WORLD)
HELLO = hello
# Still echoes "world world!"
echo $(HELLO_WORLD)
HELLO_WORLD := $(HELLO) world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
Using ?=
assigns the variable a value iff the variable was not previously assigned. If the variable was previously assigned a blank value (VAR=
), it is still considered set I think. Otherwise, functions exactly like =
.
Using +=
is like using =
, but instead of replacing the value, the value is appended to the current one, with a space in between. If the variable was previously set with :=
, it is expanded I think. The resulting value is expanded when it is used I think. For example:
HELLO_WORLD = hello
HELLO_WORLD += world!
# This echoes "hello world!"
echo $(HELLO_WORLD)
If something like HELLO_WORLD = $(HELLO_WORLD) world!
were used, recursion would result, which would most likely end the execution of your Makefile. If A := $(A) $(B)
were used, the result would not be the exact same as using +=
because B
is expanded with :=
whereas +=
would not cause B
to be expanded.
replace
[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2
[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3
with
[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2
[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3
e.g. installing into /usr/local/bin
instead of /usr/bin
.
and ensure the /usr/local/bin
is before /usr/bin
in PATH.
i.e.
[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin
Ensure this always is the case by adding
export PATH=/usr/local/bin:$PATH
to the end of your ~/.bashrc
file. Prefixing the PATH
environment variable with custom bin folder such as /usr/local/bin
or /opt/<some install>/bin
is generally recommended to ensure that customizations are found before the default system ones.
The error that you get does not seem to be related to the RequestHeader.
And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
// your code goes here
}
And your REST class should have annotations like:
@Controller
@RequestMapping("/rest/")
Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.
Example:
@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
String userAgent = request.getHeader("user-agent");
}
Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)
I also had a working system that suddenly stopped working with the described error.
After furtling around in my /lib/modules it would appear that the vboxvfs
module is no more. Instead modprobe vboxsf
was the required incantation to get things restarted.
Not sure when that change ocurred, but it caught me out.
How about this. using the modulo operator
if(a%b==0)
{
System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
System.out.println("b is NOT a factor of a");
}
The HTML spec here is really broken. It should allow nested optgroups and recommend user agents render them as nested menus. Instead, only one optgroup level is allowed. However, they do have to say the following on the subject:
Note. Implementors are advised that future versions of HTML may extend the grouping mechanism to allow for nested groups (i.e., OPTGROUP elements may nest). This will allow authors to represent a richer hierarchy of choices.
And user agents could start using submenus to render optgoups instead of displaying titles before the first option element in an optgroup as they do now.
On a Windows machine, the .m2 folder is expected to be located under ${user.home}
. On Windows 7 and Vista this resolves to <root>\Users\<username>
and on XP it is <root>\Documents and Settings\<username>\.m2
. So you'd normally see it under c:\Users\Jonathan\.m2
.
If you want to create a folder with a .
prefix on Windows, you can simply do this on the command line.
Note that you don't actually need the .m2 location unless you want to create a distinct user settings file, which is optional (see the Settings reference for more details).
If you don't need a separate user settings file and don't really want the local repository under your user home you can simply set the location of your repository to a different folder by modifying the global settings file (located in \conf\settings.xml).
The following snippet would set the local repository to c:\Maven\repository
for example:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>c:\Maven\repository</localRepository>
...
I had to do two things to the IIS configuration of the site/application. My issue had to do with getting net.tcp working in an IIS Web Site App:
First:
Second:
Just found another solutions worked for me. You can use '\' sign before your one special.
passwd=\@31\&3*J
The Hibernate Validator requires — but does not include — an Expression Language (EL) implementation. Adding a dependency on one will will fix the issue.
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.el</artifactId>
<version>3.0.3</version>
</dependency>
This requirement is documented in the Getting started with Hibernate Validator documentation. In a Java EE environment, it would be provided by the container. In a standalone application such as yours, it needs to be provided.
Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages.
When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container.
In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance, you can add the following dependency to use the JSR 341 reference implementation:
<dependency> <groupId>org.glassfish</groupId> <artifactId>jakarta.el</artifactId> <version>${version.jakarta.el-api}</version> </dependency>
There are other EL implementations that can be used other than Glassfish. For instance, Spring Boot versions 2.2.x and earlier by default used embedded Tomcat (it's since switched to use the Jakarta EL reference implementation). That version of EL can be used as follows:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>9.0.41</version>
</dependency>
That said, in a Spring Boot project, typically one would use the spring-boot-starter-validation
dependency rather than specifying the Hibernate validator & EL libraries directly. That dependency includes both hibernate-validator
and the EL implementation.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.4.2.RELEASE</version>
</dependency>
First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.
Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.
The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse
method for more info. But then, again, note that an IP might have multiple names associated with it.
With Swift 3 and Swift 4, String
has a method called data(using:allowLossyConversion:)
. data(using:allowLossyConversion:)
has the following declaration:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
Returns a Data containing a representation of the String encoded using a given encoding.
With Swift 4, String
's data(using:allowLossyConversion:)
can be used in conjunction with JSONDecoder
's decode(_:from:)
in order to deserialize a JSON string into a dictionary.
Furthermore, with Swift 3 and Swift 4, String
's data(using:allowLossyConversion:)
can also be used in conjunction with JSONSerialization
's json?Object(with:?options:?)
in order to deserialize a JSON string into a dictionary.
With Swift 4, JSONDecoder
has a method called decode(_:from:)
. decode(_:from:)
has the following declaration:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
Decodes a top-level value of the given type from the given JSON representation.
The Playground code below shows how to use data(using:allowLossyConversion:)
and decode(_:from:)
in order to get a Dictionary
from a JSON formatted String
:
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
With Swift 3 and Swift 4, JSONSerialization
has a method called json?Object(with:?options:?)
. json?Object(with:?options:?)
has the following declaration:
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
Returns a Foundation object from given JSON data.
The Playground code below shows how to use data(using:allowLossyConversion:)
and json?Object(with:?options:?)
in order to get a Dictionary
from a JSON formatted String
:
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}
SELECT * FROM users WHERE created >= CURDATE();
But I think you mean created < today
If you want to get number of physical cores you can run cmd and terminal command and then to parse the output to get info you need.Below is shown function that returns number of physical cores .
private int getNumberOfCPUCores() {
OSValidator osValidator = new OSValidator();
String command = "";
if(osValidator.isMac()){
command = "sysctl -n machdep.cpu.core_count";
}else if(osValidator.isUnix()){
command = "lscpu";
}else if(osValidator.isWindows()){
command = "cmd /C WMIC CPU Get /Format:List";
}
Process process = null;
int numberOfCores = 0;
int sockets = 0;
try {
if(osValidator.isMac()){
String[] cmd = { "/bin/sh", "-c", command};
process = Runtime.getRuntime().exec(cmd);
}else{
process = Runtime.getRuntime().exec(command);
}
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
try {
while ((line = reader.readLine()) != null) {
if(osValidator.isMac()){
numberOfCores = line.length() > 0 ? Integer.parseInt(line) : 0;
}else if (osValidator.isUnix()) {
if (line.contains("Core(s) per socket:")) {
numberOfCores = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]);
}
if(line.contains("Socket(s):")){
sockets = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]);
}
} else if (osValidator.isWindows()) {
if (line.contains("NumberOfCores")) {
numberOfCores = Integer.parseInt(line.split("=")[1]);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
if(osValidator.isUnix()){
return numberOfCores * sockets;
}
return numberOfCores;
}
OSValidator class:
public class OSValidator {
private static String OS = System.getProperty("os.name").toLowerCase();
public static void main(String[] args) {
System.out.println(OS);
if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}
public static boolean isWindows() {
return (OS.indexOf("win") >= 0);
}
public static boolean isMac() {
return (OS.indexOf("mac") >= 0);
}
public static boolean isUnix() {
return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
}
public static boolean isSolaris() {
return (OS.indexOf("sunos") >= 0);
}
public static String getOS(){
if (isWindows()) {
return "win";
} else if (isMac()) {
return "osx";
} else if (isUnix()) {
return "uni";
} else if (isSolaris()) {
return "sol";
} else {
return "err";
}
}
}
Yet another option is to cast the XML as nvarchar, and then search for the given string as if the XML vas a nvarchar field.
SELECT *
FROM Table
WHERE CAST(Column as nvarchar(max)) LIKE '%TEST%'
I love this solution as it is clean, easy to remember, hard to mess up, and can be used as a part of a where clause.
EDIT: As Cliff mentions it, you could use:
...nvarchar if there's characters that don't convert to varchar
A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.
If you want to control the width of your data, then you could use the width
sub-specifiers in the printf
format string. Eg. :
printf("%5d", 2);
It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.
If you want complete control, you'll probably have to implement it yourself.