Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.
So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.
Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.
TypeScript, React, index.html
//conf.js:
window.bar = "bar";
//index.html
<script type="module" src="./conf.js"></script>
//tsconfig.json
"include": ["typings-custom/**/*.ts"]
//typings-custom/typings.d.ts
declare var bar:string;
//App.tsx
console.log('bar', window.bar);
or
console.log('bar', bar);
in the file .eslintrc.json in side roles add this code it will solve this issue
"rules": {
"prettier/prettier": ["error",{
"endOfLine": "auto"}
]
}
Reading answers here, it seems that the error "RenderBox was not laid out" is caused when somehow the ListView size is limitless and this can happen in different scenarios.
Just aiming to help who may have the same case as mine. In my case, I was getting this error because my ListView was inside a a column whose parent was a SingleChildScrollView. I remove this parent and it worked.
Here is my working code:
List _todoList = ["AAA", "BBB"];
...
body: Column(
children: [
Container(...),
Expanded(
child: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_todoList[index]));
}))
],
));
Here how it was when I was getting the "not laid out" error:
List _todoList = ["AAA", "BBB"];
...
body: SingleChildScrollView(child: Column(
children: [
Container(...),
Expanded(
child: ListView.builder(
itemCount: _todoList.length,
itemBuilder: (context, index) {
return ListTile(title: Text(_todoList[index]));
}))
],
)));
I hope this may be useful for someone.
Check out this documentation page: https://msdn.microsoft.com/en-us/library/ms132397(v=vs.110).aspx
The Add function is the first one under Methods.
The provider is bundled with PowerShell>=6.0.
If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.
Simply call this method to get the Firebase Messaging Token
public void getFirebaseMessagingToken ( ) {
FirebaseMessaging.getInstance ().getToken ()
.addOnCompleteListener ( task -> {
if (!task.isSuccessful ()) {
//Could not get FirebaseMessagingToken
return;
}
if (null != task.getResult ()) {
//Got FirebaseMessagingToken
String firebaseMessagingToken = Objects.requireNonNull ( task.getResult () );
//Use firebaseMessagingToken further
}
} );
}
The above code works well after adding this dependency in build.gradle file
implementation 'com.google.firebase:firebase-messaging:21.0.0'
Note: This is the code modification done for the above dependency to resolve deprecation. (Working code as of 1st November 2020)
Extend the DOM Element, Handle the Error, and Degrade Gracefully
Below I use the prototype function to wrap the native DOM play function, grab its promise, and then degrade to a play button if the browser throws an exception. This extension addresses the shortcoming of the browser and is plug-n-play in any page with knowledge of the target element(s).
// JavaScript
// Wrap the native DOM audio element play function and handle any autoplay errors
Audio.prototype.play = (function(play) {
return function () {
var audio = this,
args = arguments,
promise = play.apply(audio, args);
if (promise !== undefined) {
promise.catch(_ => {
// Autoplay was prevented. This is optional, but add a button to start playing.
var el = document.createElement("button");
el.innerHTML = "Play";
el.addEventListener("click", function(){play.apply(audio, args);});
this.parentNode.insertBefore(el, this.nextSibling)
});
}
};
})(Audio.prototype.play);
// Try automatically playing our audio via script. This would normally trigger and error.
document.getElementById('MyAudioElement').play()
<!-- HTML -->
<audio id="MyAudioElement" autoplay>
<source src="https://www.w3schools.com/html/horse.ogg" type="audio/ogg">
<source src="https://www.w3schools.com/html/horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Might have todo with one of these:
In case you do need to define dataSource()
, for example when you have multiple data sources, you can use:
@Autowired Environment env;
@Primary
@Bean
public DataSource customDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("custom.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("custom.datasource.url"));
dataSource.setUsername(env.getProperty("custom.datasource.username"));
dataSource.setPassword(env.getProperty("custom.datasource.password"));
return dataSource;
}
By setting up the dataSource
yourself (instead of using DataSourceBuilder
), it fixed my problem which you also had.
The always knowledgeable Baeldung has a tutorial which explains in depth.
-May be the problem is that you have deleted .java files doing this doesn't delete the .XML files so go to res-> layout and delete those .XML files that you had delete before. -the another problem may be you haven't delete the files that is present in manifests under syntax that you deleted recently... So delete and run the code
Also I had an issue because I was versioning the application in IIS level like below:
If doing this then the configuration at the Configure method should append the version number like below:
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/1.0/swagger/V1/swagger.json", "Static Data Service");
});
In my case I found once I rebuild the app it worked.
I had imported the HttpClientModule
as specified in the previous posts but I was still getting the error. I stopped the server, rebuilt the app (ng serve
) and it worked.
Enable Multidex through build.gradle
of your app module
multiDexEnabled true
Same as below -
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.xx.xxx"
minSdkVersion 15
targetSdkVersion 27
versionCode 1
versionName "1.0"
multiDexEnabled true //Add this
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
shrinkResources true
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
Then follow below steps -
Build
menu -> press the Clean Project
button.Rebuild Project
button from the Build
menu.File -> Invalidate cashes / Restart
compile
is now deprecated so it's better to use implementation
or api
Just try to without changing anything
npm install [email protected]
X.X.X is your current version
I am successfully able to log a file using the following code
public static void Main(string[] args)
{
XmlDocument log4netConfig = new XmlDocument();
log4netConfig.Load(File.OpenRead("log4net.config"));
var repo = log4net.LogManager.CreateRepository(Assembly.GetEntryAssembly(),
typeof(log4net.Repository.Hierarchy.Hierarchy));
log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
BuildWebHost(args).Run();
}
log4net.config in website root
<?xml version="1.0" encoding="utf-8" ?>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
<file value="C:\Temp\" />
<datePattern value="yyyy-MM-dd.'txt'"/>
<staticLogFileName value="false"/>
<appendToFile value="true"/>
<rollingStyle value="Date"/>
<maxSizeRollBackups value="100"/>
<maximumFileSize value="15MB"/>
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level App %newline %message %newline %newline"/>
</layout>
</appender>
<root>
<level value="ALL"/>
<appender-ref ref="RollingLogFileAppender"/>
</root>
</log4net>
For PHP 7.2 in Ubuntu 18.04 LTS
sudo apt-get install php7.2-zip
Works like a charm
total edge case here: I had this issue installing an Arch AUR PKGBUILD file manually. In my case I needed to delete the 'pkg', 'src' and 'node_modules' folders, then it built fine without this npm error.
{% url namespace:url_name %}
. So, check if you have added the app_name
in urls.py.path('<int:question_id>/', views.detail, name='question_detail')
whereas the index.html file had the following entry <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
. Notice the incorrect name.It is possible to use your usual System.Configuration
even in .NET Core 2.0 on Linux. Try this test example:
MyLib.dll
)System.Configuration.ConfigurationManager
v4.4.0. This is needed since this package isn't covered by the meta-package NetStandard.Library
v2.0.0 (I hope that changes)ConfigurationSection
or ConfigurationElement
go into MyLib.dll
. For example MyClass.cs
derives from ConfigurationSection
and MyAccount.cs
derives from ConfigurationElement
. Implementation details are out of scope here but Google is your friend.MyApp.dll
). .NET Core apps end with .dll
rather than .exe
in Framework.app.config
in MyApp
with your custom configuration sections. This should obviously match your class designs in #3 above. For example:<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="myCustomConfig" type="MyNamespace.MyClass, MyLib" />
</configSections>
<myCustomConfig>
<myAccount id="007" />
</myCustomConfig>
</configuration>
That's it - you'll find that the app.config is parsed properly within MyApp
and your existing code within MyLib
works just fine. Don't forget to run dotnet restore
if you switch platforms from Windows (dev) to Linux (test).
Additional workaround for test projects
If you're finding that your App.config
is not working in your test projects, you might need this snippet in your test project's .csproj
(e.g. just before the ending </Project>
). It basically copies App.config
into your output folder as testhost.dll.config
so dotnet test
picks it up.
<!-- START: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
<Target Name="CopyCustomContent" AfterTargets="AfterBuild">
<Copy SourceFiles="App.config" DestinationFiles="$(OutDir)\testhost.dll.config" />
</Target>
<!-- END: This is a buildtime work around for https://github.com/dotnet/corefx/issues/22101 -->
In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.
So register the ChildComponent in Shared Module manually.
Deleted the package-lock.json file & then ran
npm install
Use a custom Action/Controller Attribute to set the CORS headers.
Example:
public class AllowMyRequestsAttribute : ControllerAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
// check origin
var origin = context.HttpContext.Request.Headers["origin"].FirstOrDefault();
if (origin == someValidOrigin)
{
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", origin);
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Headers", "*");
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Methods", "*");
// Add whatever CORS Headers you need.
}
}
public void OnActionExecuting(ActionExecutingContext context)
{
// empty
}
}
Then on the Web API Controller / Action:
[ApiController]
[AllowMyRequests]
public class MyController : ApiController
{
[HttpGet]
public ActionResult<string> Get()
{
return "Hello World";
}
}
Having something like this:
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('projectid', this.id);
let params = new URLSearchParams();
params.append("someParamKey", this.someParamValue)
this.http.get('http://localhost:63203/api/CallCenter/GetSupport', { headers: headers, search: params })
Of course, appending every param you need to params
. It gives you a lot more flexibility than just using a URL string to pass params to the request.
EDIT(28.09.2017): As Al-Mothafar stated in a comment, search
is deprecated as of Angular 4, so you should use params
EDIT(02.11.2017): If you are using the new HttpClient
there are now HttpParams
, which look and are used like this:
let params = new HttpParams().set("paramName",paramValue).set("paramName2", paramValue2); //Create new HttpParams
And then add the params to the request in, basically, the same way:
this.http.get(url, {headers: headers, params: params});
//No need to use .map(res => res.json()) anymore
More in the docs for HttpParams
and HttpClient
You could use the CSS calc
parameter to calculate the height dynamically like so:
.dynamic-height {_x000D_
color: #000;_x000D_
font-size: 12px;_x000D_
margin-top: calc(100% - 10px);_x000D_
text-align: left;_x000D_
}
_x000D_
<div class='dynamic-height'>_x000D_
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.</p>_x000D_
</div>
_x000D_
In newer versions of OS X (especially Yosemite, EL Capitan), Apple has removed Java support for security reasons. To fix this you have to do the following.
Mount the disk image file and install Java 6 runtime for OS X.
After this you should not be seeing any of the below messages:
- Unable to find any JVMs matching version "(null)"
- No Java runtime present, try --request to install.
The entity type 'DisplayFormatAttribute' requires a primary key to be defined.
In my case I figured out the problem was that I used properties like this:
public string LastName { get; set; } //OK
public string Address { get; set; } //OK
public string State { get; set; } //OK
public int? Zip { get; set; } //OK
public EmailAddressAttribute Email { get; set; } // NOT OK
public PhoneAttribute PhoneNumber { get; set; } // NOT OK
Not sure if there is a better way to solve it but I changed the Email and PhoneNumber attribute to a string. Problem solved.
First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.
But in your server you're missing ext-dom
. php-xml
has all the related packages you need. So, you can simply install it by running:
sudo apt-get update
sudo apt install php-xml
Most likely you are missing mbstring
too. If you get the error, install this package as well with:
sudo apt-get install php-mbstring
Then run:
composer update
composer require cviebrock/eloquent-sluggable
We have found that AutoGenerateBindingRedirects
might be causing this issue.
Observed: the same project targeting net45
and netstandard1.5
was successfully built on one machine and failed to build on the other. Machines had different versions of the framework installed (4.6.1 - success and 4.7.1 - failure). After upgrading framework on the first machine to 4.7.1 the build also failed.
Error Message:
System.IO.FileNotFoundException : Could not load file or assembly 'System.Runtime, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
----> System.IO.FileNotFoundException : Could not load file or assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
Auto binding redirects
is a feature of .net 4.5.1
. Whenever nuget detects that the project is transitively referencing different versions of the same assembly it will automatically generate the config file in the output directory redirecting all the versions to the highest required version.
In our case it was rebinding all versions of System.Runtime
to Version=4.1.0.0
. .net 4.7.1
ships with a 4.3.0.0
version of runtime. So redirect binding was mapping to a version that was not available in a contemporary version of framework.
The problem was fixed with disabling auto binding redirects for 4.5 target and leaving it for .net core only.
<PropertyGroup Condition="'$(TargetFramework)' == 'net45'">
<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>
</PropertyGroup>
For me, these steps worked in Ubuntu with PHP 7.3:
1. vi /etc/php/7.3/apache2/php.ini > uncomment:
;extension=pdo_sqlite
;extension=pdo_mysql
2. sudo apt-get install php7.3-sqlite3
3. sudo service apache2 restart
You can return FileResult with this methods:
1: Return FileStreamResult
[HttpGet("get-file-stream/{id}"]
public async Task<FileStreamResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var stream = await GetFileStreamById(id);
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = fileName
};
}
2: Return FileContentResult
[HttpGet("get-file-content/{id}"]
public async Task<FileContentResult> DownloadAsync(string id)
{
var fileName="myfileName.txt";
var mimeType="application/....";
var fileBytes = await GetFileBytesById(id);
return new FileContentResult(fileBytes, mimeType)
{
FileDownloadName = fileName
};
}
React Application: For me the issue was that after running npm install
had some errors.
I've went with the recommendation npm audit fix
. This operation broke my package.json
and package-lock.json
(changed version of packages and and structure of .json).
THE FIX WAS:
npm install
npm start
Hope this will be helpfull for someone.
Since unpaidMembers
is a dictionary it always returns two values when called with .items()
- (key, value). You may want to keep your data as a list of tuples [(name, email, lastname), (name, email, lastname)..]
.
There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.
import { useLocation } from 'react-router-dom';
const ExampleComponent: React.FC = () => {
const location = useLocation();
return (
<Router basename='/app'>
<main>
<AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
</main>
</Router>
);
}
Those settings has moved into the .csproj file.
By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package
tab.
Once saved those values can be found in MyProject.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
<Version>1.2.3.4</Version>
<Authors>Author 1</Authors>
<Company>Company XYZ</Company>
<Product>Product 2</Product>
<PackageId>MyApp</PackageId>
<AssemblyVersion>2.0.0.0</AssemblyVersion>
<FileVersion>3.0.0.0</FileVersion>
<NeutralLanguage>en</NeutralLanguage>
<Description>Description here</Description>
<Copyright>Copyright</Copyright>
<PackageLicenseUrl>License URL</PackageLicenseUrl>
<PackageProjectUrl>Project URL</PackageProjectUrl>
<PackageIconUrl>Icon URL</PackageIconUrl>
<RepositoryUrl>Repo URL</RepositoryUrl>
<RepositoryType>Repo type</RepositoryType>
<PackageTags>Tags</PackageTags>
<PackageReleaseNotes>Release</PackageReleaseNotes>
</PropertyGroup>
In the file explorer properties information tab, FileVersion
is shown as "File Version" and Version
is shown as "Product version"
That happened once to me: I had a perfectly working Postman configuration, but then, without changing anything, even though I didn't inform the Content-Type
manually on Postman, it stopped working; following the answers to this question, I tried both disabling the header and letting Postman add it automatically, but neither options worked.
I ended up solving it by going to the Body
tab, change the param type from File
to Text
, then back to File
and then re-selecting the file to send; somehow, this made it work again. Smells like a Postman bug, in that specific case, maybe?
Local fonts linking to your react js may be a failure. So, I prefer to use online css file from google to link fonts. Refer the following code,
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
or
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto');
</style>
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
To update Angular CLI to a new version, you must update both the global package and your project's local package.
Global package:
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli@latest
Local project package:
rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install
See the reference https://github.com/angular/angular-cli
I had similar issues when migrating to androidx. this issue comes due to the Old Butter Knife library dependency.
if you are using butter knife then you should use at least butter knife version 9.0.0-SNAPSHOT or above.
implementation 'com.jakewharton:butterknife:9.0.0-SNAPSHOT'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-SNAPSHOT'
For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.
Example python implementation:
import sys
inner_loop = 0
def collatz_sequence(N, cache):
global inner_loop
l = [ ]
stop = False
n = N
tails = [ ]
while not stop:
inner_loop += 1
tmp = n
l.append(n)
if n <= 1:
stop = True
elif n in cache:
stop = True
elif n % 2:
n = 3*n + 1
else:
n = n // 2
tails.append((tmp, len(l)))
for key, offset in tails:
if not key in cache:
cache[key] = l[offset:]
return l
def gen_sequence(l, cache):
for elem in l:
yield elem
if elem in cache:
yield from gen_sequence(cache[elem], cache)
raise StopIteration
if __name__ == "__main__":
le_cache = {}
for n in range(1, 4711, 5):
l = collatz_sequence(n, le_cache)
print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))
print("inner_loop = {}".format(inner_loop))
Try adding the following dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
To fully answer this question in 2020, let me quote several statements from official Python docs:
Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Changed in version 3.8: Dictionaries are now reversible.
Dictionaries and dictionary views are reversible.
A statement regarding OrderedDict vs Dict:
Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).
If you run it, it will work, but in order for SQL Developer to recognize and not warn about a possible error you can change it as:
ALTER TABLE TEST_PROJECT2 MODIFY (proj_name VARCHAR2(300));
<input [ngModel]="item.value | useMyPipeToFormatThatValue"
(ngModelChange)="item.value=$event" name="inputField" type="text" />
The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)]
actually encompasses. []
is one-way binding syntax and ()
is event binding syntax. When used together - [()]
Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.
The reason you cannot use [()]
with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.
See Angular Template Syntax for more info.
For Windows : Uncomment this line in your php.ini file
;extension=php_gd2.dll
If the above step doesn't work uncomment the following line as well:
;extension=gd2
Using the Options pattern in ASP.NET Core is the way to go. I just want to add, if you need to access the options within your startup.cs, I recommend to do it this way:
CosmosDbOptions.cs:
public class CosmosDbOptions
{
public string ConnectionString { get; set; }
}
Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// This is how you can access the Connection String:
var connectionString = Configuration.GetSection(nameof(CosmosDbOptions))[nameof(CosmosDbOptions.ConnectionString)];
}
I was missing the attribute:
[assembly: OwinStartupAttribute(typeof(projectname.Startup))]
Which specifies the startup class. More details: https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection
I needed to pass both: a file and an integer. I did it this way:
needed to pass a file to upload: did it as per Sumit's answer.
Request type : POST
Body -> form-data
under the heading KEY, entered the name of the variable ('file' in my backend code).
in the backend:
file = request.files['file']
Next to 'file', there's a drop-down box which allows you to choose between 'File' or 'Text'. Chose 'File' and under the heading VALUE, 'Select files' appeared. Clicked on this which opened a window to select the file.
2. needed to pass an integer:
went to:
Params
entered variable name (e.g.: id) under KEY and its value (e.g.: 1) under VALUE
in the backend:
id = request.args.get('id')
Worked!
you can, however, do something like this :
<div onclick="return function()
{console.log('yaay, another onclick event!')}()"
@click="defaultFunction"></div>
yes, by using native onclick html event.
I've experienced similar problems with my ASP.NET Core projects. What happens is that the .config file in the bin/debug-folder is generated with this:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="6.0.0.0" newVersion="9.0.0.0" />
<bindingRedirect oldVersion="10.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
If I manually change the second bindingRedirect to this it works:
<bindingRedirect oldVersion="9.0.0.0" newVersion="10.0.0.0" />
Not sure why this happens.
I'm using Visual Studio 2015 with .Net Core SDK 1.0.0-preview2-1-003177.
The above bind-redirect did not work for me so I commented out the reference to System.Net.Http
in web.config
. Everything seems to work OK without it.
<system.web>
<compilation debug="true" targetFramework="4.7.2">
<assemblies>
<!--<add assembly="System.Net.Http, Version=4.2.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />-->
<add assembly="System.ComponentModel.Composition, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<customErrors mode="Off" />
<httpRuntime targetFramework="4.7.2" />
</system.web>
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
The error message says your DbContext
(LogManagerContext
) needs a constructor which accepts a DbContextOptions
. But i couldn't find such a constructor in your DbContext
. So adding below constructor probably solves your problem.
public LogManagerContext(DbContextOptions options) : base(options)
{
}
Edit for comment
If you don't register IHttpContextAccessor
explicitly, use below code:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
Your can send notification to all devices using "/topics/all"
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/all",
"notification":{ "title":"Notification title", "body":"Notification body", "sound":"default", "click_action":"FCM_PLUGIN_ACTIVITY", "icon":"fcm_push_icon" },
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
You can specify the latest version of ruby by looking at https://www.ruby-lang.org/en/downloads/
Fetch the latest version:
curl -sSL https://get.rvm.io | bash -s stable --ruby
Install it:
rvm install 2.2
Use it as default:
rvm use 2.2 --default
Or run the latest command from ruby:
rvm install ruby --latest
rvm use 2.2 --default
In the first plate you have to check that:
http://downloads.i-theses.com/index.php?option=com_downloads&task=downloads&groupid=9&id=101
(for example)crystaldecisions.reportappserver.commlayer.dll
Try this. Why are you using RegistrationIntentService
?
public class FirebaseInstanceIDService extends FirebaseInstanceIdService {
@Override
public void onTokenRefresh() {
String token = FirebaseInstanceId.getInstance().getToken();
registerToken(token);
}
private void registerToken(String token) {
}
}
Here is a clear-cut answer from the docs regarding this:
delete intermediates folder from app\build\intermediates. then rebuild the project. it will work
As you add more modules to Android, there is an incredible demand placed on the Android build system, and the default memory settings will not work. To avoid OutOfMemory
errors during Android builds, you should uncomment the alternate Gradle memory setting present in /android/gradle.properties
:
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
I found some issue about that kind of error
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
# Connection url for the database please let me know "[email protected]"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc
# Username and secret
spring.datasource.username = root
spring.datasource.password =
# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# ===============================
# = JPA / HIBERNATE
# ===============================
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
Issue no 2.
Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine
I had this issue(app doesn't want to open on notification click if app is in background or closed), and the problem was an invalid click_action
in notification body, try removing or changing it to something valid.
I had the same problem and it is solved by defining enabled, exported to true in my service
<service
android:name=".MyFirebaseMessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
if your app is in background the notification icon will be set onMessage Receive method but if you app is in foreground the notification icon will be the one you defined on manifest
One of the reason can be that it is not able to detect the pom.xml(or gradle file) and thats why not able to set it as a maven project(or gradle).
You can manually set it up as a maven(or gradle) project by selecting your pom.xml(or gradle file)
When using spark-submit with --master yarn-cluster, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. URLs supplied after --jars must be separated by commas. That list is included in the driver and executor classpaths
Example :
spark-submit --master yarn-cluster --jars ../lib/misc.jar, ../lib/test.jar --class MainClass MainApp.jar
https://spark.apache.org/docs/latest/submitting-applications.html
Your error message is pretty explicit about what is going wrong:
laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
Do you have mbstring
installed on your server and is it enabled?
You can install mbstring
as part of the libapache2-mod-php5 package:
sudo apt-get install libapache2-mod-php5
Or standalone with:
sudo apt-get install php-mbstring
Installing it will also enable it, however you can also enable it by editing your php.ini
file and remove the ;
that is commenting it out if it is already installed.
If this is on your local machine, then follow the appropriate steps to install this on your environment.
In android/app/build.gradle
android {
compileSdkVersion 23
buildToolsVersion '23.0.0'
defaultConfig {
applicationId "com.dkm.example"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
multiDexEnabled true
}
multiDexEnabled true
it works for me
Error 127
means one of two things:
$PATH
, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.file -L
on /bin/sh
(to get your default/native format) and on the compiler itself (to see what format it is).if the problem is (2), then you can solve it in a few diff ways:
You can play here with different types and check the output,
export class ParentCmp {
myVar:stirng="micronyks";
myVal:any;
myArray:Array[]=[1,2,3];
myArr:Array[];
constructor() {
if(this.myVar){
console.log('has value') // answer
}
else{
console.log('no value');
}
if(this.myVal){
console.log('has value')
}
else{
console.log('no value'); //answer
}
if(this.myArray){
console.log('has value') //answer
}
else{
console.log('no value');
}
if(this.myArr){
console.log('has value')
}
else{
console.log('no value'); //answer
}
}
}
Another possible reason
resConfigs "hdpi", "xhdpi", "xxhdpi", "xxxhdpi"
can be source of this issue
File -> Invalidate Caches & Restart...
Build -> Build signed APK -> check the path in the dialog
This worked for me: Uploading a file via Postman, to a SpringMVC backend webapp:
I know the question asks about macOS, but here is a solution for Linux users who arrive here via Google.
I was having the issue described in this question, having installed the pdfx package via pip.
When I ran it however, nothing...
pip list | grep pdfx
pdfx (1.3.0)
Yet:
which pdfx
pdfx not found
The problem on Linux is that pip install ...
drops scripts into ~/.local/bin
and this is not on the default Debian/Ubuntu $PATH
.
Here's a GitHub issue going into more detail: https://github.com/pypa/pip/issues/3813
To fix, just add ~/.local/bin
to your $PATH
, for example by adding the following line to your .bashrc
file:
export PATH="$HOME/.local/bin:$PATH"
After that, restart your shell and things should work as expected.
using Apache IO could be another option for copy the Stream
@RequestMapping(path = "/file/{fileId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> downloadFile(@PathVariable(value="fileId") String fileId,HttpServletResponse response) throws Exception {
InputStream yourInputStream = ...
IOUtils.copy(yourInputStream, response.getOutputStream());
response.flushBuffer();
return ResponseEntity.ok().build();
}
maven dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
For Alpine (in docker), you can use apk add php7-simplexml
.
If that doesn't work for you, you can run apk add --no-cache php7-simplexml
. This is in case you aren't updating the package index first.
I actually had a similar issue, where we had to many trusted root certificates. Our fresh installed webserver had over a hunded. Our root started with the letter Z so it ended up at the end of the list.
The problem was that the IIS sent only the first twenty-something trusted roots to the client and truncated the rest, including ours. It was a few years ago, can't remember the name of the tool... it was part of the IIS admin suite, but Fiddler should do as well. After realizing the error, we removed a lot trusted roots that we don't need. This was done trial and error, so be careful what you delete.
After the cleanup everything worked like a charm.
I aso find this extremely confusing. as @EricMartinez points out Renderer2 listen() returns the function to remove the listener:
ƒ () { return element.removeEventListener(eventName, /** @type {?} */ (handler), false); }
If i´m adding a listener
this.listenToClick = this.renderer.listen('document', 'click', (evt) => {
alert('Clicking the document');
})
I´d expect my function to execute what i intended, not the total opposite which is remove the listener.
// I´d expect an alert('Clicking the document');
this.listenToClick();
// what you actually get is removing the listener, so nothing...
In the given scenario, It´d actually make to more sense to name it like:
// Add listeners
let unlistenGlobal = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let removeSimple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
There must be a good reason for this but in my opinion it´s very misleading and not intuitive.
The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:
[A]
JObject
isn't the elementary base type of everything in JSON.net, butJToken
is. So even though you could say,object i = new int[0];
in C#, you can't say,
JObject i = JObject.Parse("[0, 0, 0]");
in JSON.net.
What you want is JArray.Parse
, which will accept the array you're passing it (denoted by the opening [
in your API response). This is what the "StartArray" in the error message is telling you.
As for what happened when you used JArray
, you're using arr
instead of obj
:
var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);
Swap that, and I believe it should work.
Although I'd be tempted to deserialize arr
directly as an IEnumerable<LocationData>
, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.
1)check the package name is the same in google-services.json file
2)make sure that no other project exist with same package name
3)make sure that there is internet access
4)try syncing project and running it again
SOLVED
After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:
What's obviously missing there is the Content-Type
header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type
never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType
property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type
was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:
req.Method = "POST"
req.ContentType = "application/json"
lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
req.ContentLength = bytData.Length
reqStream = req.GetRequestStream()
reqStream.Write(bytData, 0, bytData.Length)
reqStream.Close()
'// Content-Type was being set here, causing the problem
'req.ContentType = "application/json"
That's all it was, the ContentType
property just needed to be set prior to writing to the request body
I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.
You can run this command in your project directory. Basically it just cleans the build and gradle.
cd android && rm -R .gradle && cd app && rm -R build
In my case, I was using react-native using this as a script in package.json
"scripts": { "clean-android": "cd android && rm -R .gradle && cd app && rm -R build" }
Just clean and retry solved for me.
Import jquery (I installed with 'npm install [email protected]')
import 'jquery/jquery.js';
Put all your code that depends on jquery inside this method
+function ($) {
// your code
}(window.jQuery);
or declare variable $ after import
var $ = window.$
in "rules", "no-console": [false, "log", "error"]
I also encountered this situation when I was trying to train a KNN classifier. but it seems that the warning was gone after I changed:
knn.fit(X_train,y_train)
to
knn.fit(X_train, np.ravel(y_train,order='C'))
Ahead of this line I used import numpy as np
.
./gradlew clean
Uses your project's gradle wrapper to execute your project's clean
task. Usually, this just means the deletion of the build directory.
./gradlew clean assembleDebug
Again, uses your project's gradle wrapper to execute the clean
and assembleDebug
tasks, respectively. So, it will clean first, then execute assembleDebug
, after any non-up-to-date dependent tasks.
./gradlew clean :assembleDebug
Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.
Android Studio --> Build --> Clean
Is essentially the same as ./gradlew clean
. See here.
For more info, I suggest taking the time to read through the Android docs, especially this one.
On Arch Linux what did the trick for me was:
sudo pacman -Rs npm
sudo pacman -S npm
I just had to delete and reinstall my google-services.json
and then restart Android Studio.
Even when considering all answers above you might still run into issues that will terminate your maven offline build with an error. Especially, you may experience a warning as follwos:
[WARNING] The POM for org.apache.maven.plugins:maven-resources-plugin:jar:2.6 is missing, no dependency information available
The warning will be immediately followed by further errors and maven will terminate.
For us the safest way to build offline with a maven offline cache created following the hints above is to use following maven offline parameters:
mvn -o -llr -Dmaven.repo.local=<path_to_your_offline_cache> ...
Especially, option -llr prevents you from having to tune your local cache as proposed in answer #4.
Also take care that that the localRepository parameter in settings.xml is set as follows:
<localRepository>${user.home}/.m2/repository</localRepository>
It's not an array of arrays. It's an observable of observable(s).
The following returns an observable stream of string.
requestStream
.map(function(requestUrl) {
return requestUrl;
});
While this returns an observable stream of observable stream of json
requestStream
.map(function(requestUrl) {
return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
});
flatMap
flattens the observable automatically for us so we can observe the json stream directly
If cleaning the solution didn't work and for anybody who see's this question and tried moving a project or renaming.
Open Package manager console and type "dotnet restore".
Hmmm you can find lot of examples for configuring spring framework. Anyways here is a sample
@Configuration
@Import({PersistenceConfig.class})
@ComponentScan(basePackageClasses = {
ServiceMarker.class,
RepositoryMarker.class }
)
public class AppConfig {
}
@Configuration
@PropertySource(value = { "classpath:database/jdbc.properties" })
@EnableTransactionManagement
public class PersistenceConfig {
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH = "hibernate.max_fetch_depth";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE = "hibernate.jdbc.fetch_size";
private static final String PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE = "hibernate.jdbc.batch_size";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String[] ENTITYMANAGER_PACKAGES_TO_SCAN = {"a.b.c.entities", "a.b.c.converters"};
@Autowired
private Environment env;
@Bean(destroyMethod = "close")
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return transactionManager;
}
private HibernateJpaVendorAdapter vendorAdaptor() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setShowSql(true);
return vendorAdapter;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdaptor());
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(ENTITYMANAGER_PACKAGES_TO_SCAN);
entityManagerFactoryBean.setJpaProperties(jpaHibernateProperties());
return entityManagerFactoryBean;
}
private Properties jpaHibernateProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH, env.getProperty(PROPERTY_NAME_HIBERNATE_MAX_FETCH_DEPTH));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_FETCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE, env.getProperty(PROPERTY_NAME_HIBERNATE_JDBC_BATCH_SIZE));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(AvailableSettings.SCHEMA_GEN_DATABASE_ACTION, "none");
properties.put(AvailableSettings.USE_CLASS_ENHANCER, "false");
return properties;
}
}
public static void main(String[] args) {
try (GenericApplicationContext springContext = new AnnotationConfigApplicationContext(AppConfig.class)) {
MyService myService = springContext.getBean(MyServiceImpl.class);
try {
myService.handleProcess(fromDate, toDate);
} catch (Exception e) {
logger.error("Exception occurs", e);
myService.handleException(fromDate, toDate, e);
}
} catch (Exception e) {
logger.error("Exception occurs in loading Spring context: ", e);
}
}
@Service
public class MyServiceImpl implements MyService {
@Inject
private MyDao myDao;
@Override
public void handleProcess(String fromDate, String toDate) {
List<Student> myList = myDao.select(fromDate, toDate);
}
}
@Repository
@Transactional
public class MyDaoImpl implements MyDao {
@PersistenceContext
private EntityManager entityManager;
public Student select(String fromDate, String toDate){
TypedQuery<Student> query = entityManager.createNamedQuery("Student.findByKey", Student.class);
query.setParameter("fromDate", fromDate);
query.setParameter("toDate", toDate);
List<Student> list = query.getResultList();
return CollectionUtils.isEmpty(list) ? null : list;
}
}
Assuming maven project:
Properties file should be in src/main/resources/database
folder
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=your db url
jdbc.username=your Username
jdbc.password=Your password
hibernate.max_fetch_depth = 3
hibernate.jdbc.fetch_size = 50
hibernate.jdbc.batch_size = 10
hibernate.show_sql = true
ServiceMarker and RepositoryMarker are just empty interfaces in your service or repository impl package.
Let's say you have package name a.b.c.service.impl
. MyServiceImpl is in this package and so is ServiceMarker.
public interface ServiceMarker {
}
Same for repository marker. Let's say you have a.b.c.repository.impl
or a.b.c.dao.impl
package name. Then MyDaoImpl is in this this package and also Repositorymarker
public interface RepositoryMarker {
}
//dummy class and dummy query
@Entity
@NamedQueries({
@NamedQuery(name="Student.findByKey", query="select s from Student s where s.fromDate=:fromDate" and s.toDate = :toDate)
})
public class Student implements Serializable {
private LocalDateTime fromDate;
private LocalDateTime toDate;
//getters setters
}
@Converter(autoApply = true)
public class LocalDateTimeConverter implements AttributeConverter<LocalDateTime, Timestamp> {
@Override
public Timestamp convertToDatabaseColumn(LocalDateTime dateTime) {
if (dateTime == null) {
return null;
}
return Timestamp.valueOf(dateTime);
}
@Override
public LocalDateTime convertToEntityAttribute(Timestamp timestamp) {
if (timestamp == null) {
return null;
}
return timestamp.toLocalDateTime();
}
}
<properties>
<java-version>1.8</java-version>
<org.springframework-version>4.2.1.RELEASE</org.springframework-version>
<hibernate-entitymanager.version>5.0.2.Final</hibernate-entitymanager.version>
<commons-dbcp2.version>2.1.1</commons-dbcp2.version>
<mysql-connector-java.version>5.1.36</mysql-connector-java.version>
<junit.version>4.12</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${hibernate-entitymanager.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector-java.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>${commons-dbcp2.version}</version>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
</plugins>
</build>
Hope it helps. Thanks
In case you have to deal with the arguably unfriendly logs
client (CloudWatch Logs put-log-events
), this is what I had to do to properly catch Boto3 client exceptions:
try:
### Boto3 client code here...
except boto_exceptions.ClientError as error:
Log.warning("Catched client error code %s",
error.response['Error']['Code'])
if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
"InvalidSequenceTokenException"]:
Log.debug(
"Fetching sequence_token from boto error response['Error']['Message'] %s",
error.response["Error"]["Message"])
# NOTE: apparently there's no sequenceToken attribute in the response so we have
# to parse response["Error"]["Message"] string
sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
Log.debug("Setting sequence_token to %s", sequence_token)
This works both at first attempt (with empty LogStream) and subsequent ones.
I have just been playing around a little bit with this concept. Basically, if you are ok with potentially having a pixel or so cut off from your last character, here is a pure css and html solution:
The way this works is by absolutely positioning a div below the viewable region of a viewport. We want the div to offset up into the visible region as our content grows. If the content grows too much, our div will offset too high, so upper bound the height our content can grow.
HTML:
<div class="text-container">
<span class="text-content">
PUT YOUR TEXT HERE
<div class="ellipsis">...</div> // You could even make this a pseudo-element
</span>
</div>
CSS:
.text-container {
position: relative;
display: block;
color: #838485;
width: 24em;
height: calc(2em + 5px); // This is the max height you want to show of the text. A little extra space is for characters that extend below the line like 'j'
overflow: hidden;
white-space: normal;
}
.text-content {
word-break: break-all;
position: relative;
display: block;
max-height: 3em; // This prevents the ellipsis element from being offset too much. It should be 1 line height greater than the viewport
}
.ellipsis {
position: absolute;
right: 0;
top: calc(4em + 2px - 100%); // Offset grows inversely with content height. Initially extends below the viewport, as content grows it offsets up, and reaches a maximum due to max-height of the content
text-align: left;
background: white;
}
I have tested this in Chrome, FF, Safari, and IE 11.
You can check it out here: http://codepen.io/puopg/pen/vKWJwK
You might even be able to alleviate the abrupt cut off of the character with some CSS magic.
EDIT: I guess one thing that this imposes is word-break: break-all since otherwise the content would not extend to the very end of the viewport. :(
In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.
If you have issues with the xcode-select --install
command; e.g. I kept getting a network problem timeout, then try downloading the dmg at developer.apple.com/downloads (Command line tools OS X 10.11) for Xcode 7.1
Per a comment by Daniel Neel above :
version 1.0.3 of the Microsoft.CodeDom.Providers.DotNetCompilerPlatform Nuget package works for me, but version 1.0.6 causes the error in this question
Downgrading to 1.0.3 resolved this issue for me.
Just to show java 8's stance to remove null values.
String s = Optional.ofNullable(myString).orElse("");
if (s.trim().isEmpty()) {
...
}
Makes sense if you can use Optional<String>
.
This is simple way to convert files to Base64 and avoid "maximum call stack size exceeded at FileReader.reader.onload" with the file has big size.
document.querySelector('#fileInput').addEventListener('change', function () {_x000D_
_x000D_
var reader = new FileReader();_x000D_
var selectedFile = this.files[0];_x000D_
_x000D_
reader.onload = function () {_x000D_
var comma = this.result.indexOf(',');_x000D_
var base64 = this.result.substr(comma + 1);_x000D_
console.log(base64);_x000D_
}_x000D_
reader.readAsDataURL(selectedFile);_x000D_
}, false);
_x000D_
<input id="fileInput" type="file" />
_x000D_
sudo apt-get install php-mbstring
# if your are using php 7.1
sudo apt-get install php7.1-mbstring
# if your are using php 7.2
sudo apt-get install php7.2-mbstring
In my case I've had more then 5000 items in the list. My problem was that when scrolling the recycler view, sometimes the "onBindViewHolder" get called while "myCustomAddItems" method is altering the list.
My solution was to add "synchronized (syncObject){}" to all the methods that alter the data list. This way at any point at time only one method can read this list.
This is the best solution IMHO. It covers BOTH null
and empty
scenario, as is easy to understand when reading the code. All you need to know is that .getProperty
returns a null
when system prop is not set:
String DEFAULT_XYZ = System.getProperty("user.home") + "/xyz";
String PROP = Optional.ofNullable(System.getProperty("XYZ"))
.filter(s -> !s.isEmpty())
.orElse(DEFAULT_XYZ);
In case of simple example if your api is below
@POST
@Path("update_accounts")
@Consumes(MediaType.APPLICATION_JSON)
@PermissionRequired(Permissions.UPDATE_ACCOUNTS)
void createLimit(List<AccountUpdateRequest> requestList) throws RuntimeException;
where AccountUpdateRequest :
public class AccountUpdateRequest {
private Long accountId;
private AccountType accountType;
private BigDecimal amount;
...
}
then your postman request would be: http://localhost:port/update_accounts
[
{
"accountType": "LEDGER",
"accountId": 11111,
"amount": 100
},
{
"accountType": "LEDGER",
"accountId": 2222,
"amount": 300
},
{
"accountType": "LEDGER",
"accountId": 3333,
"amount": 1000
}
]
The best way to align a div in center both horizontally and vertically will be
HTML
<div></div>
CSS:
div {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 100px;
height: 100px;
background-color: blue;
}
For Windows Platform:
try Running the 64 Bit exe version of IntelliJ from a path similar to following.
note that it is available beside the default idea.exe
"C:\Program Files (x86)\JetBrains\IntelliJ IDEA 15.0\bin\idea64.exe"
I was getting this error after deploying on IIS Server PC.
https://www.microsoft.com/en-us/download/details.aspx?id=42295enter link description here
https://www.microsoft.com/en-us/download/details.aspx?id=45496
It may require restart your computer.
Using NewRequest
just to create an URL is an overkill. Use the net/url
package:
package main
import (
"fmt"
"net/url"
)
func main() {
base, err := url.Parse("http://www.example.com")
if err != nil {
return
}
// Path params
base.Path += "this will get automatically encoded"
// Query params
params := url.Values{}
params.Add("q", "this will get encoded as well")
base.RawQuery = params.Encode()
fmt.Printf("Encoded URL is %q\n", base.String())
}
Playground: https://play.golang.org/p/YCTvdluws-r
The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.
$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString
This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))
If the info does not need to be secure at all you can convert it to plain text:
$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically. https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0
run sudo npm install ngrok --g a very simple way to install
sudo because you are installing it globally
@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
View decor = getWindow().getDecorView();
if (shouldChangeStatusBarTintToDark) {
decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
} else {
// We want to change tint color to white again.
// You can also record the flags in advance so that you can turn UI back completely if
// you have set other flags before, such as translucent or full screen.
decor.setSystemUiVisibility(0);
}
}
A. After updating the .env file with database settings, clear larval setting by "running php artisan config:clear"
B. Please make sure you restart your apache server / rerun the "php artisan serve" command for your settings to take effect.
Replace
if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged
with
if (obj === undefined) { return undefined;} // return undefined for undefined
if (obj === null) { return null;} // null unchanged
From my HomeController I want to call this Method and convert Json response to List
No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!
Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
If you don't want that and you're absolutely sure you need to return HttpResponseMessage
, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject()
yourself:
return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);
Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:
public class FileListGetter
{
public IEnumerable<QDocumentRecord> GetAllRecords()
{
listOfFiles = ...
return listOfFiles;
}
}
Either way, then you can call this class or the ApiController directly from your MVC controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var listOfFiles = new DocumentsController().GetAllRecords();
// OR
var listOfFiles = new FileListGetter().GetAllRecords();
return View(listOfFiles);
}
}
But if you really, really must do an HTTP request, you can use HttpWebRequest
, WebClient
, HttpClient
or RestSharp
, for all of which plenty of tutorials exist.
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
Apart from price and features, the throughput also varies greatly (as mentioned by user1677120):
Taken from EBS docs:
| EBS volume | Throughput | Throughput |
| type | MiB/s | dependent on.. |
|------------|------------|-------------------------------|
| gp2 (SSD) | 128-160 | volume size |
| io1 (SSD) | 0.25-500 | IOPS (256Kib/s per IOPS) |
| st1 (HDD) | 20-500 | volume size (40Mib/s per TiB) |
| sc1 (HDD) | 6-250 | volume size (12Mib/s per TiB) |
Note, that for io1, st1 and sc1 you can burst throughput traffic to at least 125Mib/s, but to 500Mib/s, depending on volume size.
You can further increase throughput by e.g. deploying EBS volumes as RAID0
Taken from EFS docs
| Filesystem | Base | Burst |
| Size | Throughput | Throughput |
| GiB | MiB/s | MiB/s |
|------------|------------|------------|
| 10 | 0.5 | 100 |
| 256 | 12.5 | 100 |
| 512 | 25.0 | 100 |
| 1024 | 50.0 | 100 |
| 1536 | 75.0 | 150 |
| 2048 | 100.0 | 200 |
| 3072 | 150.0 | 300 |
| 4096 | 200.0 | 400 |
The base throughput is guaranteed, burst throughput uses up credits you gathered while being below the base throughput (so you'll only have this for a limited time, see here for more details.
S3 is a total different thing, so it cannot really be compared to EBS and EFS. Plus: There are no published throughput metrics for S3. You can improve throughput by downloading in parallel (I somewhere read AWS states you would have basically unlimited throughput this way), or adding CloudFront to the mix
The solution in my case was just to install the NUnit 3 Test Adapter extension to my Visual Studio 2015.
You can use Toolbar inside the fragment and it is easy to handle. First add Toolbar to layout of the fragment
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:minHeight="?attr/actionBarSize"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="?attr/colorPrimaryDark">
</android.support.v7.widget.Toolbar>
Inside the onCreateView Method in the fragment you can handle the toolbar like this.
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle("Title");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
IT will set the toolbar,title and the back arrow navigation to toolbar.You can set any icon to setNavigationIcon method.
If you need to trigger any event when click toolbar navigation icon you can use this.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//handle any click event
});
If your activity have navigation drawer you may need to open that when click the navigation back button. you can open that drawer like this.
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
drawer.openDrawer(Gravity.START);
}
});
Full code is here
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//inflate the layout to the fragement
view = inflater.inflate(R.layout.layout_user,container,false);
//initialize the toolbar
Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.setTitle("Title");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//open navigation drawer when click navigation back button
DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
drawer.openDrawer(Gravity.START);
}
});
return view;
}
Command to remove Cordova and ionic
For Window system
For Mac system
For install cordova and ionic
eg.
sudo npm install -g [email protected]
sudo npm install -g [email protected]
You should do something like this:
if !(string?.isEmpty ?? true) { //Not nil nor empty }
Nil coalescing operator checks if the optional is not nil, in case it is not nil it then checks its property, in this case isEmpty. Because this optional can be nil you provide a default value which will be used when your optional is nil.
I got this error(classNotFoundException for main class), I actually changed pom version , so did maven install again and then error vanished.
It's HTML character references for encoding a character by its decimal code point
Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe
if you are using properties file you can add following line there:
spark.jars=jars/your_jar1.jar,...
assuming that
<your root from where you run spark-submit>
|
|-jars
|-your_jar1.jar
Let assume i am having a RestController
with GET/POST/PUT/DELETE
operations and i have to write unit test using spring boot.I will just share code of RestController class and respective unit test.Wont be sharing any other related code to the controller ,can have assumption on that.
@RestController
@RequestMapping(value = “/myapi/myApp” , produces = {"application/json"})
public class AppController {
@Autowired
private AppService service;
@GetMapping
public MyAppResponse<AppEntity> get() throws Exception {
MyAppResponse<AppEntity> response = new MyAppResponse<AppEntity>();
service.getApp().stream().forEach(x -> response.addData(x));
return response;
}
@PostMapping
public ResponseEntity<HttpStatus> create(@RequestBody AppRequest request) throws Exception {
//Validation code
service.createApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@PutMapping
public ResponseEntity<HttpStatus> update(@RequestBody IDMSRequest request) throws Exception {
//Validation code
service.updateApp(request);
return ResponseEntity.ok(HttpStatus.OK);
}
@DeleteMapping
public ResponseEntity<HttpStatus> delete(@RequestBody AppRequest request) throws Exception {
//Validation
service.deleteApp(request.id);
return ResponseEntity.ok(HttpStatus.OK);
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Main.class)
@WebAppConfiguration
public abstract class BaseTest {
protected MockMvc mvc;
@Autowired
WebApplicationContext webApplicationContext;
protected void setUp() {
mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
protected String mapToJson(Object obj) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(obj);
}
protected <T> T mapFromJson(String json, Class<T> clazz)
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, clazz);
}
}
public class AppControllerTest extends BaseTest {
@MockBean
private IIdmsService service;
private static final String URI = "/myapi/myApp";
@Override
@Before
public void setUp() {
super.setUp();
}
@Test
public void testGet() throws Exception {
AppEntity entity = new AppEntity();
List<AppEntity> dataList = new ArrayList<AppEntity>();
AppResponse<AppEntity> dataResponse = new AppResponse<AppEntity>();
entity.setId(1);
entity.setCreated_at("2020-02-21 17:01:38.717863");
entity.setCreated_by(“Abhinav Kr”);
entity.setModified_at("2020-02-24 17:01:38.717863");
entity.setModified_by(“Jyoti”);
dataList.add(entity);
dataResponse.setData(dataList);
Mockito.when(service.getApp()).thenReturn(dataList);
RequestBuilder requestBuilder = MockMvcRequestBuilders.get(URI)
.accept(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
String expectedJson = this.mapToJson(dataResponse);
String outputInJson = mvcResult.getResponse().getContentAsString();
assertEquals(HttpStatus.OK.value(), response.getStatus());
assertEquals(expectedJson, outputInJson);
}
@Test
public void testCreate() throws Exception {
AppRequest request = new AppRequest();
request.createdBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “India”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).createApp(Mockito.any(AppRequest.class));
service.createApp(request);
Mockito.verify(service, Mockito.times(1)).createApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testUpdate() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
request.modifiedBy = 1;
request.AppFullName = “My App”;
request.appTimezone = “Bharat”;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).updateApp(Mockito.any(AppRequest.class));
service.updateApp(request);
Mockito.verify(service, Mockito.times(1)).updateApp(request);
RequestBuilder requestBuilder = MockMvcRequestBuilders.put(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
@Test
public void testDelete() throws Exception {
AppRequest request = new AppRequest();
request.id = 1;
String inputInJson = this.mapToJson(request);
Mockito.doNothing().when(service).deleteApp(Mockito.any(Integer.class));
service.deleteApp(request.id);
Mockito.verify(service, Mockito.times(1)).deleteApp(request.id);
RequestBuilder requestBuilder = MockMvcRequestBuilders.delete(URI)
.accept(MediaType.APPLICATION_JSON).content(inputInJson)
.contentType(MediaType.APPLICATION_JSON);
MvcResult mvcResult = mvc.perform(requestBuilder).andReturn();
MockHttpServletResponse response = mvcResult.getResponse();
assertEquals(HttpStatus.OK.value(), response.getStatus());
}
}
Experimental I found way:
App extends Application not MultiDexApplication
and remove
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
from gradle.properties
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
The packages you installed introduced dependencies to version 5.2.3.0 dll's as user Bracher showed above. Microsoft.AspNet.WebApi.Cors is an example package. The path I take is to update the MVC project proir to any package installs:
Install-Package Microsoft.AspNet.Mvc -Version 5.2.3
@mayabelle you can create IHttpActionResult concrete and wrapped those code like this:
public class NotFoundPlainTextActionResult : IHttpActionResult
{
public NotFoundPlainTextActionResult(HttpRequestMessage request, string message)
{
Request = request;
Message = message;
}
public string Message { get; private set; }
public HttpRequestMessage Request { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
return Task.FromResult(ExecuteResult());
}
public HttpResponseMessage ExecuteResult()
{
var response = new HttpResponseMessage();
if (!string.IsNullOrWhiteSpace(Message))
//response.Content = new StringContent(Message);
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception(Message));
response.RequestMessage = Request;
return response;
}
}
System.ArgumentNullException: Value cannot be null. Parameter name: value
This error message is not very helpful!
You can get this error in many different ways. The error may not always be with the parameter name: value. It could be whatever parameter name is being passed into a function.
As a generic way to solve this, look at the stack trace or call stack:
Test method GetApiModel threw exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: value
at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
You can see that the parameter name value
is the first parameter for DeserializeObject
. This lead me to check my AutoMapper mapping where we are deserializing a JSON string. That string is null in my database.
You can change the code to check for null.
The above answers missing a way to find the realm file in Android platform and believe me this way will save your lot's of time which we generally waste in other approaches to get the realm file. So let's start...
First open "Device File Explorer" in android studio(View -> Tools Windows -> Device File Explorer.
This will open your device explorer.
now open data -> data -> (your_app_package_name) -> files -> default.realm
default.realm is the file for which we are here. Now Save_as this file at your location and access the file from the realm_browser and you will get your database.
NOTE: Mentioned approach is tested on non-rooted phone(one+3).
namespace TestCSharp2
{
**public** class Class2
{
int i;
public void setValue(int i)
{
this.i = i;
}
public int getValue()
{
return this.i;
}
}
}
Add the 'Public' declaration before 'class Class2'.
Os X Mojave 10.14 has:
Error: The Command Line Tools header package must be installed on Mojave.
Solution. Go to
/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg
location and install the package manually. And brew will start working and we can run:
brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git
"most convenient block of data" probably refers to the width (in bits) of the WORD, in correspondance to the system bus width, or whatever underlying "bandwidth" is available. On a 16 bit system, with WORD being defined as 16 bits wide, moving data around in chunks the size of a WORD will be the most efficient way. (On hardware or "system" level.)
With Java being more or less platform independant, it just defines a "WORD" as the next size from a "BYTE", meaning "full bandwidth". I guess any platform that's able to run Java will use 32 bits for a WORD.
The most recent version of Sublime has fixed this issue, click on Preferences, click on Theme select Adaptive.sublime-theme. This will change the sidebar to a dark colored background.
it would be great if somebody told to put gif into any folder instead of assets folder
If you altered your $PATH variable that could also cause the problem. If you think that might be the issue, check your ~/.bash_profile or ~/.bashrc
Programmatically you can do it by adding the following constraints.
NSLayoutConstraint *constraintHorizontal = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.superview
attribute:attribute
multiplier:1.0f
constant:0.0f];
NSLayoutConstraint *constraintVertical = [NSLayoutConstraint constraintWithItem:self
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.superview
attribute:attribute
multiplier:1.0f
constant:0.0f];
I had same issue. I have tried many things but nothing worked Until I try following:
gradle-[version]-all
within C:\Users\<username>\.gradle\wrapper\dists\
. If you encounter a "File in use" error (or similar), terminate any running Java executables..gradle
directory.background: rgba(255,255,255,0.5);
backdrop-filter: blur(5px);
Instead of adding another blur background to your content, you can use backdrop-filter. FYI IE 11 and Firefox may not support it. Check caniuse.
Demo:
header {_x000D_
position: fixed;_x000D_
width: 100%;_x000D_
padding: 10px;_x000D_
background: rgba(255,255,255,0.5);_x000D_
backdrop-filter: blur(5px);_x000D_
}_x000D_
body {_x000D_
margin: 0;_x000D_
}
_x000D_
<header>_x000D_
Header_x000D_
</header>_x000D_
<div>_x000D_
<img src="https://dummyimage.com/600x400/000/fff" />_x000D_
<img src="https://dummyimage.com/600x400/000/fff" />_x000D_
<img src="https://dummyimage.com/600x400/000/fff" />_x000D_
</div>
_x000D_
Add json jar to your classpath
or use java -classpath json.jar ClassName
refer this
It also disturb me a lot but now it is fine The solution is very simple (written blow) [window (android studio)]
A cleaner alternative would be to use a Dictionary
to handle parameters. They are key-value pairs after all.
private static readonly HttpClient httpclient;
static MyClassName()
{
// HttpClient is intended to be instantiated once and re-used throughout the life of an application.
// Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.
// This will result in SocketException errors.
// https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
httpclient = new HttpClient();
}
var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);
var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
// Do something with response. Example get content:
// var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}
Also dont forget to Dispose()
httpclient, if you dont use the keyword using
As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.
Edit:
You may want to look into response.EnsureSuccessStatusCode();
instead of if (response.StatusCode == HttpStatusCode.OK)
.
You may want to keep your httpclient and dont Dispose()
it. See: Do HttpClient and HttpClientHandler have to be disposed?
Edit:
Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html
I am using Mac OS X 10.10 also. And to fix this problem.
Search and replace:
<key> JVM version</key>
<string>1.6*</string>
replaced by:
<key> JVM version</key>
<string>1.6+</string>
That's it!
Using a Windows 10 guest, after I performed steps 1 through 3 from @xinampc's answer, I had to open a new File Explorer and navigated to This PC > CD Drive (D:) VirtualBox Guest Additions to run VBoxWindowsAdditions. After I ran that and went through the command prompts, Windows rebooted and I was able to see VBOXSVR under Network.
TextUtils.isEmpty( someString )
String myString = null;
if (TextUtils.isEmpty(myString)) {
return; // or break, continue, throw
}
// myString is neither null nor empty if this point is reached
Log.i("TAG", myString);
Notes
$users = Get-ADGroupMember -Identity 'Client Services' -Recursive ; $users.count
The above one-liner gives a clean count of recursive members found. Simple, easy, and one line.
If your Controller extends ControllerBase
or Controller
you can use Content(...)
method:
[HttpGet]
public ContentResult Index()
{
return base.Content("<div>Hello</div>", "text/html");
}
If you choose not to extend from Controller
classes, you can create new ContentResult
:
[HttpGet]
public ContentResult Index()
{
return new ContentResult
{
ContentType = "text/html",
Content = "<div>Hello World</div>"
};
}
Return string content with media type text/html
:
public HttpResponseMessage Get()
{
var response = new HttpResponseMessage();
response.Content = new StringContent("<div>Hello World</div>");
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
return response;
}
If you can live with limited parallel capablilities, the following solution will work:
private static <T> Stream<T> nonEmptyStream(
Stream<T> stream, Supplier<RuntimeException> e) {
Spliterator<T> it=stream.spliterator();
return StreamSupport.stream(new Spliterator<T>() {
boolean seen;
public boolean tryAdvance(Consumer<? super T> action) {
boolean r=it.tryAdvance(action);
if(!seen && !r) throw e.get();
seen=true;
return r;
}
public Spliterator<T> trySplit() { return null; }
public long estimateSize() { return it.estimateSize(); }
public int characteristics() { return it.characteristics(); }
}, false);
}
Here is some example code using it:
List<String> l=Arrays.asList("hello", "world");
nonEmptyStream(l.stream(), ()->new RuntimeException("No strings available"))
.forEach(System.out::println);
nonEmptyStream(l.stream().filter(s->s.startsWith("x")),
()->new RuntimeException("No strings available"))
.forEach(System.out::println);
The problem with (efficient) parallel execution is that supporting splitting of the Spliterator
requires a thread-safe way to notice whether either of the fragments has seen any value in a thread-safe manner. Then the last of the fragments executing tryAdvance
has to realize that it is the last one (and it also couldn’t advance) to throw the appropriate exception. So I didn’t add support for splitting here.
The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await
with Task'1.Result
, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.
I've rewritten your function and function call, which should fix your issue:
async Task<string> GetResponseString(string text)
{
var httpClient = new HttpClient();
var parameters = new Dictionary<string, string>();
parameters["text"] = text;
var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
var contents = await response.Content.ReadAsStringAsync();
return contents;
}
And your final function call:
Task<string> result = GetResponseString(text);
var finalResult = result.Result;
Or even better:
var finalResult = await GetResponseString(text);
Alternatively, manually download and execute http://www.lfd.uci.edu/~gohlke/pythonlibs Scipy version suitable for you. Consider your Python version (python --version) and your system architecture (32/64 bit). Choose the Scipy version accordingly. scipy-0.18.1-cp27-cp27m-win32 - for Python 2.7 32 bit scipy-0.18.1-cp27-cp27m-win_amd64 - for Python 2.7 64 bit Otherwise the error scipy-0.15.1-cp33-none-win_amd64.whl.whl is not supported wheel on this platform will popup on installation.
Now change directory to the downloaded file and execute command
pip install scipy-0.15.1-cp33-none-win_amd64.whl.whl
(change file name appropriately)
I have added this answer only because the Arun's answer(found useful by myself) has not mentioned anything about 32/64 bit matching which i have faced.
sudo apt install aptitude
Then
sudo aptitude install npm
The first thing you should make sure is that your static library has all architectures. When you do a lipo -info myStaticLibrary.a
on terminal - you should see armv7 armv7s i386 x86_64 arm64
architectures for your fat binary.
To accomplish that, I am assuming that you're making a universal binary - add the following to your architecture settings of static library project -
Standard architectures (including 64-bit) (armv7, armv7s, arm64)
of the static library project.$ARCHS_STANDARD
now includes 64-bit. You can also do $(ARCHS_STANDARD)
and armv7s
. Check lipo -info
without it, and you'll figure out the missing architectures. Here's the screenshot for all architectures -For your reference implementation (project using static library). The default settings should work fine -
Update 12/03/14 Xcode 6 Standard architectures exclude armv7s.
So, armv7s
is not needed? Yes. It seems that the general differences between armv7 and armv7s instruction sets are minor. So if you choose not to include armv7s, the targeted armv7 machine code still runs fine on 32 bit A6 devices, and hardly one will notice performance gap. Source
If there is a smarter way for Xcode 6.1+ (iOS 8.1 and above) - please share.
Easiest way to solve this problem is install ASP.NET MVC 3 from Web Platforms installer.
http://www.microsoft.com/web/downloads/
Or by using Nuget command
Install-Package Microsoft.AspNet.Mvc -Version 3.0.50813.1
My Project Build Target of android-support-v7-appcompat was with API 19 just changed it to API 20 it worked for me
Right click on android-support-v7-appcompat
library project
Go to properties
Click on Android
Change project build Target from Android 4.x.x to Android 5.0
This helped me hopefully it helps others too.
Goto the SDK manager in your IDE and install the latest "Intel HAXM" and start the emulator.
If it is throwing the error as
Starting emulator for AVD 'X86'
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX is not installed on this machine (/dev/HAX is missing).
It means that some hardware graphical features are to be assigned.So to overcome this problem just go to the path where you have your Adroid SDK
installed.
C:\Android\SDK\extras\intel\Hardware_Accelerated_Execution_Manager
There you can find the file intelhaxm-android.exe
.
On Mac OSXthere is a IntelHAXM_X.X.X.dmg
file, mount it and you'll find an mpkg-file.
Install the file and restart all the applications using android emulator such as(android studio,cmd etc..,).
Now try to open the emulator it will work fine
I ran into the same issue and had the right API level values in my build.gradle compileSdkVersion 21, targetSdkVersion 21 and a buildToolsVersion of 21.0.1
However, I was including this as a module in my project so I had to make sure the other module gradle settings matched API 21. After that it all worked for me.
Arr1 becomes an array of 'Variant' by the first statement of your code:
Dim arr1() As Variant
Array of size zero is not empty, as like an empty box exists in real world.
If you define a variable of 'Variant', that will be empty when it is created.
Following code will display "Empty".
Dim a as Variant
If IsEmpty(a) then
MsgBox("Empty")
Else
MsgBox("Not Empty")
End If
An easy way to do this is using the pandas
library like this.
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name
The problem here was the skipinitialspace
which remove the spaces in the header. So ' star_name' becomes 'star_name'
Long story short you need to create a launch file. So, from Terminal:
sudo vi /Library/LaunchDaemons/com.mysql.mysql.plist
(If you are not familiar with vi, then press i to start inserting text)
This should be the content of your file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>KeepAlive</key>
<true />
<key>Label</key>
<string>com.mysql.mysqld</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/mysql/bin/mysqld_safe</string>
<string>--user=mysql</string>
</array>
</dict>
</plist>
press esc then : wq!enter
Then you need to give the file the right permissions and set it to load on startup.
sudo chown root:wheel /Library/LaunchDaemons/com.mysql.mysql.plist
sudo chmod 644 /Library/LaunchDaemons/com.mysql.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/com.mysql.mysql.plist
And that is it.
This is caused by MySQL having a strict mode set which won’t allow INSERT or UPDATE commands with empty fields where the schema doesn’t have a default value set.
There are a couple of fixes for this.
First ‘fix’ is to assign a default value to your schema. This can be done with a simple ALTER command:
ALTER TABLE `details` CHANGE COLUMN `delivery_address_id` `delivery_address_id` INT(11) NOT NULL DEFAULT 0 ;
However, this may need doing for many tables in your database schema which will become tedious very quickly. The second fix is to remove sql_mode STRICT_TRANS_TABLES on the mysql server.
If you are using a brew installed MySQL you should edit the my.cnf file in the MySQL directory. Change the sql_mode at the bottom:
#sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode=NO_ENGINE_SUBSTITUTION
Save the file and restart Mysql.
Source: https://www.euperia.com/development/mysql-fix-field-doesnt-default-value/1509
Here are the commands to restore the old behavior:
# create a script that calls launchctl iterating through /etc/launchd.conf
echo '#!/bin/sh
while read line || [[ -n $line ]] ; do launchctl $line ; done < /etc/launchd.conf;
' > /usr/local/bin/launchd.conf.sh
# make it executable
chmod +x /usr/local/bin/launchd.conf.sh
# launch the script at startup
echo '<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>launchd.conf</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>/usr/local/bin/launchd.conf.sh</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
' > /Library/LaunchAgents/launchd.conf.plist
Now you can specify commands like setenv JAVA_HOME /Library/Java/Home
in /etc/launchd.conf
.
Checked on El Capitan.
This may be due to how Spark computes its classpath. My hunch is that Hadoop's log4j.properties
file is appearing ahead of Spark's on the classpath, preventing your changes from taking effect.
If you run
SPARK_PRINT_LAUNCH_COMMAND=1 bin/spark-shell
then Spark will print the full classpath used to launch the shell; in my case, I see
Spark Command: /usr/lib/jvm/java/bin/java -cp :::/root/ephemeral-hdfs/conf:/root/spark/conf:/root/spark/lib/spark-assembly-1.0.0-hadoop1.0.4.jar:/root/spark/lib/datanucleus-api-jdo-3.2.1.jar:/root/spark/lib/datanucleus-core-3.2.2.jar:/root/spark/lib/datanucleus-rdbms-3.2.1.jar -XX:MaxPermSize=128m -Djava.library.path=:/root/ephemeral-hdfs/lib/native/ -Xms512m -Xmx512m org.apache.spark.deploy.SparkSubmit spark-shell --class org.apache.spark.repl.Main
where /root/ephemeral-hdfs/conf
is at the head of the classpath.
I've opened an issue [SPARK-2913] to fix this in the next release (I should have a patch out soon).
In the meantime, here's a couple of workarounds:
export SPARK_SUBMIT_CLASSPATH="$FWDIR/conf"
to spark-env.sh
./root/ephemeral-hdfs/conf/log4j.properties
.This depends on what content do you have. You need to initialize your requestMessage.Content
property with new HttpContent. For example:
...
// Add request body
if (isPostRequest)
{
requestMessage.Content = new ByteArrayContent(content);
}
...
where content
is your encoded content. You also should include correct Content-type header.
Oh, it can be even nicer (from this answer):
requestMessage.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}", Encoding.UTF8, "application/json");
If you are on Mac run use root privilege
sudo npm install gulp-cli --global
To check if it's installed run
gulp -v
CLI version: 2.2.0 (The output)
Local version: Unknown
This is not an answer but a feedback with few compilers of 2021. On Intel CoffeeLake 9900k.
With Microsoft compiler (VS2019), toolset v142:
unsigned 209695540000 1.8322 sec 28.6152 GB/s uint64_t 209695540000 3.08764 sec 16.9802 GB/s
With Intel compiler 2021:
unsigned 209695540000 1.70845 sec 30.688 GB/s uint64_t 209695540000 1.57956 sec 33.1921 GB/s
According to Mysticial's answer, Intel compiler is aware of False Data Dependency, but not Microsoft compiler.
For intel compiler, I used /QxHost
(optimize of CPU's architecture which is that of the host) /Oi
(enable intrinsic functions) and #include <nmmintrin.h>
instead of #include <immintrin.h>
.
Full compile command: /GS /W3 /QxHost /Gy /Zi /O2 /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" //fprofile-instr-use "x64\Release\" /Fp"x64\Release\Benchmark.pch"
.
The decompiled (by IDA 7.5) assembly from ICC:
int __cdecl main(int argc, const char **argv, const char **envp)
{
int v6; // er13
_BYTE *v8; // rsi
unsigned int v9; // edi
unsigned __int64 i; // rbx
unsigned __int64 v11; // rdi
int v12; // ebp
__int64 v13; // r14
__int64 v14; // rbx
unsigned int v15; // eax
unsigned __int64 v16; // rcx
unsigned int v17; // eax
unsigned __int64 v18; // rcx
__int64 v19; // rdx
unsigned int v20; // eax
int result; // eax
std::ostream *v23; // rbx
char v24; // dl
std::ostream *v33; // rbx
std::ostream *v41; // rbx
__int64 v42; // rdx
unsigned int v43; // eax
int v44; // ebp
__int64 v45; // r14
__int64 v46; // rbx
unsigned __int64 v47; // rax
unsigned __int64 v48; // rax
std::ostream *v50; // rdi
char v51; // dl
std::ostream *v58; // rdi
std::ostream *v60; // rdi
__int64 v61; // rdx
unsigned int v62; // eax
__asm
{
vmovdqa [rsp+98h+var_58], xmm8
vmovapd [rsp+98h+var_68], xmm7
vmovapd [rsp+98h+var_78], xmm6
}
if ( argc == 2 )
{
v6 = atol(argv[1]) << 20;
_R15 = v6;
v8 = operator new[](v6);
if ( v6 )
{
v9 = 1;
for ( i = 0i64; i < v6; i = v9++ )
v8[i] = rand();
}
v11 = (unsigned __int64)v6 >> 3;
v12 = 0;
v13 = Xtime_get_ticks_0();
v14 = 0i64;
do
{
if ( v6 )
{
v15 = 4;
v16 = 0i64;
do
{
v14 += __popcnt(*(_QWORD *)&v8[8 * v16])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 24])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 16])
+ __popcnt(*(_QWORD *)&v8[8 * v15 - 8]);
v16 = v15;
v15 += 4;
}
while ( v11 > v16 );
v17 = 4;
v18 = 0i64;
do
{
v14 += __popcnt(*(_QWORD *)&v8[8 * v18])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 24])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 16])
+ __popcnt(*(_QWORD *)&v8[8 * v17 - 8]);
v18 = v17;
v17 += 4;
}
while ( v11 > v18 );
}
v12 += 2;
}
while ( v12 != 10000 );
_RBP = 100 * (Xtime_get_ticks_0() - v13);
std::operator___std::char_traits_char___(std::cout, "unsigned\t");
v23 = (std::ostream *)std::ostream::operator<<(std::cout, v14);
std::operator___std::char_traits_char____0(v23, v24);
__asm
{
vmovq xmm0, rbp
vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
vpunpckldq xmm0, xmm0, xmm8
vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
vsubpd xmm0, xmm0, xmm7
vpermilpd xmm1, xmm0, 1
vaddsd xmm6, xmm1, xmm0
vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
}
v33 = (std::ostream *)std::ostream::operator<<(v23);
std::operator___std::char_traits_char___(v33, " sec \t");
__asm
{
vmovq xmm0, r15
vpunpckldq xmm0, xmm0, xmm8
vsubpd xmm0, xmm0, xmm7
vpermilpd xmm1, xmm0, 1
vaddsd xmm0, xmm1, xmm0
vmulsd xmm7, xmm0, cs:__real@40c3880000000000
vdivsd xmm1, xmm7, xmm6
}
v41 = (std::ostream *)std::ostream::operator<<(v33);
std::operator___std::char_traits_char___(v41, " GB/s");
LOBYTE(v42) = 10;
v43 = std::ios::widen((char *)v41 + *(int *)(*(_QWORD *)v41 + 4i64), v42);
std::ostream::put(v41, v43);
std::ostream::flush(v41);
v44 = 0;
v45 = Xtime_get_ticks_0();
v46 = 0i64;
do
{
if ( v6 )
{
v47 = 0i64;
do
{
v46 += __popcnt(*(_QWORD *)&v8[8 * v47])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 8])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 16])
+ __popcnt(*(_QWORD *)&v8[8 * v47 + 24]);
v47 += 4i64;
}
while ( v47 < v11 );
v48 = 0i64;
do
{
v46 += __popcnt(*(_QWORD *)&v8[8 * v48])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 8])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 16])
+ __popcnt(*(_QWORD *)&v8[8 * v48 + 24]);
v48 += 4i64;
}
while ( v48 < v11 );
}
v44 += 2;
}
while ( v44 != 10000 );
_RBP = 100 * (Xtime_get_ticks_0() - v45);
std::operator___std::char_traits_char___(std::cout, "uint64_t\t");
v50 = (std::ostream *)std::ostream::operator<<(std::cout, v46);
std::operator___std::char_traits_char____0(v50, v51);
__asm
{
vmovq xmm0, rbp
vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
vsubpd xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
vpermilpd xmm1, xmm0, 1
vaddsd xmm6, xmm1, xmm0
vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
}
v58 = (std::ostream *)std::ostream::operator<<(v50);
std::operator___std::char_traits_char___(v58, " sec \t");
__asm { vdivsd xmm1, xmm7, xmm6 }
v60 = (std::ostream *)std::ostream::operator<<(v58);
std::operator___std::char_traits_char___(v60, " GB/s");
LOBYTE(v61) = 10;
v62 = std::ios::widen((char *)v60 + *(int *)(*(_QWORD *)v60 + 4i64), v61);
std::ostream::put(v60, v62);
std::ostream::flush(v60);
free(v8);
result = 0;
}
else
{
std::operator___std::char_traits_char___(std::cerr, "usage: array_size in MB");
LOBYTE(v19) = 10;
v20 = std::ios::widen((char *)&std::cerr + *((int *)std::cerr + 1), v19);
std::ostream::put(std::cerr, v20);
std::ostream::flush(std::cerr);
result = -1;
}
__asm
{
vmovaps xmm6, [rsp+98h+var_78]
vmovaps xmm7, [rsp+98h+var_68]
vmovaps xmm8, [rsp+98h+var_58]
}
return result;
}
and disassembly of main:
.text:0140001000 .686p
.text:0140001000 .mmx
.text:0140001000 .model flat
.text:0140001000
.text:0140001000 ; ===========================================================================
.text:0140001000
.text:0140001000 ; Segment type: Pure code
.text:0140001000 ; Segment permissions: Read/Execute
.text:0140001000 _text segment para public 'CODE' use64
.text:0140001000 assume cs:_text
.text:0140001000 ;org 140001000h
.text:0140001000 assume es:nothing, ss:nothing, ds:_data, fs:nothing, gs:nothing
.text:0140001000
.text:0140001000 ; =============== S U B R O U T I N E =======================================
.text:0140001000
.text:0140001000
.text:0140001000 ; int __cdecl main(int argc, const char **argv, const char **envp)
.text:0140001000 main proc near ; CODE XREF: __scrt_common_main_seh+107?p
.text:0140001000 ; DATA XREF: .pdata:ExceptionDir?o
.text:0140001000
.text:0140001000 var_78 = xmmword ptr -78h
.text:0140001000 var_68 = xmmword ptr -68h
.text:0140001000 var_58 = xmmword ptr -58h
.text:0140001000
.text:0140001000 push r15
.text:0140001002 push r14
.text:0140001004 push r13
.text:0140001006 push r12
.text:0140001008 push rsi
.text:0140001009 push rdi
.text:014000100A push rbp
.text:014000100B push rbx
.text:014000100C sub rsp, 58h
.text:0140001010 vmovdqa [rsp+98h+var_58], xmm8
.text:0140001016 vmovapd [rsp+98h+var_68], xmm7
.text:014000101C vmovapd [rsp+98h+var_78], xmm6
.text:0140001022 cmp ecx, 2
.text:0140001025 jnz loc_14000113E
.text:014000102B mov rcx, [rdx+8] ; String
.text:014000102F call cs:__imp_atol
.text:0140001035 mov r13d, eax
.text:0140001038 shl r13d, 14h
.text:014000103C movsxd r15, r13d
.text:014000103F mov rcx, r15 ; size
.text:0140001042 call ??_U@YAPEAX_K@Z ; operator new[](unsigned __int64)
.text:0140001047 mov rsi, rax
.text:014000104A test r15d, r15d
.text:014000104D jz short loc_14000106E
.text:014000104F mov edi, 1
.text:0140001054 xor ebx, ebx
.text:0140001056 mov rbp, cs:__imp_rand
.text:014000105D nop dword ptr [rax]
.text:0140001060
.text:0140001060 loc_140001060: ; CODE XREF: main+6C?j
.text:0140001060 call rbp ; __imp_rand
.text:0140001062 mov [rsi+rbx], al
.text:0140001065 mov ebx, edi
.text:0140001067 inc edi
.text:0140001069 cmp rbx, r15
.text:014000106C jb short loc_140001060
.text:014000106E
.text:014000106E loc_14000106E: ; CODE XREF: main+4D?j
.text:014000106E mov rdi, r15
.text:0140001071 shr rdi, 3
.text:0140001075 xor ebp, ebp
.text:0140001077 call _Xtime_get_ticks_0
.text:014000107C mov r14, rax
.text:014000107F xor ebx, ebx
.text:0140001081 jmp short loc_14000109F
.text:0140001081 ; ---------------------------------------------------------------------------
.text:0140001083 align 10h
.text:0140001090
.text:0140001090 loc_140001090: ; CODE XREF: main+A2?j
.text:0140001090 ; main+EC?j ...
.text:0140001090 add ebp, 2
.text:0140001093 cmp ebp, 2710h
.text:0140001099 jz loc_140001184
.text:014000109F
.text:014000109F loc_14000109F: ; CODE XREF: main+81?j
.text:014000109F test r13d, r13d
.text:01400010A2 jz short loc_140001090
.text:01400010A4 mov eax, 4
.text:01400010A9 xor ecx, ecx
.text:01400010AB nop dword ptr [rax+rax+00h]
.text:01400010B0
.text:01400010B0 loc_1400010B0: ; CODE XREF: main+E7?j
.text:01400010B0 popcnt rcx, qword ptr [rsi+rcx*8]
.text:01400010B6 add rcx, rbx
.text:01400010B9 lea edx, [rax-3]
.text:01400010BC popcnt rdx, qword ptr [rsi+rdx*8]
.text:01400010C2 add rdx, rcx
.text:01400010C5 lea ecx, [rax-2]
.text:01400010C8 popcnt rcx, qword ptr [rsi+rcx*8]
.text:01400010CE add rcx, rdx
.text:01400010D1 lea edx, [rax-1]
.text:01400010D4 xor ebx, ebx
.text:01400010D6 popcnt rbx, qword ptr [rsi+rdx*8]
.text:01400010DC add rbx, rcx
.text:01400010DF mov ecx, eax
.text:01400010E1 add eax, 4
.text:01400010E4 cmp rdi, rcx
.text:01400010E7 ja short loc_1400010B0
.text:01400010E9 test r13d, r13d
.text:01400010EC jz short loc_140001090
.text:01400010EE mov eax, 4
.text:01400010F3 xor ecx, ecx
.text:01400010F5 db 2Eh
.text:01400010F5 nop word ptr [rax+rax+00000000h]
.text:01400010FF nop
.text:0140001100
.text:0140001100 loc_140001100: ; CODE XREF: main+137?j
.text:0140001100 popcnt rcx, qword ptr [rsi+rcx*8]
.text:0140001106 add rcx, rbx
.text:0140001109 lea edx, [rax-3]
.text:014000110C popcnt rdx, qword ptr [rsi+rdx*8]
.text:0140001112 add rdx, rcx
.text:0140001115 lea ecx, [rax-2]
.text:0140001118 popcnt rcx, qword ptr [rsi+rcx*8]
.text:014000111E add rcx, rdx
.text:0140001121 lea edx, [rax-1]
.text:0140001124 xor ebx, ebx
.text:0140001126 popcnt rbx, qword ptr [rsi+rdx*8]
.text:014000112C add rbx, rcx
.text:014000112F mov ecx, eax
.text:0140001131 add eax, 4
.text:0140001134 cmp rdi, rcx
.text:0140001137 ja short loc_140001100
.text:0140001139 jmp loc_140001090
.text:014000113E ; ---------------------------------------------------------------------------
.text:014000113E
.text:014000113E loc_14000113E: ; CODE XREF: main+25?j
.text:014000113E mov rsi, cs:__imp_?cerr@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cerr
.text:0140001145 lea rdx, aUsageArraySize ; "usage: array_size in MB"
.text:014000114C mov rcx, rsi ; std::ostream *
.text:014000114F call std__operator___std__char_traits_char___
.text:0140001154 mov rax, [rsi]
.text:0140001157 movsxd rcx, dword ptr [rax+4]
.text:014000115B add rcx, rsi
.text:014000115E mov dl, 0Ah
.text:0140001160 call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:0140001166 mov rcx, rsi
.text:0140001169 mov edx, eax
.text:014000116B call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001171 mov rcx, rsi
.text:0140001174 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000117A mov eax, 0FFFFFFFFh
.text:014000117F jmp loc_1400013E2
.text:0140001184 ; ---------------------------------------------------------------------------
.text:0140001184
.text:0140001184 loc_140001184: ; CODE XREF: main+99?j
.text:0140001184 call _Xtime_get_ticks_0
.text:0140001189 sub rax, r14
.text:014000118C imul rbp, rax, 64h ; 'd'
.text:0140001190 mov r14, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001197 lea rdx, aUnsigned ; "unsigned\t"
.text:014000119E mov rcx, r14 ; std::ostream *
.text:01400011A1 call std__operator___std__char_traits_char___
.text:01400011A6 mov rcx, r14
.text:01400011A9 mov rdx, rbx
.text:01400011AC call cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:01400011B2 mov rbx, rax
.text:01400011B5 mov rcx, rax ; std::ostream *
.text:01400011B8 call std__operator___std__char_traits_char____0
.text:01400011BD vmovq xmm0, rbp
.text:01400011C2 vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
.text:01400011CA vpunpckldq xmm0, xmm0, xmm8
.text:01400011CF vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
.text:01400011D7 vsubpd xmm0, xmm0, xmm7
.text:01400011DB vpermilpd xmm1, xmm0, 1
.text:01400011E1 vaddsd xmm6, xmm1, xmm0
.text:01400011E5 vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
.text:01400011ED mov r12, cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z ; std::ostream::operator<<(double)
.text:01400011F4 mov rcx, rbx
.text:01400011F7 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:01400011FA mov rbx, rax
.text:01400011FD lea rdx, aSec ; " sec \t"
.text:0140001204 mov rcx, rax ; std::ostream *
.text:0140001207 call std__operator___std__char_traits_char___
.text:014000120C vmovq xmm0, r15
.text:0140001211 vpunpckldq xmm0, xmm0, xmm8
.text:0140001216 vsubpd xmm0, xmm0, xmm7
.text:014000121A vpermilpd xmm1, xmm0, 1
.text:0140001220 vaddsd xmm0, xmm1, xmm0
.text:0140001224 vmulsd xmm7, xmm0, cs:__real@40c3880000000000
.text:014000122C vdivsd xmm1, xmm7, xmm6
.text:0140001230 mov rcx, rbx
.text:0140001233 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001236 mov rbx, rax
.text:0140001239 lea rdx, aGbS ; " GB/s"
.text:0140001240 mov rcx, rax ; std::ostream *
.text:0140001243 call std__operator___std__char_traits_char___
.text:0140001248 mov rax, [rbx]
.text:014000124B movsxd rcx, dword ptr [rax+4]
.text:014000124F add rcx, rbx
.text:0140001252 mov dl, 0Ah
.text:0140001254 call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:014000125A mov rcx, rbx
.text:014000125D mov edx, eax
.text:014000125F call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001265 mov rcx, rbx
.text:0140001268 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000126E xor ebp, ebp
.text:0140001270 call _Xtime_get_ticks_0
.text:0140001275 mov r14, rax
.text:0140001278 xor ebx, ebx
.text:014000127A jmp short loc_14000128F
.text:014000127A ; ---------------------------------------------------------------------------
.text:014000127C align 20h
.text:0140001280
.text:0140001280 loc_140001280: ; CODE XREF: main+292?j
.text:0140001280 ; main+2DB?j ...
.text:0140001280 add ebp, 2
.text:0140001283 cmp ebp, 2710h
.text:0140001289 jz loc_14000131D
.text:014000128F
.text:014000128F loc_14000128F: ; CODE XREF: main+27A?j
.text:014000128F test r13d, r13d
.text:0140001292 jz short loc_140001280
.text:0140001294 xor eax, eax
.text:0140001296 db 2Eh
.text:0140001296 nop word ptr [rax+rax+00000000h]
.text:01400012A0
.text:01400012A0 loc_1400012A0: ; CODE XREF: main+2D6?j
.text:01400012A0 xor ecx, ecx
.text:01400012A2 popcnt rcx, qword ptr [rsi+rax*8]
.text:01400012A8 add rcx, rbx
.text:01400012AB xor edx, edx
.text:01400012AD popcnt rdx, qword ptr [rsi+rax*8+8]
.text:01400012B4 add rdx, rcx
.text:01400012B7 xor ecx, ecx
.text:01400012B9 popcnt rcx, qword ptr [rsi+rax*8+10h]
.text:01400012C0 add rcx, rdx
.text:01400012C3 xor ebx, ebx
.text:01400012C5 popcnt rbx, qword ptr [rsi+rax*8+18h]
.text:01400012CC add rbx, rcx
.text:01400012CF add rax, 4
.text:01400012D3 cmp rax, rdi
.text:01400012D6 jb short loc_1400012A0
.text:01400012D8 test r13d, r13d
.text:01400012DB jz short loc_140001280
.text:01400012DD xor eax, eax
.text:01400012DF nop
.text:01400012E0
.text:01400012E0 loc_1400012E0: ; CODE XREF: main+316?j
.text:01400012E0 xor ecx, ecx
.text:01400012E2 popcnt rcx, qword ptr [rsi+rax*8]
.text:01400012E8 add rcx, rbx
.text:01400012EB xor edx, edx
.text:01400012ED popcnt rdx, qword ptr [rsi+rax*8+8]
.text:01400012F4 add rdx, rcx
.text:01400012F7 xor ecx, ecx
.text:01400012F9 popcnt rcx, qword ptr [rsi+rax*8+10h]
.text:0140001300 add rcx, rdx
.text:0140001303 xor ebx, ebx
.text:0140001305 popcnt rbx, qword ptr [rsi+rax*8+18h]
.text:014000130C add rbx, rcx
.text:014000130F add rax, 4
.text:0140001313 cmp rax, rdi
.text:0140001316 jb short loc_1400012E0
.text:0140001318 jmp loc_140001280
.text:014000131D ; ---------------------------------------------------------------------------
.text:014000131D
.text:014000131D loc_14000131D: ; CODE XREF: main+289?j
.text:014000131D call _Xtime_get_ticks_0
.text:0140001322 sub rax, r14
.text:0140001325 imul rbp, rax, 64h ; 'd'
.text:0140001329 mov rdi, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001330 lea rdx, aUint64T ; "uint64_t\t"
.text:0140001337 mov rcx, rdi ; std::ostream *
.text:014000133A call std__operator___std__char_traits_char___
.text:014000133F mov rcx, rdi
.text:0140001342 mov rdx, rbx
.text:0140001345 call cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:014000134B mov rdi, rax
.text:014000134E mov rcx, rax ; std::ostream *
.text:0140001351 call std__operator___std__char_traits_char____0
.text:0140001356 vmovq xmm0, rbp
.text:014000135B vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
.text:0140001363 vsubpd xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
.text:014000136B vpermilpd xmm1, xmm0, 1
.text:0140001371 vaddsd xmm6, xmm1, xmm0
.text:0140001375 vdivsd xmm1, xmm6, cs:__real@41cdcd6500000000
.text:014000137D mov rcx, rdi
.text:0140001380 call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001383 mov rdi, rax
.text:0140001386 lea rdx, aSec ; " sec \t"
.text:014000138D mov rcx, rax ; std::ostream *
.text:0140001390 call std__operator___std__char_traits_char___
.text:0140001395 vdivsd xmm1, xmm7, xmm6
.text:0140001399 mov rcx, rdi
.text:014000139C call r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:014000139F mov rdi, rax
.text:01400013A2 lea rdx, aGbS ; " GB/s"
.text:01400013A9 mov rcx, rax ; std::ostream *
.text:01400013AC call std__operator___std__char_traits_char___
.text:01400013B1 mov rax, [rdi]
.text:01400013B4 movsxd rcx, dword ptr [rax+4]
.text:01400013B8 add rcx, rdi
.text:01400013BB mov dl, 0Ah
.text:01400013BD call cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:01400013C3 mov rcx, rdi
.text:01400013C6 mov edx, eax
.text:01400013C8 call cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:01400013CE mov rcx, rdi
.text:01400013D1 call cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:01400013D7 mov rcx, rsi ; Block
.text:01400013DA call cs:__imp_free
.text:01400013E0 xor eax, eax
.text:01400013E2
.text:01400013E2 loc_1400013E2: ; CODE XREF: main+17F?j
.text:01400013E2 vmovaps xmm6, [rsp+98h+var_78]
.text:01400013E8 vmovaps xmm7, [rsp+98h+var_68]
.text:01400013EE vmovaps xmm8, [rsp+98h+var_58]
.text:01400013F4 add rsp, 58h
.text:01400013F8 pop rbx
.text:01400013F9 pop rbp
.text:01400013FA pop rdi
.text:01400013FB pop rsi
.text:01400013FC pop r12
.text:01400013FE pop r13
.text:0140001400 pop r14
.text:0140001402 pop r15
.text:0140001404 retn
.text:0140001404 main endp
Coffee lake specification update "POPCNT instruction may take longer to execute than expected".
This is an easy way to get a successful response from the server like PHP echo otherwise an error message.
BufferedReader br = null;
if (conn.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
} else {
br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String strCurrentLine;
while ((strCurrentLine = br.readLine()) != null) {
System.out.println(strCurrentLine);
}
}
jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}, {"name": "Joe Schmoe"}]}, "type": "status", "id": "id_7"}"""
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
print("to_id:", dest.get('id', 'null'))
Try it:
>>> getTargetIds(jsonData)
to_id: 1543
to_id: null
Or, if you just want to skip over values missing ids instead of printing 'null'
:
def getTargetIds(jsonData):
data = json.loads(jsonData)
for dest in data['to']['data']:
if 'id' in to_id:
print("to_id:", dest['id'])
So:
>>> getTargetIds(jsonData)
to_id: 1543
Of course in real life, you probably don't want to print
each id, but to store them and do something with them, but that's another issue.
Obviously there's a lot of different causes and thus a lot of solutions for this problem. To throw mine into the mix, we upgraded an assembly (System.Net.Http) that was previously directly referenced in our Web project to a version managed by NuGet. This removed the direct reference within that project, but our Test project still contained the direct reference. Upgrading both projects to use the NuGet-managed assembly resolved the issue.
If what you're looking for is simply to blur the image edges you can simply use the box-shadow with an inset.
Working example: http://jsfiddle.net/d9Q5H/1/
HTML:
<div class="image-blurred-edge"></div>
CSS
.image-blurred-edge {
background-image: url('http://lorempixel.com/200/200/city/9');
width: 200px;
height: 200px;
/* you need to match the shadow color to your background or image border for the desired effect*/
box-shadow: 0 0 8px 8px white inset;
}
This question's bit old, but, there's a tricky scenario which also leads to this error:
In controller:
ViewBag.id = //id from querystring
List<string> = GrabDataFromDBByID(ViewBag.id).Select(a=>a.ToString());
The above code will lead to an error in this part: .Select(a=>a.ToString())
because of the below reason:
You're passing a ViewBag.id
to a method which in compiler, it doesn't know the type, so there might be several methods with the same name and different parameters let's say:
GrabDataFromDBByID(string)
GrabDataFromDBByID(int)
GrabDataFromDBByID(whateverType)
So to prevent this case, either explicitly cast the ViewBag or create another variable storing it.
I had a different issue that brought me to this question, which will probably be more common than the overrelease issue in the accepted answer.
Root cause was our completion block being called twice due to bad if/else fallthrough in the network handler, leading to two calls of dispatch_group_leave
for every one call to dispatch_group_enter
.
dispatch_group_enter(group);
[self badMethodThatCallsMULTIPLECompletions:^(NSString *completion) {
// this block is called multiple times
// one `enter` but multiple `leave`
dispatch_group_leave(group);
}];
count
Upon the EXC_BAD_INSTRUCTION
, you should still have access to your dispatch_group in the debugger. DispatchGroup: check how many "entered"
Print out the dispatch_group and you'll see:
<OS_dispatch_group: group[0x60800008bf40] = { xrefcnt = 0x2, refcnt = 0x1, port = 0x0, count = -1, waiters = 0 }>
When you see count = -1
it indicates that you've over-left the dispatch_group. Be sure to dispatch_enter
and dispatch_leave
the group in matched pairs.
From The Swift Programming Language
:
The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.
The sort
function has two declarations.
The default declaration which allows you to specify a comparison closure:
func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]
And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."
func sort<T : Comparable>(array: T[]) -> T[]
Example:
sort( _arrayToSort_ ) { $0 > $1 }
I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.
let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = random()
}
let y = sort(x) { $0 > $1 }
It is not an efficient function, an I would recommend using a better sorting function implementation.
EDIT:
I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)
import Foundation
func quickSort(inout array: Int[], begin: Int, end: Int) {
if (begin < end) {
let p = partition(&array, begin, end)
quickSort(&array, begin, p - 1)
quickSort(&array, p + 1, end)
}
}
func partition(inout array: Int[], left: Int, right: Int) -> Int {
let numElements = right - left + 1
let pivotIndex = left + numElements / 2
let pivotValue = array[pivotIndex]
swap(&array[pivotIndex], &array[right])
var storeIndex = left
for i in left..right {
let a = 1 // <- Used to see how many comparisons are made
if array[i] <= pivotValue {
swap(&array[i], &array[storeIndex])
storeIndex++
}
}
swap(&array[storeIndex], &array[right]) // Move pivot to its final place
return storeIndex
}
let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
x[i] = Int(arc4random())
}
quickSort(&x, 0, x.count - 1) // <- Does the sorting
for i in 0..n {
x[i] // <- Used by the playground to display the results
}
Using this with n=1000, I found that
It seems that the built-in sort method is (or is close to) quick sort, and is really slow...
AFAIK, {...}
can only be used as a path, not inside a query-param. Try this instead:
public interface FooService {
@GET("/maps/api/geocode/json?sensor=false")
void getPositionByZip(@Query("address") String address, Callback<String> cb);
}
If you have an unknown amount of parameters to pass, you can use do something like this:
public interface FooService {
@GET("/maps/api/geocode/json")
@FormUrlEncoded
void getPositionByZip(@FieldMap Map<String, String> params, Callback<String> cb);
}
Windows -> references ->Android->lint error checking.
un tick Run full error.......
We also had to develop a solution which would even work with APIs requiring authentication (see this article)
Using AngularJS in a nutshell here is how we did it:
Step 1: Create a dedicated directive
// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
restrict: 'E',
templateUrl: '/path/to/pdfDownload.tpl.html',
scope: true,
link: function(scope, element, attr) {
var anchor = element.children()[0];
// When the download starts, disable the link
scope.$on('download-start', function() {
$(anchor).attr('disabled', 'disabled');
});
// When the download finishes, attach the data to the link. Enable the link and change its appearance.
scope.$on('downloaded', function(event, data) {
$(anchor).attr({
href: 'data:application/pdf;base64,' + data,
download: attr.filename
})
.removeAttr('disabled')
.text('Save')
.removeClass('btn-primary')
.addClass('btn-success');
// Also overwrite the download pdf function to do nothing.
scope.downloadPdf = function() {
};
});
},
controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
$scope.downloadPdf = function() {
$scope.$emit('download-start');
$http.get($attrs.url).then(function(response) {
$scope.$emit('downloaded', response.data);
});
};
}]
});
Step 2: Create a template
<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>
Step 3: Use it
<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>
This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.
Like this.
function printMousePos(event) {_x000D_
document.body.textContent =_x000D_
"clientX: " + event.clientX +_x000D_
" - clientY: " + event.clientY;_x000D_
}_x000D_
_x000D_
document.addEventListener("click", printMousePos);
_x000D_
MouseEvent.clientX Read only
The X coordinate of the mouse pointer in local (DOM content) coordinates.MouseEvent.clientY Read only
The Y coordinate of the mouse pointer in local (DOM content) coordinates.
Here is the solution:
For Update:
public function controllerName(Request $request, $id)
{
$this->validate($request, [
"form_field_name" => 'required|unique:db_table_name,db_table_column_name,'.$id
]);
// the rest code
}
That's it. Happy Coding :)
StringUtils.isBlank
also returns true
for just whitespace:
isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
Alternatively there is the built-in function pd.get_dummies for these kinds of assignments:
w['female'] = pd.get_dummies(w['female'],drop_first = True)
This gives you a data frame with two columns, one for each value that occurs in w['female'], of which you drop the first (because you can infer it from the one that is left). The new column is automatically named as the string that you replaced.
This is especially useful if you have categorical variables with more than two possible values. This function creates as many dummy variables needed to distinguish between all cases. Be careful then that you don't assign the entire data frame to a single column, but instead, if w['female'] could be 'male', 'female' or 'neutral', do something like this:
w = pd.concat([w, pd.get_dummies(w['female'], drop_first = True)], axis = 1])
w.drop('female', axis = 1, inplace = True)
Then you are left with two new columns giving you the dummy coding of 'female' and you got rid of the column with the strings.
In JavaScript, we can close a window only if it is opened by using window.open
method:
window.open('https://www.google.com');
window.close();
But to close a window which has not been opened using window.open()
, you must
window.open()
)window.open("", "_self");
window.close();
A slightly different approach I took to solve this problem, I have observed two key points in this problem.
So I converted these points into easy-to-implement and understandable format.
For Example : "{ } ( ) [ ]" will be "1 -1 2 -2 3 -3" is valid parenthesis. For a balanced parenthesis, positives can be adjacent where as a negative number should be of positive number in top of the stack.
Below is code:
import java.util.Stack;
public class Main {
public static void main (String [] args)
{
String value = "()(){}{}{()}";
System.out.println(Main.balancedParanthesis(value));
}
public static boolean balancedParanthesis(String s) {
char[] charArray=s.toCharArray();
int[] integerArray=new int[charArray.length];
// creating braces with equivalent numeric values
for(int i=0;i<charArray.length;i++) {
if(charArray[i]=='{') {
integerArray[i]=1;
}
else if(charArray[i]=='}') {
integerArray[i]=-1;
}
else if(charArray[i]=='[') {
integerArray[i]=2;
}
else if(charArray[i]==']') {
integerArray[i]=-2;
}
else if(charArray[i]=='(') {
integerArray[i]=3;
}
else {
integerArray[i]=-3;
}
}
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<charArray.length;i++) {
if(stack.isEmpty()) {
if(integerArray[i]<0) {
stack.push(integerArray[i]);
break;
}
stack.push(integerArray[i]);
}
else{
if(integerArray[i]>0) {
stack.push(integerArray[i]);
}
else {
if(stack.peek()==-(integerArray[i])) {
stack.pop();
}
else {
break;
}
}
}
}
return stack.isEmpty();
}
}
You can also use get(). Initially I believed it to only check if key existed.
>>> d = { 'a':1, 'b':2, 'c':{}}
>>> bool(d.get('c'))
False
>>> d['c']['e']=1
>>> bool(d.get('c'))
True
What I like with get is that it does not trigger an exception, so it makes it easy to traverse large structures.
Let me show you another way that works 100%. I will also add some padding for the example.
<div class = "container">
<div class = "flex-pad-x">
<div class = "flex-pad-y">
<div class = "flex-pad-y">
<div class = "flex-grow-y">
Content Centered
</div>
</div>
</div>
</div>
</div>
.container {
position: fixed;
top: 0px;
left: 0px;
bottom: 0px;
right: 0px;
width: 100%;
height: 100%;
}
.flex-pad-x {
padding: 0px 20px;
height: 100%;
display: flex;
}
.flex-pad-y {
padding: 20px 0px;
width: 100%;
display: flex;
flex-direction: column;
}
.flex-grow-y {
flex-grow: 1;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
As you can see we can achieve this with a few wrappers for control while utilising the flex-grow & flex-direction attribute.
1: When the parent "flex-direction" is a "row", its child "flex-grow" works horizontally. 2: When the parent "flex-direction" is "columns", its child "flex-grow" works vertically.
Hope this helps
Daniel
there seems to be incorrect info posted here. some people report on how to clear the Android builder cache (with task cleanBuildCache
) but do not seem to realize that said cache is independent of Gradle's build cache, AFAIK.
my understanding is that Android's cache predates (and inspired) Gradle's, but i could be wrong. whether the Android builder will be/was updated to use Gradle's cache and retire its own, i do not know.
EDIT: the Android builder cache is obsolete and has been eliminated. the Android Gradle plugin now uses Gradle's build cache instead. to control this cache you must now interact with Gradle's generic cache infrastructure.
TIP: search for Gradle's cache help online without mentioning the keyword 'android' to get help for the currently relevant cache.
EDIT 2: due to tir38's question in a comment below, i am testing using an Android Gradle plugin v3.4.2 project. the gradle cache is enabled by org.gradle.caching=true
in gradle.properties
. i do a couple of clean build
and the second time most tasks show FROM-CACHE
as their status, showing that the cache is working.
surprisingly, i have a cleanBuildCache
gradle task and a <user-home>/.android/build-cache/3.4.2/
directory, both hinting the existence of an Android builder cache.
i execute cleanBuildCache
and the 3.4.2/
directory is gone. next i do another clean build
:
FROM-CACHE
as their status and the build completed at cache-enabled speeds.3.4.2/
directory is recreated.3.4.2/
directory is empty (save for 2 hidden, zero length marker files).conclusions:
cleanBuildCache
does not clear or affect the build cache in any way.next, i disable the Gradle cache by removing org.gradle.caching=true
from gradle.properties
and i try a couple of clean build
:
3.4.2/
directory continues to be empty.more conclusions:
EDIT 3: user tir38 confirmed that the Android builder cache is obsolete and has been eliminated with this find. tir38 also created this issue. thanks!
I had this problem in some solutions on VS 2015 (not MVC though), and even in the same solution on one workstation but not on another. The errors started appeared after changing .NET version to 4.6 and referencing PCL.
The solution is simple: Close the solution and delete the hidden .vs folder in the same folder as the solution.
Adding the missing references as suggested in other answers also solves the problem, but the error remains solved even after you remove the references again.
As for TeamCity, I cannot say since my configuration never had a problem. But make sure that you reset the working catalog as a part of your debugging effort.
FromBody is a strange attribute in that the input POST values need to be in a specific format for the parameter to be non-null, when it is not a primitive type. (student here)
{"name":"John Doe", "age":18, "country":"United States of America"}
as the json. [FromBody]
attribute and try the solution. It should work for non-primitive types. (student)[FromBody]
attribute, the other option is to send the values in =Value
format, rather than key=value
format. This would mean your key value of student
should be an empty string... There are also other options to write a custom model binder for the student class and attribute the parameter with your custom binder.
In my case it was just a matter of:
Tools -> NuGet Package Manager -> Package Manager Settings -> Clear Cache
The problem was caused when I remapped a TFS folder.
You should be able to get this done using delegates, lambda expression
private void button2_Click(object sender, EventArgs e)
{
label1.Text = "waiting....";
Task<string> sCode = Task.Run(async () =>
{
string msg =await GenerateCodeAsync();
return msg;
});
label1.Text += sCode.Result;
}
private Task<string> GenerateCodeAsync()
{
return Task.Run<string>(() => GenerateCode());
}
private string GenerateCode()
{
Thread.Sleep(2000);
return "I m back" ;
}
This is because charset=utf8
should be without a space after application/json
. That will work fine. Use it like application/json;charset=utf-8
Below section add in to your web.config
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json"
publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
VS2019: Tools -> Nuget Package Manager -> Package Manager Setting -> in Package Restore section, check 2 options. After that, go to project packages folder and delete all child folders inside (for no longer any error) Then Rebuild solution, Nuget will redownload all packages and project should run without any reference.
Please check if you are were passing method as POST
instead as GET
.
if so you will get same error as a you posted above.
$http({
method: 'GET',
The request entity's media type 'text/plain' is not supported for this resource.
In here:
if (ValidationUtils.isNullOrEmpty(lastName)) {
registrationErrors.add(ValidationErrors.LAST_NAME);
}
if (!ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do
if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
registrationErrors.add(ValidationErrors.EMAIL);
}
or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.
You can also use
Update-Package -reinstall
to restore the NuGet packages on the Package Management Console in Visual Studio.
I Had the same problem.
The solution for me is:
You must have the same version of: Microsoft.ReportViewer.ProcessingObjectModel registred in C:\Windows\assembly\GAC_MSIL\Microsoft.ReportViewer.ProcessingObjectModel, like you have registraded in web.config in developer server:
In my case i was only registred the 13. version in my prodution server and i have the 12. version in developer server.
the solution is install the version 12. in the prodution server too
the version 12. :
Then now i have the version 12. in the prodution and the report work fine.
*** Remember to reset your IIS after instalation
First of all, write the following code:
#include <Mmsystem.h>
#include <mciapi.h>
//these two headers are already included in the <Windows.h> header
#pragma comment(lib, "Winmm.lib")
To open *.mp3:
mciSendString("open \"*.mp3\" type mpegvideo alias mp3", NULL, 0, NULL);
To play *.mp3:
mciSendString("play mp3", NULL, 0, NULL);
To play and wait until the *.mp3 has finished playing:
mciSendString("play mp3 wait", NULL, 0, NULL);
To replay (play again from start) the *.mp3:
mciSendString("play mp3 from 0", NULL, 0, NULL);
To replay and wait until the *.mp3 has finished playing:
mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
To play the *.mp3 and replay it every time it ends like a loop:
mciSendString("play mp3 repeat", NULL, 0, NULL);
If you want to do something when the *.mp3 has finished playing, then you need to RegisterClassEx
by the WNDCLASSEX
structure, CreateWindowEx
and process it's messages with the GetMessage, TranslateMessage and DispatchMessage functions in a while
loop and call:
mciSendString("play mp3 notify", NULL, 0, hwnd); //hwnd is an handle to the window returned from CreateWindowEx. If this doesn't work, then replace the hwnd with MAKELONG(hwnd, 0).
In the window procedure, add the case MM_MCINOTIFY:
The code in there will be executed when the mp3 has finished playing.
But if you program a Console Application and you don't deal with windows, then you can CreateThread
in suspend state by specifying the CREATE_SUSPENDED
flag in the dwCreationFlags
parameter and keep the return value in a static
variable and call it whatever you want. For instance, I call it mp3. The type of this static
variable is HANDLE
of course.
Here is the ThreadProc
for the lpStartAddress
of this thread:
DWORD WINAPI MP3Proc(_In_ LPVOID lpParameter) //lpParameter can be a pointer to a structure that store data that you cannot access outside of this function. You can prepare this structure before `CreateThread` and give it's address in the `lpParameter`
{
Data *data = (Data*)lpParameter; //If you call this structure Data, but you can call it whatever you want.
while (true)
{
mciSendString("play mp3 from 0 wait", NULL, 0, NULL);
//Do here what you want to do when the mp3 playback is over
SuspendThread(GetCurrentThread()); //or the handle of this thread that you keep in a static variable instead
}
}
All what you have to do now is to ResumeThread(mp3);
every time you want to replay your mp3 and something will happen every time it finishes.
You can #define play_my_mp3 ResumeThread(mp3);
to make your code more readable.
Of course you can remove the while (true)
, SuspendThread
and the from 0 codes, if you want to play your mp3 file only once and do whatever you want when it is over.
If you only remove the SuspendThread
call, then the sound will play over and over again and do something whenever it is over. This is equivalent to:
mciSendString("play mp3 repeat notify", NULL, 0, hwnd); //or MAKELONG(hwnd, 0) instead
in windows.
To pause the *.mp3 in middle:
mciSendString("pause mp3", NULL, 0, NULL);
and to resume it:
mciSendString("resume mp3", NULL, 0, NULL);
To stop it in middle:
mciSendString("stop mp3", NULL, 0, NULL);
Note that you cannot resume a sound that has been stopped, but only paused, but you can replay it by carrying out the play command. When you're done playing this *.mp3, don't forget to:
mciSendString("close mp3", NULL, 0, NULL);
All these actions also apply to (work with) wave files too, but with wave files, you can use "waveaudio" instead of "mpegvideo". Also you can just play them directly without opening them:
PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME);
If you don't want to specify an handle to a module:
sndPlaySound("*.wav", SND_FILENAME);
If you don't want to wait until the playback is over:
PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC);
To play the wave file over and over again:
PlaySound("*.wav", GetModuleHandle(NULL), SND_FILENAME | SND_ASYNC | SND_LOOP);
//or
sndPlaySound("*.wav", SND_FILENAME | SND_ASYNC | SND_LOOP);
Note that you must specify both the SND_ASYNC
and SND_LOOP
flags, because you never going to wait until a sound, that repeats itself countless times, is over!
Also you can fopen
the wave file and copy all it's bytes to a buffer (an enormous/huge (very big) array of bytes) with the fread
function and then:
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC);
//or
PlaySound(buffer, GetModuleHandle(NULL), SND_MEMORY | SND_ASYNC | SND_LOOP);
//or
sndPlaySound(buffer, SND_MEMORY);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC);
//or
sndPlaySound(buffer, SND_MEMORY | SND_ASYNC | SND_LOOP);
Either OpenFile
or CreateFile
or CreateFile2
and either ReadFile
or ReadFileEx
functions can be used instead of fopen
and fread
functions.
Hope this fully answers perfectly your question.
I think you must have named the file as nltk.py (or the folder consists of a file with that name) so change it to any other name and try executing it....
I had this when build my application with "All cpu" target while it referenced a 3rd party x64-only (managed) dll.
For me : I have a white space in my path's folder name G:\Other Imp Projects\Mi.....
Remove white space from folder
Example: Other Imp Projects
->> Other_Imp_Projects
add Quote (""
) for your path.
Example: mkdir "$(ProjectDir)$(OutDir)Configurations"
//see double quotes
Coffeescript doesn't support javascript ternary operator. Here is the reason from the coffeescript author:
I love ternary operators just as much as the next guy (probably a bit more, actually), but the syntax isn't what makes them good -- they're great because they can fit an if/else on a single line as an expression.
Their syntax is just another bit of mystifying magic to memorize, with no analogue to anything else in the language. The result being equal, I'd much rather have
if/elses
always look the same (and always be compiled into an expression).So, in CoffeeScript, even multi-line ifs will compile into ternaries when appropriate, as will if statements without an else clause:
if sunny go_outside() else read_a_book(). if sunny then go_outside() else read_a_book()
Both become ternaries, both can be used as expressions. It's consistent, and there's no new syntax to learn. So, thanks for the suggestion, but I'm closing this ticket as "wontfix".
Please refer to the github issue: https://github.com/jashkenas/coffeescript/issues/11#issuecomment-97802
NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];
or use
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);
The first push should be a:
git push -u origin branchname
That would make sure:
origin
',simple
'Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.
The for loop is getting one extra run. Change
for (x=0;x<=InvForm.SelBranch.length;x++)
to
for (x=0; x < InvForm.SelBranch.length; x++)
Using only standard python libs:
from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()
Works on Windows (if you are on drive C), Mac or Linux
Alternatively, you could remove one line with an immediate invocation:
from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()
For those experiencing this error on CI/CD, adding the line below worked for me on my GitHub Actions CI/CD workflow right after running pip install pyflakes diff-cover
:
git fetch origin master:refs/remotes/origin/master
This is a snippet of the solution from the diff-cover github repo:
Solution: diff-cover matches source files in the coverage XML report with source files in the git diff. For this reason, it's important that the relative paths to the files match. If you are using coverage.py to generate the coverage XML report, then make sure you run diff-cover from the same working directory.
I got the solution on the links below. It is a documented diff-cover
error.
https://diff-cover.readthedocs.io/en/latest//README.html https://github.com/Bachmann1234/diff_cover/blob/master/README.rst
Hope this helps :-).
This function should work whichever the locale and currency settings :
function getNumPrice(price, decimalpoint) {
var p = price.split(decimalpoint);
for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
return p.join('.');
}
This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>
).
You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc
:
int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
buf[i] = (int*) malloc(N * sizeof(int));
and then you can reference buf[3][5]
or whatever.
I was able to solve "ORA-00604: error" by Droping with purge.
DROP TABLE tablename PURGE
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em
's or %
.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
You can also use DOM to do so. Say you have a function you call like this:
function disable_scroll() {
document.body.style.overflow="hidden";
}
And that's all there is to it! Hope this helps in addition to all the other answers!
The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:
;WITH sumCTE
AS
(
SELECT Rel.t2ID, SUM(Price) price
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
GROUP
BY Rel.t2ID
)
,maxCTE
AS
(
SELECT Rel.t2ID, Rel.t1ID,
ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM @t2 AS T2
JOIN sumCTE AS sumT1
ON sumT1.t2ID = t2.ID
JOIN maxCTE AS maxT1
ON maxT1.t2ID = t2.ID
JOIN @t1 AS T1
ON T1.ID = maxT1.t1ID
WHERE maxT1.PriceList = 1
You can't pull in blocks from an included file into a child template to override the parent template's blocks. However, you can specify a parent in a variable and have the base template specified in the context.
From the documentation:
{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
Instead of separate "page1.html" and "page2.html", put {% extends base_template %}
at the top of "commondata.html". And then in your view, define base_template
to be either "base1.html" or "base2.html".
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
This is the favicon and is explained in the link.
e.g. from W3C
<link rel="icon"
type="image/png"
href="http://example.com/myicon.png">
Plus, of course the image file in the appropriate place.
I had luck with this:
<Route
path="/example"
component={() => {
global.window && (global.window.location.href = 'https://example.com');
return null;
}}
/>
Although the accepted answer works, you should really be using python's json
module:
import json
score=[1,2,3,4,5]
with open("file.json", 'w') as f:
# indent=2 is not needed but makes the file human-readable
json.dump(score, f, indent=2)
with open("file.json", 'r') as f:
score = json.load(f)
print(score)
Advantages:
json
is a widely adopted and standardized data format, so non-python programs can easily read and understand the json filesjson
files are human-readablejson
file (as long as all the contents are serializable).Disadvantages:
hdf5
is for).When to use json
vs pickle
:
pickle
pickle
.json
json
Common use cases:
node.js
uses a package.json
file to track project details, dependencies, scripts, etc ...)REST
APIs use json
to transmit and receive datacsv
, xml
or yaml
filesIf you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [(
brackets which wrap the variable.
If you know x
and y
are both strings, using ===
is not strictly necessary, but is still good practice.
Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string
rather than an actual string, which may complicate things.
Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===
. Just go with that.
If you are really like to know that handle CSV files perfectly in Java, it's not good to try to implement CSV reader/writer by yourself. Check below out.
http://opencsv.sourceforge.net/
When your CSV document includes double-quotes or newlines, you will face difficulties.
To learn object-oriented approach at first, seeing other implementation (by Java) will help you. And I think it's not good way to manage one row in a List. CSV doesn't allow you to have difference column size.
Export should be specific about which version of GCC/G++ to use, because if user had multiple compiler version, it would not compile successfully.
export CC=path_of_gcc/gcc-version
export CXX=path_of_g++/g++-version
cmake path_of_project_contain_CMakeList.txt
make
In case project use C++11 this can be handled by using -std=C++-11
flag in CMakeList.txt
Check this out with IsNullOrEmpty and IsNullOrwhiteSpace
string sTestes = "I like sweat peaches";
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < 5000000; i++)
{
for (int z = 0; z < 500; z++)
{
var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
}
}
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);
Console.ReadLine();
You'll see that IsNullOrWhiteSpace is much slower :/
I am using this and it is working fine.
{{1288323623006 | date:'medium'}}: Oct 29, 2010 9:10:23 AM
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}: 2010-10-29 09:10:23 +0530
{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}: 10/29/2010 @ 9:10AM
{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}: 10/29/2010 at 9:10AM
you can use this code inside col-md-3 , col-md-9
.col-side-right{
flex: 0 0 20% !important;
max-width: 20%;
}
.col-side-left{
flex: 0 0 80%;
max-width: 80%;
}
There are two approaches that I know of. The first is to tell the browser not to cache the page. Setting the Response to no cache takes care of that, however as you suspect the browser will often ignore this directive. The other approach is to set the date time of your response to a point in the future. I believe all browsers will correct this to the current time when they add the page to the cache, but it will show the page as newer when the comparison is made. I believe there may be some cases where a comparison is not made. I am not sure of the details and they change with each new browser release. Final note I have had better luck with pages that "refresh" themselves (another response directive). The refresh seems less likely to come from the cache.
Hope that helps.
https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5?view=netframework-4.7.2
using System;
using System.Security.Cryptography;
using System.Text;
static string GetMd5Hash(string input)
{
using (MD5 md5Hash = MD5.Create())
{
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
}
// Verify a hash against a string.
static bool VerifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = GetMd5Hash(input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
return 0 == comparer.Compare(hashOfInput, hash);
}
Just json.dumps will fix the problem
json.dumps function actually converts all the unicode literals to string literals and it will be easy for us to load the data either in json file or csv file.
sample code:
import json
EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
result_list = json.dumps(EmployeeList)
print result_list
output: ["1001", "Karick", "14-12-2020", "1$"]
Since a lot of people search Java topics for Groovy answers, here's how you can do it in Groovy:
dev map = new HashMap<String, Integer>()
map.put("key1", 3)
map.merge("key1", 1) {a, b -> a + b}
map.merge("key2", 1) {a, b -> a + b}
This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=?
to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"}
and getting the error.
This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})
Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:
$ret['foo'] = "bar";
finish();
function finish() {
header("content-type:application/json");
if ($_GET['callback']) {
print $_GET['callback']."(";
}
print json_encode($GLOBALS['ret']);
if ($_GET['callback']) {
print ")";
}
exit;
}
Hopefully that will help someone in the future.
Unless you have Excel installed on the Server/PC or use an external tool (which is possible without using Excel Interop, see Create Excel (.XLS and .XLSX) file from C#), it will fail. Using the interop requires Excel to be installed.
The variable name you're looking for is ansible_ssh_private_key_file
.
You should set it at 'vars' level:
in the inventory file:
myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
in the host_vars
:
# hosts_vars/myHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
# hosts_vars/myOtherHost.yml
ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
in a group_vars
file if you use the same key for a group of hosts
in the vars
section of your play:
- hosts: myHost
remote_user: ubuntu
vars_files:
- vars.yml
vars:
ansible_ssh_private_key_file: "{{ key1 }}"
tasks:
- name: Echo a hello message
command: echo hello
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
Use nargs='?'
(or nargs='*'
if you need more than one dir)
parser.add_argument('dir', nargs='?', default=os.getcwd())
extended example:
>>> import os, argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-v', action='store_true')
_StoreTrueAction(option_strings=['-v'], dest='v', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('dir', nargs='?', default=os.getcwd())
_StoreAction(option_strings=[], dest='dir', nargs='?', const=None, default='/home/vinay', type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args('somedir -v'.split())
Namespace(dir='somedir', v=True)
>>> parser.parse_args('-v'.split())
Namespace(dir='/home/vinay', v=True)
>>> parser.parse_args(''.split())
Namespace(dir='/home/vinay', v=False)
>>> parser.parse_args(['somedir'])
Namespace(dir='somedir', v=False)
>>> parser.parse_args('somedir -h -v'.split())
usage: [-h] [-v] [dir]
positional arguments:
dir
optional arguments:
-h, --help show this help message and exit
-v
Create a directory named like Images
and put all the images that will be rendered by the Markdown.
For example, put example.png
into Images
.
To load example.png
that was located under the Images
directory before.
![title](Images/example.png)
Note : Images
directory must be located under the same directory of your markdown text file which has .md
extension.
In SQL 2005:
select object_name(object_id), name
from sys.columns
where is_identity = 1
[start:stop:step]
So If you want to take only 100 first character, use your_string[0:100]
or your_string[:100]
If you want to take only the character at even position, use your_string[::2]
The "default values" for start is 0, for stop - len of string, and for step - 1. So when you don't provide one of its and put ':', it'll use it default value.
I had the same problem and while TechZen's answer may indeed be amazing I found it hard to apply to my situation.
Eventually I resolved the issue by linking the label via the Controller listed under Objects (highlighted in the image below) rather then via the File Owner.
Hope this helps.
.ix
indexer works okay for pandas version prior to 0.20.0, but since pandas 0.20.0, the .ix
indexer is deprecated, so you should avoid using it. Instead, you can use .loc
or iloc
indexers. You can solve this problem by:
mask = df.my_channel > 20000
column_name = 'my_channel'
df.loc[mask, column_name] = 0
Or, in one line,
df.loc[df.my_channel > 20000, 'my_channel'] = 0
mask
helps you to select the rows in which df.my_channel > 20000
is True
, while df.loc[mask, column_name] = 0
sets the value 0 to the selected rows where mask
holds in the column which name is column_name
.
Update:
In this case, you should use loc
because if you use iloc
, you will get a NotImplementedError
telling you that iLocation based boolean indexing on an integer type is not available.
In your parent window:
var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);
Then in childwindow.html:
var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
var keyValuePairs = keyValue.split(/=/);
var key = keyValuePairs[0];
var value = keyValuePairs[1];
parameters[key] = value;
}
alert(parameters['yourKey']);
There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');
For each of your dataframe column, you could get quantile with:
q = df["col"].quantile(0.99)
and then filter with:
df[df["col"] < q]
If one need to remove lower and upper outliers, combine condition with an AND statement:
q_low = df["col"].quantile(0.01)
q_hi = df["col"].quantile(0.99)
df_filtered = df[(df["col"] < q_hi) & (df["col"] > q_low)]
<merge/>
is useful because it can get rid of unneeded ViewGroups, i.e. layouts that are simply used to wrap other views and serve no purpose themselves.
For example, if you were to <include/>
a layout from another file without using merge, the two files might look something like this:
layout1.xml:
<FrameLayout>
<include layout="@layout/layout2"/>
</FrameLayout>
layout2.xml:
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
which is functionally equivalent to this single layout:
<FrameLayout>
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
</FrameLayout>
That FrameLayout in layout2.xml may not be useful. <merge/>
helps get rid of it. Here's what it looks like using merge (layout1.xml doesn't change):
layout2.xml:
<merge>
<TextView />
<TextView />
</merge>
This is functionally equivalent to this layout:
<FrameLayout>
<TextView />
<TextView />
</FrameLayout>
but since you are using <include/>
you can reuse the layout elsewhere. It doesn't have to be used to replace only FrameLayouts - you can use it to replace any layout that isn't adding something useful to the way your view looks/behaves.
For what it's worth automatic signing failed every time until I just manually deleted local profiles in: ~/Library/MobileDevice/Provisioning Profiles
After that automatic signing worked perfectly and it got the right profiles from Apple's servers.
This was affecting only some builds, notably the ones for which I had manually created profiles for watch app.
Let's say you're using this HTML5 layout:
<html>
<body>
<header>
<nav><ul>...</ul></nav>
</header>
<article>
<ul>...</ul>
</article>
<footer>
<ul>...</ul>
</footer>
</body>
</html>
You could say in your CSS:
header ul, footer ul, nav ul { list-style-type: none; }
If you're using HTML 4, assign IDs to your DIVs (instead of using the new fancy-pants elements) and change this to:
#header ul, #footer ul, #nav ul { list-style-type: none; }
If you're using a CSS reset stylesheet (like Eric Meyer's), you would actually have to give the list style back, since the reset removes the list style from all lists.
#content ul { list-style-type: disc; margin-left: 1.5em; }
FYI,
I've seen this strange behavior before in jQuery widgets. Part of the key is to put the updatepanel inside the modal. This allows the DOM of the updatepanel to "stay with" the modal (however it works with bootstrap).
Got better solution:
$('#element').resizable({
stop: function( event, ui ) {
$('#element').height(ui.originalSize.height);
}
});
#include <windows.h>
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
cout << "QueryPerformanceFrequency failed!\n";
PCFreq = double(li.QuadPart)/1000.0;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return double(li.QuadPart-CounterStart)/PCFreq;
}
int main()
{
StartCounter();
Sleep(1000);
cout << GetCounter() <<"\n";
return 0;
}
This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).
The StartCounter()
function records the number of ticks the performance counter has in the CounterStart
variable. The GetCounter()
function returns the number of milliseconds since StartCounter()
was last called as a double, so if GetCounter()
returns 0.001 then it has been about 1 microsecond since StartCounter()
was called.
If you want to have the timer use seconds instead then change
PCFreq = double(li.QuadPart)/1000.0;
to
PCFreq = double(li.QuadPart);
or if you want microseconds then use
PCFreq = double(li.QuadPart)/1000000.0;
But really it's about convenience since it returns a double.
Because Firefox does not support mp3 format. To make this work with Firefox, you should use the ogg format.
For Meteor, this can be solved by changing twbs:[email protected] to twbs:[email protected] in .versions
$(this).closest('div')
is same as $(this).parents('div').eq(0)
.
If you want to just check if they are identical or not, a == b
should give you true / false with ordering taken into account.
In case you want to compare elements, you can use numpy for comparison
c = (numpy.array(a) == numpy.array(b))
Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.
EDIT: Sorry, I should have tested better before. This should work:
new File(new URI(androidURI.toString()));
URI is java.net.URI.
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
Run: npm link typescript
if you installed globally
But if you have not installed typescript try this command: npm install typescript
Also if the goal is only to access the files on the phone. There is a File Explorer that is accessible from the Eclipse DDMS perspective. It lets you copy file from and to the device. So you can always get the file, modify it and put it back on the device. Of course it enables to access only the files that are not read protected.
If you don't see the File Explorer, from the DDMS perspective, go in "Window" -> "Show View" -> "File Explorer".
The fact that your method does not use the self
argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.
No, #region does not exist in the T-SQL language.
You can get code-folding using begin-end blocks:
-- my region begin -- code goes here end
I'm not sure I'd recommend using them for this unless the code cannot be acceptably refactored by other means though!
You have a few options here:
Context
as an argument to FeedAdapter and keep it as class fieldContext
when you need it. I strongly suggest reading about it. There is a great tool for that -- Dagger by SquareGet it from any View
object. In your case this might work for you:
holder.pub_image.getContext()
As pub_image
is a ImageView
.
Try this:
$.ajax({
beforeSend: function (xhr){
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","text/json");
},
type: "POST",
//........
});
If you want to append a file instead of constantly making a new one/deleting the old one's content, use double >
marks. A single >
mark will overwrite all the file's content.
Overwrite file
MyCommand.exe>file.txt
^This will open file.txt if it already exists and overwrite the data, or create a new file and fill it with your output
Append file from its end-point
MyCommand.exe>>file.txt
^This will append file.txt from its current end of file if it already exists, or create a new file and fill it with your output.
My batch-fu has improved over time, so here's some minor updates.
If you want to differentiate between error output and normal output for a program that correctly uses Standard streams, STDOUT
/STDERR
, you can do this with minor changes to the syntax. I'll just use >
for overwriting for these examples, but they work perfectly fine with >>
for append, in regards to file-piping output re-direction.
The 1
before the >>
or >
is the flag for STDOUT. If you need to actually output the number one or two before the re-direction symbols, this can lead to strange, unintuitive errors if you don't know about this mechanism. That's especially relevant when outputting a single result number into a file. 2
before the re-direction symbols is for STDERR.
Now that you know that you have more than one stream available, this is a good time to show the benefits of outputting to nul
. Now, outputting to nul
works the same way conceptually as outputting to a file. You don't see the content in your console. Instead of it going to file or your console output, it goes into the void.
STDERR to file and suppress STDOUT
MyCommand.exe 1>nul 2>errors.txt
STDERR to file to only log errors. Will keep STDOUT in console
MyCommand.exe 2>errors.txt
STDOUT to file and suppress STDERR
MyCommand.exe 1>file.txt 2>nul
STDOUT only to file. Will keep STDERR in console
MyCommand.exe 1>file.txt
STDOUT to one file and STDERR to another file
MyCommand.exe 1>stdout.txt 2>errors.txt
The only caveat I have here is that it can create a 0-byte file for an unused stream if one of the streams never gets used. Basically, if no errors occurred, you might end up with a 0-byte errors.txt file.
I started noticing weird behavior when writing console apps that wrote directly to STDERR
, and realized that if I wanted my error output to go to the same file when using basic piping, I either had to combine streams 1
and 2
or just use STDOUT
. The problem with that problem is I didn't know about the correct way to combine streams, which is this:
%command% > outputfile 2>&1
Therefore, if you want all STDOUT and STDERR piped into the same stream, make sure to use that like so:
MyCommand.exe > file.txt 2>&1
The redirector actually defaults to 1>
or 1>>
, even if you don't explicitly use 1
in front of it if you don't use a number in front of it, and the 2>&1
combines the streams.
If you want to completely suppress STDOUT and STDERR you can do it this way. As a warning not all text pipes use STDOUT and STDERR but it will work for a vast majority of use cases.
STD* to null
MyCommand.exe>nul 2>&1
If all you want is the command output from a CMD or Powershell session that you just finished up, or any other shell for that matter you can usually just select that console from that session, CTRL + A to select all content, then CTRL + C to copy the content. Then you can do whatever you like with the copied content while it's in your clipboard.
I think your EmpID
column is string and you forget to use ' '
in your value.
Because when you write EmpID=" + id.Text
, your command looks like EmpID = 12345
instead of EmpID = '12345'
Change your SqlCommand
to
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);
Or as a better way you can (and should) always use parameterized queries
. This kind of string concatenations are open for SQL Injection
attacks.
SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);
I think your EmpID
column keeps your employee id's, so it's type should some numerical type instead of character.
I recently had the requirement to use JNDI with an embedded Tomcat in Spring Boot.
Actual answers give some interesting hints to solve my task but it was not enough as probably not updated for Spring Boot 2.
Here is my contribution tested with Spring Boot 2.0.3.RELEASE.
Specifying a datasource available in the classpath at runtime
You have multiple choices :
If you don't specify anyone of them, with the default configuration the instantiation of the datasource will throw an exception :
Caused by: javax.naming.NamingException: Could not create resource factory instance at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:50) at org.apache.naming.factory.FactoryBase.getObjectInstance(FactoryBase.java:90) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:321) at org.apache.naming.NamingContext.lookup(NamingContext.java:839) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org.apache.naming.NamingContext.lookup(NamingContext.java:827) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org.apache.naming.NamingContext.lookup(NamingContext.java:827) at org.apache.naming.NamingContext.lookup(NamingContext.java:159) at org.apache.naming.NamingContext.lookup(NamingContext.java:827) at org.apache.naming.NamingContext.lookup(NamingContext.java:173) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:163) at javax.naming.InitialContext.lookup(InitialContext.java:417) at org.springframework.jndi.JndiTemplate.lambda$lookup$0(JndiTemplate.java:156) at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:91) at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:156) at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178) at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:96) at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:114) at org.springframework.jndi.JndiObjectTargetSource.getTarget(JndiObjectTargetSource.java:140) ... 39 common frames omitted Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory at java.net.URLClassLoader.findClass(URLClassLoader.java:381) at java.lang.ClassLoader.loadClass(ClassLoader.java:424) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) at java.lang.ClassLoader.loadClass(ClassLoader.java:357) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:264) at org.apache.naming.factory.ResourceFactory.getDefaultFactory(ResourceFactory.java:47) ... 58 common frames omitted
To use Apache JDBC datasource, you don't need to add any dependency but you have to change the default factory class to org.apache.tomcat.jdbc.pool.DataSourceFactory
.
You can do it in the resource declaration :
resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
I will explain below where add this line.
To use DBCP 2 datasource a dependency is required:
<dependency> <groupId>org.apache.tomcat</groupId> <artifactId>tomcat-dbcp</artifactId> <version>8.5.4</version> </dependency>
Of course, adapt the artifact version according to your Spring Boot Tomcat embedded version.
To use HikariCP, add the required dependency if not already present in your configuration (it may be if you rely on persistence starters of Spring Boot) such as :
<dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>3.1.0</version> </dependency>
and specify the factory that goes with in the resource declaration:
resource.setProperty("factory", "com.zaxxer.hikari.HikariJNDIFactory");
Datasource configuration/declaration
You have to customize the bean that creates the TomcatServletWebServerFactory
instance.
Two things to do :
enabling the JNDI naming which is disabled by default
creating and add the JNDI resource(s) in the server context
For example with PostgreSQL and a DBCP 2 datasource, do that :
@Bean
public TomcatServletWebServerFactory tomcatFactory() {
return new TomcatServletWebServerFactory() {
@Override
protected TomcatWebServer getTomcatWebServer(org.apache.catalina.startup.Tomcat tomcat) {
tomcat.enableNaming();
return super.getTomcatWebServer(tomcat);
}
@Override
protected void postProcessContext(Context context) {
// context
ContextResource resource = new ContextResource();
resource.setName("jdbc/myJndiResource");
resource.setType(DataSource.class.getName());
resource.setProperty("driverClassName", "org.postgresql.Driver");
resource.setProperty("url", "jdbc:postgresql://hostname:port/dbname");
resource.setProperty("username", "username");
resource.setProperty("password", "password");
context.getNamingResources()
.addResource(resource);
}
};
}
Here the variants for Tomcat JDBC and HikariCP datasource.
In postProcessContext()
set the factory property as explained early for Tomcat JDBC ds :
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
//...
resource.setProperty("factory", "org.apache.tomcat.jdbc.pool.DataSourceFactory");
//...
context.getNamingResources()
.addResource(resource);
}
};
and for HikariCP :
@Override
protected void postProcessContext(Context context) {
ContextResource resource = new ContextResource();
//...
resource.setProperty("factory", "com.zaxxer.hikari.HikariDataSource");
//...
context.getNamingResources()
.addResource(resource);
}
};
Using/Injecting the datasource
You should now be able to lookup the JNDI ressource anywhere by using a standard InitialContext
instance :
InitialContext initialContext = new InitialContext();
DataSource datasource = (DataSource) initialContext.lookup("java:comp/env/jdbc/myJndiResource");
You can also use JndiObjectFactoryBean
of Spring to lookup up the resource :
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.afterPropertiesSet();
DataSource object = (DataSource) bean.getObject();
To take advantage of the DI container you can also make the DataSource
a Spring bean :
@Bean(destroyMethod = "")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.afterPropertiesSet();
return (DataSource) bean.getObject();
}
And so you can now inject the DataSource in any Spring beans such as :
@Autowired
private DataSource jndiDataSource;
Note that many examples on the internet seem to disable the lookup of the JNDI resource on startup :
bean.setJndiName("java:comp/env/jdbc/myJndiResource");
bean.setProxyInterface(DataSource.class);
bean.setLookupOnStartup(false);
bean.afterPropertiesSet();
But I think that it is helpless as it invokes just after afterPropertiesSet()
that does the lookup !
This excerpt is from the following awesome post.
ERROR – something terribly wrong had happened, that must be investigated immediately. No system can tolerate items logged on this level. Example: NPE, database unavailable, mission critical use case cannot be continued.
WARN – the process might be continued, but take extra caution. Actually I always wanted to have two levels here: one for obvious problems where work-around exists (for example: “Current data unavailable, using cached values”) and second (name it: ATTENTION) for potential problems and suggestions. Example: “Application running in development mode” or “Administration console is not secured with a password”. The application can tolerate warning messages, but they should always be justified and examined.
INFO – Important business process has finished. In ideal world, administrator or advanced user should be able to understand INFO messages and quickly find out what the application is doing. For example if an application is all about booking airplane tickets, there should be only one INFO statement per each ticket saying “[Who] booked ticket from [Where] to [Where]“. Other definition of INFO message: each action that changes the state of the application significantly (database update, external system request).
DEBUG – Developers stuff. I will discuss later what sort of information deserves to be logged.
TRACE – Very detailed information, intended only for development. You might keep trace messages for a short period of time after deployment on production environment, but treat these log statements as temporary, that should or might be turned-off eventually. The distinction between DEBUG and TRACE is the most difficult, but if you put logging statement and remove it after the feature has been developed and tested, it should probably be on TRACE level.
PS: Read TRACE as VERBOSE
A perfect easy way
var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
var newProperty = 'getThisFromUser';
data[newProperty] = 4;
console.log(data);
If you want to apply it on an array of data (ES6/TS version)
const data = [
{ 'PropertyA': 1, 'PropertyB': 2, 'PropertyC': 3 },
{ 'PropertyA': 11, 'PropertyB': 22, 'PropertyC': 33 }
];
const newProperty = 'getThisFromUser';
data.map( (d) => d[newProperty] = 4 );
console.log(data);
Collapse all : CTRL + SHIFT + /
Expand all code blocks : CTRL + *
You can use the properties tab in eclipse to set various values.
here are all the possible values
Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
In my case (Oracle), it's WHERE REGEXP_LIKE(column, 'regex.*')
. See here:
SQL Function
Description
REGEXP_LIKE
This function searches a character column for a pattern. Use this function in the WHERE clause of a query to return rows matching the regular expression you specify.
...
REGEXP_REPLACE
This function searches for a pattern in a character column and replaces each occurrence of that pattern with the pattern you specify.
...
REGEXP_INSTR
This function searches a string for a given occurrence of a regular expression pattern. You specify which occurrence you want to find and the start position to search from. This function returns an integer indicating the position in the string where the match is found.
...
REGEXP_SUBSTR
This function returns the actual substring matching the regular expression pattern you specify.
(Of course, REGEXP_LIKE only matches queries containing the search string, so if you want a complete match, you'll have to use '^$'
for a beginning (^
) and end ($
) match, e.g.: '^regex.*$'
.)
This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:
I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM")
, drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".
I was able to get past this by using the Array keyword instead of empty brackets:
const enhancers: Array<any> = [];
Use:
if (typeof devToolsExtension === 'function') {
enhancers.push(devToolsExtension())
}
The config file is just an XML file, you can open it by:
private static XmlDocument loadConfigDocument()
{
XmlDocument doc = null;
try
{
doc = new XmlDocument();
doc.Load(getConfigFilePath());
return doc;
}
catch (System.IO.FileNotFoundException e)
{
throw new Exception("No configuration file found.", e);
}
catch (Exception ex)
{
return null;
}
}
and later retrieving values by:
// retrieve appSettings node
XmlNode node = doc.SelectSingleNode("//appSettings");
You can use localStorage
for the purpose.
Steps:
On Redhat 64bit, this solved problem for me.
ifconfig $1|sed -n 2p|awk '{ print $2 }'|awk -F : '{ print $2 }'
Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.
Actions builder = new Actions(driver);
builder.keyDown(Keys.CONTROL)
.click(someElement)
.moveByOffset( 10, 25 );
.click(someOtherElement)
.keyUp(Keys.CONTROL).build().perform();
If you want a Toast
to persist, I found you can hack your way around it by having a Timer
call toast.show()
repeatedly (every second or so should do). Calling show()
doesn't break anything if the Toast
is already showing, but it does refresh the amount of time it stays on the screen.
%%timeit
final_df.columns.values.tolist()
948 ns ± 19.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
list(final_df.columns)
14.2 µs ± 79.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
list(final_df.columns.values)
1.88 µs ± 11.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
final_df.columns.tolist()
12.3 µs ± 27.4 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
%%timeit
list(final_df.head(1).columns)
163 µs ± 20.6 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
According to this page.
NOTE: The accepted answer works for associative arrays, but it will not work as expected with indexed arrays (explained below). If you want to compare either of them, then use this solution. Also, this function may not works with multidimensional arrays (due to the nature of array_diff function).
Testing two indexed arrays, which elements are in different order, using $a == $b
or $a === $b
fails, for example:
<?php
(array("x","y") == array("y","x")) === false;
?>
That is because the above means:
array(0 => "x", 1 => "y")
vs. array(0 => "y", 1 => "x")
.
To solve that issue, use:
<?php
function array_equal($a, $b) {
return (
is_array($a)
&& is_array($b)
&& count($a) == count($b)
&& array_diff($a, $b) === array_diff($b, $a)
);
}
?>
Comparing array sizes was added (suggested by super_ton) as it may improve speed.
You need to use convert in order by as well:
SELECT Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)
I think cURL doesn't work with WAMP 2.2e. I tried all your solutions, but it still did not work. I got the previous version, (2.2d) and it works.
So just download the previous version :D
Also u can consider this
$('#select_2').find('option:selected').text();
which might be a little faster solution though I am not sure.
You had the identity
node as a child of authentication
node. That was the issue. As in the example above, authentication
and identity
nodes must be children of the system.web
node
Here's my way to find file names that contain some content that I'm interested in, just a single bash line that nicely handles spaces in filenames too:
find . -name \*.xml | while read i; do grep '<?xml' "$i" >/dev/null; [ $? == 0 ] && echo $i; done
Are you escaping it with \
?
/\[/
Here's a helpful resource to get started with Regular Expressions:
A corresponding cross for ✓ ✓
would be ✗ ✗
I think (Dingbats).
Depending on the boost version libboost-system comes with the -mt suffix which should indicate the libraries multithreading capability.
So if -lboost_system
cannot be found by the linker try -lboost_system-mt
.
The answer here is not clear, so I wanted to add more detail.
Using the link provided above, I performed the following step.
In my XML config manager I changed the "Provider" to SQLOLEDB.1 rather than SQLNCLI.1. This got me past this error.
This information is available at the link the OP posted in the Answer.
The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/
np.max
is just an alias for np.amax
. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis
argument and will find the maximum value along an axis of the input array (returning a new array).
>>> a = np.array([[0, 1, 6],
[2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])
The default behaviour of np.maximum
is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:
>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])
But np.maximum
is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):
>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])
This is not possible with np.max
.
You can make np.maximum
imitate np.max
to a certain extent when using np.maximum.reduce
:
>>> np.maximum.reduce(d)
9
>>> np.max(d)
9
Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max()
actually calls np.maximum.reduce
to do the computation.
IN this answer when i say a file i mean the location in memory
All the data that is saved is stored in memory using a data structure called inodes Every inode has a inodenumber.The inode number is used to access the inode.All the hard links to a file may have different names but share the same inode number.Since all the hard links have the same inodenumber(which inturn access the same inode),all of them point to the same physical memory.
A symbolic link is a special kind of file.Since it is also a file it will have a file name and an inode number.As said above the inode number acceses an inode which points to data.Now what makes a symbolic link special is that the inodenumbers in symbolic links access those inodes which point to "a path" to another file.More specifically the inode number in symbolic link acceses those inodes who point to another hard link.
when we are moving,copying,deleting a file in GUI we are playing with the hardlinks of the file not the physical memory.when we delete a file we are deleting the hardlink of the file. we are not wiping out the physical memory.If all the hardlinks to file are deleted then it will not be possible to access the data stored although it may still be present in memory
The usual way to test for a NaN is to see if it's equal to itself:
def isNaN(num):
return num != num
Section 6.5.8.6 of the C standard says:
Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.) The result has type int.
Alternatively referred to as a fixed space or hard space, non-breaking space (NBSP) is used in programming and word processing to create a space in a line that cannot be broken by word wrap.
With HTML,
allows you to create multiple spaces that are visible on a web page and not only in the source code.
You can also invoke cmake itself to do this in a cross-platform way:
cmake -E env EnvironmentVariableName="Hello World" cmake ..
env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...
Run command in a modified environment.
Just be aware that this may only work the first time. If CMake re-configures with one of the consecutive builds (you just call e.g. make
, one CMakeLists.txt
was changed and CMake runs through the generation process again), the user defined environment variable may not be there anymore (in comparison to system wide environment variables).
So I transfer those user defined environment variables in my projects into a CMake cached variable:
cmake_minimum_required(VERSION 2.6)
project(PrintEnv NONE)
if (NOT "$ENV{EnvironmentVariableName}" STREQUAL "")
set(EnvironmentVariableName "$ENV{EnvironmentVariableName}" CACHE INTERNAL "Copied from environment variable")
endif()
message("EnvironmentVariableName = ${EnvironmentVariableName}")
Reference
import codecs
decode_hex = codecs.getdecoder("hex_codec")
# for an array
msgs = [decode_hex(msg)[0] for msg in msgs]
# for a string
string = decode_hex(string)[0]
I'm late to the party but would like to share the solution I found to the same issue: Specifically, I was looking to do sequential combinations, so for "STAR" I wanted "STAR", "TA", "AR", but not "SR".
lst = [S, T, A, R]
lstCombos = []
for Length in range(0,len(lst)+1):
for i in lst:
lstCombos.append(lst[lst.index(i):lst.index(i)+Length])
Duplicates can be filtered with adding in an additional if before the last line:
lst = [S, T, A, R]
lstCombos = []
for Length in range(0,len(lst)+1):
for i in lst:
if not lst[lst.index(i):lst.index(i)+Length]) in lstCombos:
lstCombos.append(lst[lst.index(i):lst.index(i)+Length])
If for some reason this returns blank lists in the output, which happened to me, I added:
for subList in lstCombos:
if subList = '':
lstCombos.remove(subList)
If the server resides on a remote machine, make sure the file in in the remote machine and not in your local machine.
If the file is in the same machine where the mysql server is, make sure the mysql user has permissions to read/write the file, or copy teh file into the mysql schema directory:
In my case in ubuntu it was: /var/lib/mysql/db_myschema/myfile.csv
Also, not relative to this problem, but if you have problems with the new lines, use sublimeTEXT to change the line endings to WINDOWS format, save the file and retry.
I had similar problem when using Tomcat6.x and none of the advices I found was helping.
At the end I deleted work
folder (of Tomcat) and the problem gone.
I know it is illogical but for documentation purpose...
This cannot work because ppCombined
is a collection of objects in memory and you cannot join a set of data in the database with another set of data that is in memory. You can try instead to extract the filtered items personProtocol
of the ppCombined
collection in memory after you have retrieved the other properties from the database:
var persons = db.Favorites
.Where(f => f.userId == userId)
.Join(db.Person, f => f.personId, p => p.personId, (f, p) =>
new // anonymous object
{
personId = p.personId,
addressId = p.addressId,
favoriteId = f.favoriteId,
})
.AsEnumerable() // database query ends here, the rest is a query in memory
.Select(x =>
new PersonDTO
{
personId = x.personId,
addressId = x.addressId,
favoriteId = x.favoriteId,
personProtocol = ppCombined
.Where(p => p.personId == x.personId)
.Select(p => new PersonProtocol
{
personProtocolId = p.personProtocolId,
activateDt = p.activateDt,
personId = p.personId
})
.ToList()
});
This seems homework-y, so I'll give a hint rather than a detailed explanation. Correct me if I've assumed wrong.
You're doing fine as far as bailing out when you see an even divisor.
But you're printing 'count' as soon as you see even one number that doesn't divide into it. 2, for instance, does not divide evenly into 9. But that doesn't make 9 a prime. You might want to keep going until you're sure no number in the range matches.
(as others have replied, a Sieve is a much more efficient way to go... just trying to help you understand why this specific code isn't doing what you want)
There are at least five different ways to break out of two or more loops:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
fast:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break fast;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
I found this on another forum while looking to solve the same problem. I've modified it a bit from what I found. It works great. I'm running OS X, so if you're running Microsoft, you'll need to find the correct system() command to switch to raw and cooked modes.
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
// Output prompt
cout << "Press any key to continue..." << endl;
// Set terminal to raw mode
system("stty raw");
// Wait for single character
char input = getchar();
// Echo input:
cout << "--" << input << "--";
// Reset terminal to normal "cooked" mode
system("stty cooked");
// And we're out of here
return 0;
}
Use the start command to prevent the batch file from waiting for the program. Just remember to put a empty double quote in front of the program you want to run after "Start". For example, if you want to run Visual Studio 2012 from a batch command:
Start "" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe"
notice the double quote after start.
Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.
Command-line help for "at":
C:\>at /? The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command. AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]] AT [\\computername] time [/INTERACTIVE] [ /EVERY:date[,...] | /NEXT:date[,...]] "command" \\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted. id Is an identification number assigned to a scheduled command. /delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled. /yes Used with cancel all jobs command when no further confirmation is desired. time Specifies the time when command is to run. /interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs. /every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed. /next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed. "command" Is the Windows NT command, or batch program to be run.
You can try below code. it’s very easy method for push new fragment from old fragment.
private int mContainerId;
private FragmentTransaction fragmentTransaction;
private FragmentManager fragmentManager;
private final static String TAG = "DashBoardActivity";
public void replaceFragment(Fragment fragment, String TAG) {
try {
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(mContainerId, fragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.commitAllowingStateLoss();
} catch (Exception e) {
// TODO: handle exception
}
}
Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)
This worked perfectly for me:
$ git reset -- foo/bar.txt
$ git checkout foo/bar.txt
It is not best practise to mix up content with style, but a solution could be
<div class="thumb" style="background-image: url('images/img.jpg')"></div>
Node.js does not run in a browser, therefore you will not have a document
object available. Actually, you will not even have a DOM tree at all. If you are a bit confused at this point, I encourage you to read more about it before going further.
There are a few methods you can choose from to do what you want.
Because you wrote about opening the file in the browser, why don't you use a framework that will serve the file directly as an HTTP service, instead of having a two-step process? This way, your code will be more dynamic and easily maintainable (not mentioning your HTML always up-to-date).
There are plenty frameworks out there for that :
The most basic way you could do what you want is this :
var http = require('http');
http.createServer(function (req, res) {
var html = buildHtml(req);
res.writeHead(200, {
'Content-Type': 'text/html',
'Content-Length': html.length,
'Expires': new Date().toUTCString()
});
res.end(html);
}).listen(8080);
function buildHtml(req) {
var header = '';
var body = '';
// concatenate header string
// concatenate body string
return '<!DOCTYPE html>'
+ '<html><head>' + header + '</head><body>' + body + '</body></html>';
};
And access this HTML with http://localhost:8080
from your browser.
(Edit: you could also serve them with a small HTTP server.)
If what you are trying to do is simply generating some HTML files, then go simple. To perform IO access on the file system, Node has an API for that, documented here.
var fs = require('fs');
var fileName = 'path/to/file';
var stream = fs.createWriteStream(fileName);
stream.once('open', function(fd) {
var html = buildHtml();
stream.end(html);
});
Note: The buildHtml
function is exactly the same as in Method 1.
stdout
This is the most basic Node.js implementation and requires the invoking application to handle the output itself. To output something in Node (ie. to stdout), the best way is to use console.log(message)
where message
is any string, or object, etc.
var html = buildHtml();
console.log(html);
Note: The buildHtml
function is exactly the same as in Method 1 (again)
If your script is called html-generator.js
(for example), in Linux/Unix based system, simply do
$ node html-generator.js > path/to/file
Because Node is a modular system, you can even put the buildHtml
function inside it's own module and simply write adapters to handle the HTML however you like. Something like
var htmlBuilder = require('path/to/html-builder-module');
var html = htmlBuilder(options);
...
You have to think "server-side" and not "client-side" when writing JavaScript for Node.js; you are not in a browser and/or limited to a sandbox, other than the V8 engine.
Extra reading, learn about npm. Hope this helps.
Please, follow this example with this implementation by using Kotlin and Andoirdx support:
button1.setOnClickListener{
file = getPhotoFile()
val uri: Uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri)
val camaraActivities: List<ResolveInfo> = applicationContext.getPackageManager().queryIntentActivities(captureImage, PackageManager.MATCH_DEFAULT_ONLY)
for (activity in camaraActivities) {
applicationContext.grantUriPermission(activity.activityInfo.packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
}
startActivityForResult(captureImage, REQUEST_PHOTO)
}
And the activity result:
if (requestCode == REQUEST_PHOTO) {
val uri = FileProvider.getUriForFile(applicationContext, "com.example.foto_2.filrprovider", file!!)
applicationContext.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
imageView1.viewTreeObserver.addOnGlobalLayoutListener {
width = imageView1.width
height = imageView1.height
imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
}
if(width!=0&&height!=0){
imageView1.setImageBitmap(getScaleBitmap(file!!.path , width , height))
}else{
val size = Point()
this.windowManager.defaultDisplay.getSize(size)
imageView1.setImageBitmap(getScaleBitmap(file!!.path , size.x , size.y))
}
}
You can get more detail in https://github.com/joelmmx/take_photo_kotlin.git
I hope it helps you!
protected void TableGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1 && e.Row.RowType == DataControlRowType.Header)
{
GridViewRow gvRow = new GridViewRow(0, 0, DataControlRowType.DataRow,DataControlRowState.Insert);
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = " ";
gvRow.Cells.Add(tCell);
Table tbl = e.Row.Parent as Table;
tbl.Rows.Add(gvRow);
}
}
}
One-liner to get the query:
var value = location.search.match(new RegExp(key + "=(.*?)($|\&)", "i"))[1];
Hope this helps: http://nrecursions.blogspot.in/2014/02/how-to-trigger-jenkins-build-on-git.html
It's just a matter of using curl
to trigger a Jenkins job using the git hooks provided by git.
The command
curl http://localhost:8080/job/someJob/build?delay=0sec
can run a Jenkins job, where someJob
is the name of the Jenkins job.
Search for the hooks
folder in your hidden .git folder. Rename the post-commit.sample
file to post-commit
. Open it with Notepad, remove the : Nothing
line and paste the above command into it.
That's it. Whenever you do a commit, Git will trigger the post-commit commands defined in the file.
var clist = document.getElementsByTagName("input");
for (var i = 0; i < clist.length; ++i) { clist[i].checked = false; }
$('input:checkbox').each(function() { this.checked = false; });
To do opposite, see: Select All Checkboxes By ID/Class
you can configure IIS in IIS Mgr to use EVERY port between 1 and 65535 as long it is not used by any other application
Another option is to create an additional "errata commit" (and push) which references the commit object that contains the error -- the new errata commit also provides the correction. An errata commit is a commit with no substantive code changes but an important commit message -- for example, add one space character to your readme file and commit that change with the important commit message, or use the git option --allow-empty
. It's certainly easier and safer than rebasing, it doesn't modify true history, and it keeps the branch tree clean (using amend
is also a good choice if you are correcting the most recent commit, but an errata commit may be a good choice for older commits). This type of thing so rarely happens that simply documenting the mistake is good enough. In the future, if you need to search through a git log for a feature keyword, the original (erroneous) commit may not appear because the wrong keyword was used in that original commit (the original typo) -- however, the keyword will appear in the errata commit which will then point you to the original commit that had the typo. Here's an example:
$ git log commit 0c28141c68adae276840f17ccd4766542c33cf1d Author: First Last Date: Wed Aug 8 15:55:52 2018 -0600 Errata commit: This commit has no substantive code change. This commit is provided only to document a correction to a previous commit message. This pertains to commit object e083a7abd8deb5776cb304fa13731a4182a24be1 Original incorrect commit message: Changed background color to red Correction (*change highlighted*): Changed background color to *blue* commit 032d0ff0601bff79bdef3c6f0a02ebfa061c4ad4 Author: First Last Date: Wed Aug 8 15:43:16 2018 -0600 Some interim commit message commit e083a7abd8deb5776cb304fa13731a4182a24be1 Author: First Last Date: Wed Aug 8 13:31:32 2018 -0600 Changed background color to red
Angular 6 + Alyle UI
With Alyle UI you can change the styles dynamically
Here a demo stackblitz
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CommonModule,
FormsModule,
HttpClientModule,
BrowserAnimationsModule,
AlyleUIModule.forRoot(
{
name: 'myTheme',
primary: {
default: '#00bcd4'
},
accent: {
default: '#ff4081'
},
scheme: 'myCustomScheme', // myCustomScheme from colorSchemes
lightGreen: '#8bc34a',
colorSchemes: {
light: {
myColor: 'teal',
},
dark: {
myColor: '#FF923D'
},
myCustomScheme: {
background: {
primary: '#dde4e6',
},
text: {
default: '#fff'
},
myColor: '#C362FF'
}
}
}
),
LyCommonModule, // for bg, color, raised and others
],
bootstrap: [AppComponent]
})
export class AppModule { }
Html
<div [className]="classes.card">dynamic style</div>
<p color="myColor">myColor</p>
<p bg="myColor">myColor</p>
For change Style
import { Component } from '@angular/core';
import { LyTheme } from '@alyle/ui';
@Component({ ... })
export class AppComponent {
classes = {
card: this.theme.setStyle(
'card', // key
() => (
// style
`background-color: ${this.theme.palette.myColor};` +
`position: relative;` +
`margin: 1em;` +
`text-align: center;`
...
)
)
}
constructor(
public theme: LyTheme
) { }
changeScheme() {
const scheme = this.theme.palette.scheme === 'light' ?
'dark' : this.theme.palette.scheme === 'dark' ?
'myCustomScheme' : 'light';
this.theme.setScheme(scheme);
}
}
var floatValue = 10.23
var intValue = Int(floatValue)
This is enough to convert from float
to Int
Don't update the styles in style.css, instead create a new stylesheet of your own and import in style.css
your-own-style.css
.body{
/*any updates*/
}
import your-own-style.css in style.css
@import url("your-own-style.css");
The only way I know of is to concatenate multiple lines with plus signs
Yes, as many as you want!
BUT, only one "public" class in every file.
In viewDidLoad
declare:
[yourTextField setDelegate:self];
Then, include the override of the delegate method:
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
Actually I had used (what else ;-) ) Vim for this: it has a 2html "plugin". See the docs here.
So as I edit my code, I just convert it to HTML and paste the results to Blogger's HTML editor.
Note: it's not so beautiful HTML (embeded css would be better), but it just works.
Oh: and it has syntax files for several languages which makes it pretty useful.
In plain English: Assume you can do 3 things:
You have a lot of apples in front of you on a table and you want to know how many apples there are.
start
Is the table empty?
yes: Count the tally marks and cheer like it's your birthday!
no: Take 1 apple and put it aside
Write down a tally mark
goto start
The process of repeating the same thing till you are done is called recursion.
I hope this is the "plain english" answer you are looking for!
I stopped using DECODE
several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN
.
However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.
select a, b, decode(a, b, 'true', 'false') as same
from t;
A B SAME
------ ------ -----
1 1 true
1 0 false
1 false
null null true
Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...
DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))
I will still accept any answers that are better than this one!
Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
Becomes:
printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");
With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:
any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)
How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.
You can use the following regex to get integer and floating values from a string:
re.findall(r'[\d\.\d]+', 'hello -34 42 +34.478m 88 cricket -44.3')
['34', '42', '34.478', '88', '44.3']
Thanks Rex
I have had good success using Spring WS for the client end of a web service app - see http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html
My project uses a combination of:
XMLBeans (generated from a simple Maven job using the xmlbeans-maven-plugin)
Spring WS - using marshalSendAndReceive() reduces the code down to one line for sending and receiving
some Dozer - mapping the complex XMLBeans to simple beans for the client GUI
JUnit 4 does not have any out-of-the-box mechanism for a test case to get it’s own name (including during setup and teardown).
another option ... needs remoting ...
(invoke-command -ComputerName mymachine -ScriptBlock {Get-ItemProperty HKLM:\SOFTWARE\VanDyke\VShell\License -Name Version }).version
Eventually what solved the issue was:
I guess for some reason, just cleaning the solution had a different effect than specifically cleaning every project individually.
Edit:
As per @maplemale comment, It seems that sometimes removing and re-adding each reference is also required.
Update 2019:
This question got a lot of traffic in the past, but it seems that since VS 2017 was released, it got much less attention.
So another suggestion would be - Update to a newer version of VS (>= 2017) and among other new features this issue will also be solved
In order to remove all subviews from superviews:
NSArray *oSubView = [self subviews];
for(int iCount = 0; iCount < [oSubView count]; iCount++)
{
id object = [oSubView objectAtIndex:iCount];
[object removeFromSuperview];
iCount--;
}
You typically want to render templates like this:
app.get('/', function(req, res){
res.render('index.ejs');
});
However you can also deliver static content - to do so use:
app.use(express.static(__dirname + '/public'));
Now everything in the /public
directory of your project will be delivered as static content at the root of your site e.g. if you place default.htm
in the public folder if will be available by visiting /default.htm
Take a look through the express API and Connect Static middleware docs for more info.
Considering that the UrnMapping
class is mapped to the internal_uddi
table, I would suggest this:
@Repository
public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> {
@Query(value = "select iu from UrnMapping iu where iu.urn like %:text% or iu.contact like %:text%")
Page<UrnMapping> fullTextSearch(@Param("text") String text, Pageable pageable);
}
Please note that you might have to turn off native queries with dynamic requests.
Check if that file is included in Build Phases -> Compiled Sources
When I make a new project using React, to install the React modules I have to run "npm install" (PowerShell) from within the new projects ClientApp folder (e.g. "C:\Users\Chris\source\repos\HelloWorld2\HelloWorld2\ClientApp"). The .NET core WebApp with React needs to have the React files installed in the correct location for React commands to work properly.
Updated Answer:
DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.
For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.
For more on DynamoDB secondary indexes see the secondary index documentation
Original Answer:
DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.
You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.
If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.
Short answer: in POST requests, values are sent in the "body" of the request. With web-forms they are most likely sent with a media type of application/x-www-form-urlencoded
or multipart/form-data
. Programming languages or frameworks which have been designed to handle web-requests usually do "The Right Thing™" with such requests and provide you with easy access to the readily decoded values (like $_REQUEST
or $_POST
in PHP, or cgi.FieldStorage()
, flask.request.form
in Python).
Now let's digress a bit, which may help understand the difference ;)
The difference between GET
and POST
requests are largely semantic. They are also "used" differently, which explains the difference in how values are passed.
When executing a GET
request, you ask the server for one, or a set of entities. To allow the client to filter the result, it can use the so called "query string" of the URL. The query string is the part after the ?
. This is part of the URI syntax.
So, from the point of view of your application code (the part which receives the request), you will need to inspect the URI query part to gain access to these values.
Note that the keys and values are part of the URI. Browsers may impose a limit on URI length. The HTTP standard states that there is no limit. But at the time of this writing, most browsers do limit the URIs (I don't have specific values). GET
requests should never be used to submit new information to the server. Especially not larger documents. That's where you should use POST
or PUT
.
When executing a POST
request, the client is actually submitting a new document to the remote host. So, a query string does not (semantically) make sense. Which is why you don't have access to them in your application code.
POST
is a little bit more complex (and way more flexible):
When receiving a POST request, you should always expect a "payload", or, in HTTP terms: a message body. The message body in itself is pretty useless, as there is no standard (as far as I can tell. Maybe application/octet-stream?) format. The body format is defined by the Content-Type
header. When using a HTML FORM
element with method="POST"
, this is usually application/x-www-form-urlencoded
. Another very common type is multipart/form-data if you use file uploads. But it could be anything, ranging from text/plain
, over application/json
or even a custom application/octet-stream
.
In any case, if a POST
request is made with a Content-Type
which cannot be handled by the application, it should return a 415
status-code.
Most programming languages (and/or web-frameworks) offer a way to de/encode the message body from/to the most common types (like application/x-www-form-urlencoded
, multipart/form-data
or application/json
). So that's easy. Custom types require potentially a bit more work.
Using a standard HTML form encoded document as example, the application should perform the following steps:
Content-Type
field415
status codeAgain, languages like PHP, or web-frameworks for other popular languages will probably handle this for you. The exception to this is the 415
error. No framework can predict which content-types your application chooses to support and/or not support. This is up to you.
A PUT
request is pretty much handled in the exact same way as a POST
request. The big difference is that a POST
request is supposed to let the server decide how to (and if at all) create a new resource. Historically (from the now obsolete RFC2616 it was to create a new resource as a "subordinate" (child) of the URI where the request was sent to).
A PUT
request in contrast is supposed to "deposit" a resource exactly at that URI, and with exactly that content. No more, no less. The idea is that the client is responsible to craft the complete resource before "PUTting" it. The server should accept it as-is on the given URL.
As a consequence, a POST
request is usually not used to replace an existing resource. A PUT
request can do both create and replace.
There are also "path parameters" which can be used to send additional data to the remote, but they are so uncommon, that I won't go into too much detail here. But, for reference, here is an excerpt from the RFC:
Aside from dot-segments in hierarchical paths, a path segment is considered opaque by the generic syntax. URI producing applications often use the reserved characters allowed in a segment to delimit scheme-specific or dereference-handler-specific subcomponents. For example, the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes. For example, one URI producer might use a segment such as "name;v=1.1" to indicate a reference to version 1.1 of "name", whereas another might use a segment such as "name,1.1" to indicate the same. Parameter types may be defined by scheme-specific semantics, but in most cases the syntax of a parameter is specific to the implementation of the URIs dereferencing algorithm.
Actually, a good solution is to have a static method for the random number generator that is thread-safe and doesn't use locks.
That way, multiple users accessing your web application at the same time don't get the same random strings.
There are 3 examples here: http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx
I'd use the last one:
public static class RandomGen3
{
private static RNGCryptoServiceProvider _global =
new RNGCryptoServiceProvider();
[ThreadStatic]
private static Random _local;
public static int Next()
{
Random inst = _local;
if (inst == null)
{
byte[] buffer = new byte[4];
_global.GetBytes(buffer);
_local = inst = new Random(
BitConverter.ToInt32(buffer, 0));
}
return inst.Next();
}
}
Then you can properly eliminate
Random random = new Random();
And just call RandomGen3.Next(), while your method can remain static.
var nowDate = new Date();_x000D_
var today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);_x000D_
$('#date').datetimepicker({_x000D_
startDate: today_x000D_
});
_x000D_
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
or an ECHO server and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
I just encountered this problem, and it turned out to be that my project is stored in my user folder, which is stored on the network, and we had a momentary network outage. I did a build; it complained that my files had been modified outside the editor (they hadn't; the file locks just got borked), and it built fine, removing the error regarding the InitializeComponent()
method.
BTW, in case you're wondering, developing something from a network drive is bad practice. It becomes particularly problematic when you're trying to leverage .NET's managed code; in my experience, it freaks out every time you build. I forgot to put this little throw-away project in the proper folder, and ended up paying the price.
If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join()
available as a method on any old string object, and you will instead need to use the string module. Example:
a = ['a', 'b', 'c', 'd']
try:
b = ''.join(a)
except AttributeError:
import string
b = string.join(a, '')
The string b
will be 'abcd'
.
Set a default value for people
with ngInit
<div ng-app>
<div ng-init="people=1" />
<input type="radio" ng-model="people" value="1"><label>1</label>
<input type="radio" ng-model="people" value="2"><label>2</label>
<input type="radio" ng-model="people" value="3"><label>3</label>
<ul>
<li>{{10*people}}€</li>
<li>{{8*people}}€</li>
<li>{{30*people}}€</li>
</ul>
</div>
Demo: Fiddle
Actually asXML() converts the string into xml as it name says:
<id>5</id>
This will display normally on a web page but it will cause problems when you matching values with something else.
You may use strip_tags function to get real value of the field like:
$newString = strip_tags($xml->asXML());
PS: if you are working with integers or floating numbers, you need to convert it into integer with intval() or floatval().
$newNumber = intval(strip_tags($xml->asXML()));
First you have to locate the frame id and define it in a WebElement
For ex:- WebElement fr = driver.findElementById("id");
Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");
An example script:-
WebElement fr = driver.findElementById("theIframe");
driver.switchTo().frame(fr);
Then to move out of frame use:- driver.switchTo().defaultContent();
I am using this method to avoid the popup blocker in my React code. it will work in all other javascript codes also.
When you are making an async call on click event, just open a blank window first and then write the URL in that later when an async call will complete.
const popupWindow = window.open("", "_blank");
popupWindow.document.write("<div>Loading, Plesae wait...</div>")
on async call's success, write the following
popupWindow.document.write(resonse.url)
System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));
This is the code:
f = open(filename, 'w')
f.write("hello\talex")
The \t
inside the string is the escape sequence for the horizontal tabulation.
How about something like:
\documentclass{article}
\usepackage{amssymb,amsmath}
\begin{document}
\begin{equation}\label{A_Label}
\begin{split}
w^T x_i + b \geqslant 1-\xi_i \text{ if } y_i &= 1, \\
w^T x_i + b \leqslant -1+\xi_i \text{ if } y_i &= -1
\end{split}
\end{equation}
\end{document}
which produces:
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
if you have autoplay property in the iframe src it wont help to reload the src attr/prop so you have to replace the autoplay=1 to autoplay=0
var stopVideo = function(player) {
var vidSrc = player.prop('src').replace('autoplay=1','autoplay=0');
player.prop('src', vidSrc);
};
stopVideo($('#video'));
You should use keyPressed
if you want an immediate effect, and keyReleased
if you want the effect after you release the key. You cannot use keyTyped
because F5 is not a character. keyTyped
is activated only when an character is pressed.
Load each query into a datatable:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=143
load both datatables into the dataset:
http://msdn.microsoft.com/en-us/library/aeskbwf7%28v=vs.80%29.aspx
Use the event listener's own function remove()
. For example:
getEventListeners().click.forEach((e)=>{e.remove()})
Another short way you could use is a pipe (%<>%
) from the magrittr package. It converts the character column mycolumn to a factor.
library(magrittr)
mydf$mycolumn %<>% factor
you can also do this in aggregation by using project at 3.4
{$project: {"tags.words": 0} }
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
I have used ngIf for one of my similar logic. it is as follows:
<table>
<tr *ngFor="let object of objectData; let i= index;">
<td *ngIf="(i%(object.rowSpan))==0" [attr.rowspan]="object.rowSpan">{{object.value}}</td>
</tr>
</table>
_x000D_
here, i'm getting rowspan value from my model object.
I use tabBarController and i have a few section in my tableview at every tab, so this is best solution for me.
extension UITableView {
func scrollToTop(){
for index in 0...numberOfSections - 1 {
if numberOfSections > 0 && numberOfRows(inSection: index) > 0 {
scrollToRow(at: IndexPath(row: 0, section: index), at: .top, animated: true)
break
}
if index == numberOfSections - 1 {
setContentOffset(.zero, animated: true)
break
}
}
}
}
How about XStream? Not 1 class but 2 jars for many use cases including yours, very simple to use yet quite powerful.
Yes sure, provided you have its context. (See how to get canvas context here.)
var imgData = context.getImageData(0,0,canvas.width,canvas.height);
// { data: [r,g,b,a,r,g,b,a,r,g,..], ... }
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return [d[i],d[i+1],d[i+2],d[i+3]] // Returns array [R,G,B,A]
}
// AND/OR
function getPixelXY(imgData, x, y) {
return getPixel(imgData, y*imgData.width+x);
}
PS: If you plan to mutate the data and draw them back on the canvas, you can use subarray
var
idt = imgData, // See previous code snippet
a = getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
b = idt.data.subarray(188411*4, 188411*4 + 4) // Uint8ClampedArray(4) [0, 251, 0, 255]
a[0] = 255 // Does nothing
getPixel(idt, 188411), // Array(4) [0, 251, 0, 255]
b[0] = 255 // Mutates the original imgData.data
getPixel(idt, 188411), // Array(4) [255, 251, 0, 255]
// Or use it in the function
function getPixel(imgData, index) {
var i = index*4, d = imgData.data;
return imgData.data.subarray(index, index+4) // Returns subarray [R,G,B,A]
}
You can experiment with this on http://qry.me/xyscope/, the code for this is in the source, just copy/paste it in the console.
In Linux, run file on the Eclipse executable, like this:
$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
Chrome does not allow autoplay if the video is not muted. Try using this:
<video width="440px" loop="true" autoplay="autoplay" controls muted>
<source src="http://www.tuscorlloyds.com/CorporateVideo.mp4" type="video/mp4" />
<source src="http://www.tuscorlloyds.com/CorporateVideo.ogv" type="video/ogv" />
<source src="http://www.tuscorlloyds.com/CorporateVideo.webm" type="video/webm" />
</video>
Here is a link which is useful to learn about select a siblings element in Jquery.
How do I select a sibling element using jQuery
$("selector").nextAll();
$("selector").prev();
you can also find an element using Jquery selector
$("h2").siblings('table').find('tr');
For more information, refer this link next(), nextAll(), prev(), prevAll(), find() and siblings in JQuery
The difference between the commands is that one provides you with a tag message while the other doesn't. An annotated tag has a message that can be displayed with git-show(1), while a tag without annotations is just a named pointer to a commit.
According to the documentation: "To create a lightweight tag, don’t supply any of the -a, -s, or -m options, just provide a tag name". There are also some different options to write a message on annotated tags:
git tag <tagname>
, Git will create a tag at the current revision but will not prompt you for an annotation. It will be tagged without a message (this is a lightweight tag).git tag -a <tagname>
, Git will prompt you for an annotation unless you have also used the -m flag to provide a message.git tag -a -m <msg> <tagname>
, Git will tag the commit and annotate it with the provided message.git tag -m <msg> <tagname>
, Git will behave as if you passed the -a flag for annotation and use the provided message.Basically, it just amounts to whether you want the tag to have an annotation and some other information associated with it or not.
This problem is related to missing the Visual Studio "redistributable package." It is not obvious which one is missing based on the dependency walk, but I would try the one that corresponds with your compiler version first and see if things run properly:
I ran into this problem because I am using the Visual Studio compilers, but not the full Visual Studio environment.
Going to dare to inject a new link here: The latest supported Visual C++ downloads. Stein Åsmul, 29.11.2018.
Here's the signature.
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
What you are doing is mixing the values
and the htmlAttributes
together. values
are for URL routing.
You might want to do this.
@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null,
new { @style="text-transform:capitalize;" });
This function is not made to be used for the English language. I translated the words in English. This needs more fixing before using for English.
function ago($d) {
$ts = time() - strtotime(str_replace("-","/",$d));
if($ts>315360000) $val = round($ts/31536000,0).' year';
else if($ts>94608000) $val = round($ts/31536000,0).' years';
else if($ts>63072000) $val = ' two years';
else if($ts>31536000) $val = ' a year';
else if($ts>24192000) $val = round($ts/2419200,0).' month';
else if($ts>7257600) $val = round($ts/2419200,0).' months';
else if($ts>4838400) $val = ' two months';
else if($ts>2419200) $val = ' a month';
else if($ts>6048000) $val = round($ts/604800,0).' week';
else if($ts>1814400) $val = round($ts/604800,0).' weeks';
else if($ts>1209600) $val = ' two weeks';
else if($ts>604800) $val = ' a week';
else if($ts>864000) $val = round($ts/86400,0).' day';
else if($ts>259200) $val = round($ts/86400,0).' days';
else if($ts>172800) $val = ' two days';
else if($ts>86400) $val = ' a day';
else if($ts>36000) $val = round($ts/3600,0).' year';
else if($ts>10800) $val = round($ts/3600,0).' years';
else if($ts>7200) $val = ' two years';
else if($ts>3600) $val = ' a year';
else if($ts>600) $val = round($ts/60,0).' minute';
else if($ts>180) $val = round($ts/60,0).' minutes';
else if($ts>120) $val = ' two minutes';
else if($ts>60) $val = ' a minute';
else if($ts>10) $val = round($ts,0).' second';
else if($ts>2) $val = round($ts,0).' seconds';
else if($ts>1) $val = ' two seconds';
else $val = $ts.' a second';
return $val;
}
For 8085: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of the top of the stack.
The stack pointer register in a computer is made available for general purpose use by programs executing at lower privilege levels than interrupt handlers. A set of instructions in such programs, excluding stack operations, stores data other than the stack pointer, such as operands, and the like, in the stack pointer register. When switching execution to an interrupt handler on an interrupt, return address data for the currently executing program is pushed onto a stack at the interrupt handler's privilege level. Thus, storing other data in the stack pointer register does not result in stack corruption. Also, these instructions can store data in a scratch portion of a stack segment beyond the current stack pointer.
Read this one for more info.
Simply Answer you can use like this
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
setContentView(webView);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("http://www.google.com");
}
}
It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.
This is a first step for somebody that is a beginner. Same thing happened to me:
Look in the Solution Explorer box to the left. Make sure that there is actually a .cpp
file there. You can do the same by looking the .cpp
file where the .sln
file for the project is stored. If there is not one, then you will get that error.
When adding a cpp file you want to use the Add new item icon. (top left with a gold star on it, hover over it to see the name) For some reason Ctrl+N does not actually add a .cpp
file to the project.
In Magento 1.9.4.0 and maybe all versions in 1.x use:
Mage::getStoreConfig('general/store_information/address');
and the following params, it depends what you want to get:
Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.
HTML:
<h1>Hello world!</h1>
Javascript (jQuery):
$(document).ready(function(){
$('h1').css({ 'width':'100%', 'text-align':'center' });
var h1 = $('h1').height();
var h = h1/2;
var w1 = $(window).height();
var w = w1/2;
var m = w - h
$('h1').css("margin-top",m + "px")
});
This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top
of the h1. The beauty of this method is that it works on multiple-line h1
s.
EDIT: I modified it so that it centered it every time the window is resized.
[a-zA-Z]
should do that just fine.
You can reference the cheat sheet.
The $@
and $<
are called automatic variables. The variable $@
represents the name of the target and $<
represents the first prerequisite required to create the output file.
For example:
hello.o: hello.c hello.h
gcc -c $< -o $@
Here, hello.o
is the output file. This is what $@
expands to. The first dependency is hello.c
. That's what $<
expands to.
The -c
flag generates the .o
file; see man gcc
for a more detailed explanation. The -o
specifies the output file to create.
For further details, you can read this article about Linux Makefiles.
Also, you can check the GNU make
manuals. It will make it easier to make Makefiles and to debug them.
If you run this command, it will output the makefile database:
make -p
Always check for Inner Exception if any. In my case Inner Exception turned out to be really helpful in figuring out the issue.
My site was working fine in Dev Environment. But after i deployed to production, it started giving out this exception, but the Inner Exception was saying that Login failed for the particular user.
So i figured out it was something to do with the connection itself. Hence tried logging in using SSMS and even that failed.
Eventually figured out that exception showed up for the simple reason that the SQL server had only Windows Authentication enabled and SQL Authentication was failing which was what i was using for Authentication.
In short, changing Authentication to Mixed(SQL and Windows), fixed the issue for me. :)
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.
You can try this method:
Get the total number of records in the collection with
db.dbcollection.count()
Then use skip:
db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()
Add the text-align
css property to its parent style attribute
Eg:
<div style="text-align:center">
<a href="http://www.example.com">example</a>????????????????????????????????????
</div>?
Or using a class (recommended)
<div class="my-class">
<a href="http://www.example.com">example</a>????????????????????????????????????
</div>?
.my-class {
text-align: center;
}
See below working example:
.my-class {_x000D_
text-align: center;_x000D_
background:green;_x000D_
width:400px;_x000D_
padding:15px; _x000D_
}_x000D_
.my-class a{text-decoration:none; color:#fff;}
_x000D_
<!--EXAMPLE-ONE-->_x000D_
<div style="text-align:center; border:solid 1px #000; padding:15px;">_x000D_
<a href="http://www.example.com">example</a>????????????????????????????????????_x000D_
</div>?_x000D_
_x000D_
<!--EXAMPLE-TWO-->_x000D_
<div class="my-class">_x000D_
<a href="http://www.example.com">example</a>????????????????????????????????????_x000D_
</div>?
_x000D_
Q: Why doesn't the text-align
style get applied to the a
element instead of the div
?
A: The text-align
style describes how inline
content is aligned within a block
element. In this case the div
is an block element and it's inline content is the a
. To further explore this consider how little sense it would make to apply the text-align
style to the a
element when it is accompanied by more text
<div>
Plain text is inline content.
<a href="http://www.example.com" style="text-align: center">example</a>
<span>Spans are also inline content</span>
</div>
Even though threre are line breaks here all the contents of div
are inline content and therefore will produce something like:
Plain text is inline content. example Spans are also inline content
It doesnt' make much sense as to how "example" in this case would be displayed if the text-align
property were to be applied it it.
You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:
git add a_text_file.txt
... do:
git commit -m "Initial commit."
... and those errors should go away.
You have to return a promise instead of a variable. So in your function just return:
return relationsManagerResource.GetParentId(nodeId)
And later resolve the returned promise.
Or you can make another deferred and resolve theParentId
with it.
To use in Eloquent. Add on top of your model
protected $table = 'table_name as alias'
//table_name should be exact as in your database
..then use in your query like
ModelName::query()->select(alias.id, alias.name)
I have a slightly different setup, but think my solution will help you out.
I have a Windows 8 Machine, Python 2.7 installed and running my stuff through eclipse.
Some Background:
When I did an easy install
it tries to install MySQL-python 1.2.5
which failed with an error: Unable to find vcvarsall.bat
. I did an easy_install
of pip
and tried the pip
install which also failed with a similar error. They both reference vcvarsall.bat
which is something to do with visual studio, since I don't have visual studio on my machine, it left me looking for a different solution, which I share below.
The Solution:
After I did both of those installs I was able to query my MySQL db through eclipse.
you may try the TO_CHAR function to convert the result
e.g.
SELECT TO_CHAR(92, '99.99') AS RES FROM DUAL
SELECT TO_CHAR(92.258, '99.99') AS RES FROM DUAL
Hope it helps
It means you asked it to include the library 'libz.a' or 'libz.so' containing a compression package, and although the compiler found some files, none of them was suitable for the build you are using.
You either need to change your build parameters or you need to get the correct library installed or you need to specify where the correct library is on the link command line with a -L/where/it/is/lib
type option.
editText.setFocusableInTouchMode(false);
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);
editText.setFocusable(true);
EditText will lose focus, but can gain it again on a new touch event.
You can also use the stat
command if you want detailed information on a file/directory. (I precise this as you say you are learning ^^)
Seeing as this isn't already mentioned here and it's how I got around the issue...
Right click the target database and choose Tasks > Export data
and follow that through. One of the destinations on the 'Choose a destination' screen is Microsoft Excel and there's a step that will accept your query.
It's the SQL Server Import and Export wizard. It's a lot more long-winded than the simple Copy with headers option that I normally use but, save jumping through a lot more hoops, when you have a lot of data to get into excel it's a worthy option.
The following code works for me. I am using Swift 5
let path = Bundle.main.path(forResource: "yourJSONfileName", ofType: "json")
var jsonData = try! String(contentsOfFile: path!).data(using: .utf8)!
Then, if your Person Struct (or Class) is Decodable (and also all of its properties), you can simply do:
let person = try! JSONDecoder().decode(Person.self, from: jsonData)
I avoided all the error handling code to make the code more legible.
Firstly you have to make it executable using: chmod +x name_of_your_file_script
.
After you made it executable, you can run it using ./same_name_of_your_file_script
in my case i did following
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = '<YOUR HOST>';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '<USERNAME>';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = '';
$mail->smtpConnect([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
$mail->smtpClose();
$mail->From = '<[email protected]>';
$mail->FromName = '<MAIL FROM NAME>';
$mail->addAddress("<[email protected]>", '<SEND TO>');
$mail->isHTML(true);
$mail->Subject= '<SUBJECTHERE>';
$mail->Body = '<h2>Test Mail</h2>';
$isSend = $mail->send();
Looking at the source code I also think there must be some issue with the private key.
What it is doing is actually to check if the certificate that is passed is of type X509Certificate2 and if it has the private key.
If it doesn't find the private key it tries to find the certificate in the CurrentUser store and then in the LocalMachine store. If it finds the certificate it checks if the private key is present.
(see source code from class SecureChannnel, method EnsurePrivateKey)
So depending on which file you imported (.cer - without private key or .pfx - with private key) and on which store it might not find the right one and Request.ClientCertificate won't be populated.
You can activate Network Tracing to try to debug this. It will give you output like this:
When you use strace (on Linux) to run your binary, it will output the returns from system calls and what the error number means. This may sometimes be useful to you.
Might as well throw up an actual response with my solution, which was inspired by Peter Liljenberg's:
$ mpstat | awk '$12 ~ /[0-9.]+/ { print 100 - $12"%" }'
0.75%
This will use awk
to print out 100 minus the 12th field (idle), with a percentage sign after it. awk
will only do this for a line where the 12th field has numbers and dots only ($12 ~ /[0-9]+/
).
You can also average five samples, one second apart:
$ mpstat 1 5 | awk 'END{print 100-$NF"%"}'
Test it like this:
$ mpstat 1 5 | tee /dev/tty | awk 'END{print 100-$NF"%"}'
I solved it this way:
Call the following just before calling your ssl webservice that cause that error:
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
/// <summary>
/// solution for exception
/// System.Net.WebException:
/// The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
/// </summary>
public static void BypassCertificateError()
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(
Object sender1,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
In C# I did:
alert('Text\\n\\nSome more text');
It display as:
Text
Some more text
Winmerge has a command line utility that might be worth checking out.
Also, you can use the graphical part of it too depending on what you need.
The reason behind this is that meanwhile creating your own class, you had also accepted to create a default class as prescribed by your IDE and after writing your code in your own class, you are getting such an error. In order to eliminate this, go to the PROJECT folder ? src
? Default package. Keep only one class (in which you had written code) and delete others.
After that, run your program and it will definitely run without any error.