In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
I was facing this problem when trying to add a .NETStandard dependency to a .NET4.6.1 library, and compiling it in Linux with Mono 4.6.2 (the version that comes with Ubuntu 16.04).
I finally solved it today; the solution requires to do both of these things:
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
to <TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
in the .csproj file.The latest set of guidance is as follows: (from https://docs.microsoft.com/en-us/azure/azure-functions/functions-dotnet-class-library#environment-variables)
Use:
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
From the docs:
public static class EnvironmentVariablesExample
{
[FunctionName("GetEnvironmentVariables")]
public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
{
log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
log.LogInformation(GetEnvironmentVariable("AzureWebJobsStorage"));
log.LogInformation(GetEnvironmentVariable("WEBSITE_SITE_NAME"));
}
public static string GetEnvironmentVariable(string name)
{
return name + ": " +
System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process);
}
}
App settings can be read from environment variables both when developing locally and when running in Azure. When developing locally, app settings come from the
Values
collection in the local.settings.json file. In both environments, local and Azure,GetEnvironmentVariable("<app setting name>")
retrieves the value of the named app setting. For instance, when you're running locally, "My Site Name" would be returned if your local.settings.json file contains{ "Values": { "WEBSITE_SITE_NAME": "My Site Name" } }
.The System.Configuration.ConfigurationManager.AppSettings property is an alternative API for getting app setting values, but we recommend that you use
GetEnvironmentVariable
as shown here.
For me I put my dependencies in the wrong spot.
buildscript {
dependencies {
//Don't put dependencies here.
}
}
dependencies {
//Put them here
}
It's a pandas data-frame and it's using label base selection tool with df.loc
and in it, there are two inputs, one for the row and the other one for the column, so in the row input it's selecting all those row values where the value saved in the column class
is versicolor
, and in the column input it's selecting the column with label class
, and assigning Iris-versicolor
value to them.
So basically it's replacing all the cells of column class
with value versicolor
with Iris-versicolor
.
After different tries, I end up to a solution since most markdown interpreter support Math environment. The following adds one white space :
$~$
And here ten:
$~~~~~~~~~~~$
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
when(dao.doSearch(dto)).thenReturn(inspectionsSummaryList);//got error in this line
verify(dao).doSearchInspections(dto);
The when
here configures your mock to do something. However, you donot use this mock in any way anymore after this line (apart from doing a verify
). Mockito warns you that the when
line therefore is pointless. Perhaps you made a logic error?
data.reshape((50,1104,-1))
works for me
Containers use the OS kernel. Windows Container utilize processes in order to run. So theoretically speaking Windows Containers cannot run on Linux.
However there are workarounds utilizing VMstyle solutions.
I Have found this solution which uses Vagrant and Packer on Mac, so it should work for Linux as well: https://github.com/StefanScherer/windows-docker-machine
This Vagrant environment creates a Docker Machine to work on your MacBook with Windows containers. You can easily switch between Docker for Mac Linux containers and the Windows containers.
building the headless Vagrant box
$ git clone https://github.com/StefanScherer/packer-windows $ cd packer-windows $ packer build --only=vmware-iso windows_2019_docker.json $ vagrant box add windows_2019_docker windows_2019_docker_vmware.box
Create the Docker Machine
$ git clone https://github.com/StefanScherer/windows-docker-machine $ cd windows-docker-machine $ vagrant up --provider vmware_fusion 2019
Switch to Windows containers
$ eval $(docker-machine env 2019)
If you are using Linux OS:
matplotlib==1.3.1
from requirements.txt
sudo apt-get install python-matplotlib
pip install -r requirements.txt
(Python 2), or pip3 install -r requirements.txt
(Python 3)pip freeze > requirements.txt
If you are using Windows OS:
python -m pip install -U pip setuptools
python -m pip install matplotlib
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))
This has happened to me as well. The problem is with the mysql repo that comes already with the linux distro. So when you simply do:
$ sudo apt install mysql-server
it installs mysql from their default repo which gives this problem. So to overcome that you need to uninstall that installed mysql
$ sudo apt remove mysql* --purge --auto-remove
Then download mysql repo from official mysql website MySQL APT Repo Follow their documentation on how to add repo and install it. This gives no issue. Also as answered by @zetacu, you can verify that mysql root now indeed uses mysql_native_password plugin
A simple working configuration using
@TestPropertySource and properties
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {"spring.config.location=classpath:another.yml"})
public class TestClass {
@Test
public void someTest() {
}
}
You can set the column index using index_col parameter available while reading from spreadsheet in Pandas.
Here is my solution:
Firstly, import pandas as pd:
import pandas as pd
Read in filename using pd.read_excel() (if you have your data in a spreadsheet) and set the index to 'Locality' by specifying the index_col parameter.
df = pd.read_excel('testexcel.xlsx', index_col=0)
At this stage if you get a 'no module named xlrd' error, install it using pip install xlrd
.
For visual inspection, read the dataframe using df.head()
which will print the following output
Now you can fetch the values of the desired columns of the dataframe and print it
Was updating an old website using nuget (including .Net update and MVC update).
I deleted the System.Net.HTTP reference in VS2017 (it was to version 2.0.0.0) and re-added the reference, which then showed 4.2.0.0.
I then updated a ton of 'packages' using nuget and got the error message, then noticed something had reset the reference to 2.0.0.0, so I removed and re-added again and it works fine... bizarre.
It's so simple.
Just install Microsoft.EntityFrameworkCore.Tools
package from nuget:
Install-Package Microsoft.EntityFrameworkCore.Tools -Version 3.1.5
You can also use this link to install the latest version: Nuget package link
.NET CLI command:
dotnet add package Microsoft.EntityFrameworkCore.Tools
To get rid of the bad looking datepicker you need to add jquery-ui css
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css">
Don't worry... Its much easy to solve your problem. Just SET you SDK-LOCATION and JDK-LOCATION.
Clik Android Sdk Location
Select & Browse your Android SDK Location (Like: C:\Android\sdk)
Uncheck USE EMBEDDED JDK LOCATION
If another pull just works, it means your internet wasn't connected.
You might want to change the DNS settings of the Docker daemon. You can edit (or create) the configuration file at /etc/docker/daemon.json
with the dns key, as
{
"dns": ["your_dns_address", "8.8.8.8"]
}
In the example above, the first element of the list is the address of your DNS server. The second item is the Google’s DNS which can be used when the first one is not available.
Before proceeding, save daemon.json and restart the docker service.
sudo service docker restart
Once fixed, retry to run the build command.
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
I had the similar problem in my app. Here is what I did.
1.add this for build.gradle in module: app
multiDexEnabled = true
So the code would be like:
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.example..."
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "1.0"
multiDexEnabled = true
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
This worked for me. Hope this helps you too :)
In the same project I was using Firebase too. So enabling multiDexEnabled let to another problem in Firebase for Pre Lollipop devices. Some FireBase classes were not identified. (Unable to get provider com.google.firebase.provider).
Method to resolve that is explained here.
update
If you use the router you can use lifecycle hooks or resolvers to delay navigation until the data arrived. https://angular.io/guide/router#milestone-5-route-guards
To load data before the initial rendering of the root component APP_INITIALIZER
can be used How to pass parameters rendered from backend to angular2 bootstrap method
original
When console.log(this.ev)
is executed after this.fetchEvent();
, this doesn't mean the fetchEvent()
call is done, this only means that it is scheduled. When console.log(this.ev)
is executed, the call to the server is not even made and of course has not yet returned a value.
Change fetchEvent()
to return a Promise
fetchEvent(){
return this._apiService.get.event(this.eventId).then(event => {
this.ev = event;
console.log(event); // Has a value
console.log(this.ev); // Has a value
});
}
change ngOnInit()
to wait for the Promise
to complete
ngOnInit() {
this.fetchEvent().then(() =>
console.log(this.ev)); // Now has value;
}
This actually won't buy you much for your use case.
My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>
and in ngOnInit()
isDataAvailable:boolean = false;
ngOnInit() {
this.fetchEvent().then(() =>
this.isDataAvailable = true); // Now has value;
}
As the accepted answer requires you to add a Frame Layout, here how you can do it with material design.
Add this if you haven't already
implementation 'com.google.android.material:material:1.0.0'
Now change to Cardview to MaterialCardView
<com.google.android.material.card.MaterialCardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
app:cardCornerRadius="8dp"
app:cardElevation="2dp"
app:strokeWidth="1dp"
app:strokeColor="@color/black">
Now you need to change the activity theme to Theme.Material. If you are using Theme.Appcompact I will suggest you to move to Theme.Material for future projects for having better material design in you app.
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight">
The solution below does only one groupBy and extract the rows of your dataframe that contain the maxValue in one shot. No need for further Joins, or Windows.
import org.apache.spark.sql.Row
import org.apache.spark.sql.catalyst.encoders.RowEncoder
import org.apache.spark.sql.DataFrame
//df is the dataframe with Day, Category, TotalValue
implicit val dfEnc = RowEncoder(df.schema)
val res: DataFrame = df.groupByKey{(r) => r.getInt(0)}.mapGroups[Row]{(day: Int, rows: Iterator[Row]) => i.maxBy{(r) => r.getDouble(2)}}
As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:
@TestPropertySource("classpath:application-test.properties")
Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource
Simply restarting Visual Studio works for me.. try restarting Visual Studio.
You can use the following
import { find } from 'lodash'
Then to return the entire object (not only its key or value) from the list with the following:
let match = find(savedViews, { 'ID': 'id to match'});
Add to your build.gradle:
test {
useJUnitPlatform()
}
Additional to tomaskazemekas's answer: you should install spyder in that virtual environment by:
conda install -n myenv spyder
(on Windows, for Linux or MacOS, you can search for similar commands)
Adding @WebAppConfiguration
(org.springframework.test.context.web.WebAppConfiguration
) annotation to your DemoApplicationTests class will work.
The accepted answer didn't work in my situation, not sure why. I switched from JRE1.7 to JRE1.8 and that resolved the issue automatically. JRE1.8 uses TLS1.2 by default
I had the same error here but with glassfish server. Maybe it can help. I needed to configure the glassfish-web.xml file with the content inside the <resources>
from glassfish-resources.xml. As I got another error I could find this annotation in the server log:
Caused by: java.lang.RuntimeException: Error in parsing WEB-INF/glassfish-web.xml for archive [file:/C:/Users/Win/Documents/NetBeansProjects/svad/build/web/]: The xml element should be [glassfish-web-app] rather than [resources]
All I did then was to change the <resources>
tag and apply <glassfish-web-app>
in the glassfish-web.xml file.
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
Your mock is raising the exception just fine, but the error.resp.status
value is missing. Rather than use return_value
, just tell Mock
that status
is an attribute:
barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
Additional keyword arguments to Mock()
are set as attributes on the resulting object.
I put your foo
and bar
definitions in a my_tests
module, added in the HttpError
class so I could use it too, and your test then can be ran to success:
>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
... barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
... result = my_test.foo()
...
404 -
>>> result is None
True
You can even see the print '404 - %s' % error.message
line run, but I think you wanted to use error.content
there instead; that's the attribute HttpError()
sets from the second argument, at any rate.
You can try this:
df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))
I spent a long time looking for solutions, and found this answer.
It looks like, in order to get what you (and I) want, you need the combination of plt.ion()
, plt.show()
(not with block=False
) and, most importantly, plt.pause(.001)
(or whatever time you want). The pause is needed because the GUI events happen while the main code is sleeping, including drawing. It's possible that this is implemented by picking up time from a sleeping thread, so maybe IDEs mess with that—I don't know.
Here's an implementation that works for me on python 3.5:
import numpy as np
from matplotlib import pyplot as plt
def main():
plt.axis([-50,50,0,10000])
plt.ion()
plt.show()
x = np.arange(-50, 51)
for pow in range(1,5): # plot x^1, x^2, ..., x^4
y = [Xi**pow for Xi in x]
plt.plot(x, y)
plt.draw()
plt.pause(0.001)
input("Press [enter] to continue.")
if __name__ == '__main__':
main()
If you're using application.properties in spring boot app, then just put the below line into application.properties and it should work:
spring.datasource.url: jdbc:mysql://google/?cloudSqlInstance=&socketFactory=com.google.cloud.sql.mysql.SocketFactory&user=****&password=****
If all else fails just go to your terminal and type from your folder:
git push origin master
That's the way the Gods originally wanted it to be.
I struggled with this as well and found a simple pattern to isolate the test context after a cursory read of the @ComponentScan docs.
/**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for annotated components. The package of each class specified will be scanned.
* Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {};
("com.example.test")
.Example
IsolatedTest.java
package com.example.test;
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackageClasses = {TestDomain.class})
@SpringApplicationConfiguration(classes = IsolatedTest.Config.class)
public class IsolatedTest {
String expected = "Read the documentation on @ComponentScan";
String actual = "Too lazy when I can just search on Stack Overflow.";
@Test
public void testSomething() throws Exception {
assertEquals(expected, actual);
}
@ComponentScan(basePackageClasses = {TestDomain.class})
public static class Config {
public static void main(String[] args) {
SpringApplication.run(Config.class, args);
}
}
}
...
TestDomain.java
package com.example.test;
public interface TestDomain {
//noop marker
}
you can do make App in FullScreen Mode form just one line code. i am using this in my code.
just set AppTheme -> Theme.AppCompat.Light.NoActionBar in your style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
It will work in all pages..
This error is fairly self-explanatory. Dictionary keys are unique and you cannot have more than one of the same key. To fix this, you should modify your code like so:
Dictionary<string, string> rct3Features = new Dictionary<string, string>();
Dictionary<string, string> rct4Features = new Dictionary<string, string>();
foreach (string line in rct3Lines)
{
string[] items = line.Split(new String[] { " " }, 2, StringSplitOptions.None);
if (!rct3Features.ContainsKey(items[0]))
{
rct3Features.Add(items[0], items[1]);
}
////To print out the dictionary (to see if it works)
//foreach (KeyValuePair<string, string> item in rct3Features)
//{
// Console.WriteLine(item.Key + " " + item.Value);
//}
}
This simple if
statement ensures that you are only attempting to add a new entry to the Dictionary when the Key (items[0]
) is not already present.
This typically is caused by the mount directory being left mounted due to a crash of your filesystem. Go to the parent directory of the mount point and enter fusermount -u YOUR_MNT_DIR
.
If this doesn't do the trick, do sudo umount -l YOUR_MNT_DIR
.
If you are using intellij, then try restarting intellij cache
See if it works, it worked for me.
If one is wanting to iterate through an array (Array
or more generally any SequenceType
) in reverse. You have a few additional options.
First you can reverse()
the array and loop through it as normal. However I prefer to use enumerate()
much of the time since it outputs a tuple containing the object and it's index.
The one thing to note here is that it is important to call these in the right order:
for (index, element) in array.enumerate().reverse()
yields indexes in descending order (which is what I generally expect). whereas:
for (index, element) in array.reverse().enumerate()
(which is a closer match to NSArray's reverseEnumerator
)
walks the array backward but outputs ascending indexes.
If you're running test Suite via @RunWith(Suite.class) @Suite.SuiteClasses({})
check if all provided classes are really test classes ;).
In my case one of the classes was an actual implementation, not a test class. Just a silly typo.
By using https://github.com/nick318/FindElementInFrames You can find webElement across all frames:
SearchByFramesFactory searchFactory = new SearchByFramesFactory(driver);
SearchByFrames searchInFrame = searchFactory.search(() -> driver.findElement(By.tagName("body")));
Optional<WebElement> elem = searchInFrame.getElem();
only start listner then u can connect with database. command run on editor:
lsnrctl start
its work fine.
By default overflow
does not apply to table group elements unless you give a display:block
to <tbody>
also you have to give a position:relative
and display: block
to <thead>
. Check the DEMO.
.fixed {
width:350px;
table-layout: fixed;
border-collapse: collapse;
}
.fixed th {
text-decoration: underline;
}
.fixed th,
.fixed td {
padding: 5px;
text-align: left;
min-width: 200px;
}
.fixed thead {
background-color: red;
color: #fdfdfd;
}
.fixed thead tr {
display: block;
position: relative;
}
.fixed tbody {
display: block;
overflow: auto;
width: 100%;
height: 100px;
overflow-y: scroll;
overflow-x: hidden;
}
In my case, with letsencrypt https, this was caused by using cert.pem
instead of fullchain.pem
as the certificate file on the requested server. See this thread for details.
Use FileSaver.js
. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js
implements the saveAs() FileSaver interface in browsers that do not natively support it:
https://github.com/eligrey/FileSaver.js
Minified version is really small at < 2.5KB, gzipped < 1.2KB.
Usage:
/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);
You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
https://github.com/eligrey/Blob.js
Consider StreamSaver.js if you have files larger than blob's size limitations.
Complete example:
/* Two options_x000D_
* 1. Get FileSaver.js from here_x000D_
* https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
* <script src="FileSaver.min.js" />_x000D_
*_x000D_
* Or_x000D_
*_x000D_
* 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
* then a simple implementation of saveAs function can be:_x000D_
*/_x000D_
function saveAs(blob, fileName) {_x000D_
var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
var anchorElem = document.createElement("a");_x000D_
anchorElem.style = "display: none";_x000D_
anchorElem.href = url;_x000D_
anchorElem.download = fileName;_x000D_
_x000D_
document.body.appendChild(anchorElem);_x000D_
anchorElem.click();_x000D_
_x000D_
document.body.removeChild(anchorElem);_x000D_
_x000D_
// On Edge, revokeObjectURL should be called only after_x000D_
// a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
setTimeout(function() {_x000D_
window.URL.revokeObjectURL(url);_x000D_
}, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
// convert base64 string to byte array_x000D_
var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
var byteNumbers = new Array(byteCharacters.length);_x000D_
for (var i = 0; i < byteCharacters.length; i++) {_x000D_
byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
}_x000D_
var byteArray = new Uint8Array(byteNumbers);_x000D_
_x000D_
// now that we have the byte array, construct the blob from it_x000D_
var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
var fileName1 = "cool.gif";_x000D_
saveAs(blob1, fileName1);_x000D_
_x000D_
// saving text file_x000D_
var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
var fileName2 = "cool.txt";_x000D_
saveAs(blob2, fileName2);_x000D_
})();
_x000D_
Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js
for supporting IE 11).
You can also save from a canvas
element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.
Demos: https://eligrey.com/demos/FileSaver.js/
Blog post by author of FileSaver.js
: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side
Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers
Note 2: Failed to execute 'atob' on 'Window'
Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
See http://caniuse.com/#search=blob
Note 4: IE < 10 support (I've not tested this part):
https://github.com/eligrey/FileSaver.js#ie--10
https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476
Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html
Note 5: Creating a BLOB from a Base64 string in JavaScript
Note 6: FileSaver.js
examples: https://github.com/eligrey/FileSaver.js#examples
If you're using Spring Boot, you can simply use @SpringBootTest
to load in your ApplicationContext
(which is what your stacktrace is barking at you about). This allows you to autowire in your spring-data repositories. Be sure to add @RunWith(SpringRunner.class)
so the spring-specific annotations are picked up:
@RunWith(SpringRunner.class)
@SpringBootTest
public class OrphanManagementTest {
@Autowired
private UserRepository userRepository;
@Test
public void saveTest() {
User user = new User("Tom");
userRepository.save(user);
Assert.assertNotNull(userRepository.findOne("Tom"));
}
}
You can read more about testing in spring boot in their docs.
Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:
src("'js/**/!(*.min).js")
Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js
This solution worked for me using PyQt5 version 5.15.0
import sys
from PyQt5 import QtWidgets, QtWebEngineWidgets
from PyQt5.QtCore import QUrl
from PyQt5.QtGui import QPageLayout, QPageSize
from PyQt5.QtWidgets import QApplication
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
loader = QtWebEngineWidgets.QWebEngineView()
loader.setZoomFactor(1)
layout = QPageLayout()
layout.setPageSize(QPageSize(QPageSize.A4Extra))
layout.setOrientation(QPageLayout.Portrait)
loader.load(QUrl('https://stackoverflow.com/questions/23359083/how-to-convert-webpage-into-pdf-by-using-python'))
loader.page().pdfPrintingFinished.connect(lambda *args: QApplication.exit())
def emit_pdf(finished):
loader.page().printToPdf("test.pdf", pageLayout=layout)
loader.loadFinished.connect(emit_pdf)
sys.exit(app.exec_())
You can use the magic of Spring's ReflectionTestUtils.setField
in order to avoid making any modifications whatsoever to your code.
The comment from Michal Stochmal provides an example:
use
ReflectionTestUtils.setField(bean, "fieldName", "value");
before invoking yourbean
method during test.
Check out this tutorial for even more information, although you probably won't need it since the method is very easy to use
UPDATE
Since the introduction of Spring 4.2.RC1 it is now possible to set a static field without having to supply an instance of the class. See this part of the documentation and this commit.
the solution that solved my problem for this is
goto references->right click Newtonsoft.json--goto properties and check the version
this same version should be in
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-YourDllVersion" newVersion="YourDllVersion" />
</dependentAssembly>
If you install PyQt4 on Windows, files wind up here by default:
C:\Python27\Lib\site-packages\PyQt4*.*
but it also leaves a file here:
C:\Python27\Lib\site-packages\sip.pyd
If you copy the both the sip.pyd and PyQt4 folder into your virtualenv things will work fine.
For example:
mkdir c:\code
cd c:\code
virtualenv BACKUP
cd c:\code\BACKUP\scripts
activate
Then with windows explorer copy from C:\Python27\Lib\site-packages
the file (sip.pyd) and folder (PyQt4) mentioned above to C:\code\BACKUP\Lib\site-packages\
Then back at CLI:
cd ..
(c:\code\BACKUP)
python backup.py
The problem with trying to launch a script which calls PyQt4 from within virtualenv is that the virtualenv does not have PyQt4 installed and it doesn't know how to reference the default installation described above. But follow these steps to copy PyQt4 into your virtualenv and things should work great.
Base on @ashakirov answer, here is my extension to show/hide view with fade animation
fun View.fadeVisibility(visibility: Int, duration: Long = 400) {
val transition: Transition = Fade()
transition.duration = duration
transition.addTarget(this)
TransitionManager.beginDelayedTransition(this.parent as ViewGroup, transition)
this.visibility = visibility
}
Example using
view.fadeVisibility(View.VISIBLE)
view.fadeVisibility(View.GONE, 2000)
It took me ages to work this one out, so for the benefit of searchers:
I had a bizarre issue whereby the application worked in debug, but gave the XamlParseException
once released.
After fixing the x86/x64 issue as detailed by Katjoek, the issue remained.
The issue was that a CEF tutorial said to bring down System.Windows.Interactivity
from NuGet (even thought it's in the Extensions section of references in .NET) and bringing down from NuGet sets specific version
to true
.
Once deployed, a different version of System.Windows.Interactivity
was being packed by a different application.
It's refusal to use a different version of the dll caused the whole application to crash with XamlParseException
.
I used concat method and works well.
concat(//SomeElement/text(),'_',//OtherElement/text())
I think somewhere in your codebase are you @Autowiring
the concrete class ServiceImpl
where you should be autowiring it's interface (presumably MyService
).
Determining of root cause is not an issue since Go 1.8; field name now is shown in the error message:
json: cannot unmarshal object into Go struct field Comment.author of type string
How to install PyQt4 on anaconda python 2 on Windows:
At first I have tried to isntall pyqt4 via pip install
:
C:\Users\myuser\Anaconda2\Scripts\pip.exe search pyqt4 > pyqt4.txt
It shows:
PyQt4 (4.11.4) - Python bindings for the Qt cross platform GUI toolkit
But when I tried to install, it gives an error:
C:\Users\myuser\Anaconda2\Scripts\pip.exe install PyQt4
Collecting PyQt4
Could not find a version that satisfies the requirement PyQt4 (from versions:
)
No matching distribution found for PyQt4
Seems this answer is realated to this problem: https://superuser.com/a/725869/213959
Then I have tried to install it via conda install
( How to install PyQt4 in anaconda? ) :
C:\Users\myuser\Anaconda2\Scripts\conda.exe search pyqt
It shows:
pyqt 4.10.4 py26_0 defaults
4.10.4 py27_0 defaults
4.10.4 py33_0 defaults
4.10.4 py34_0 defaults
4.10.4 py26_1 defaults
4.10.4 py27_1 defaults
4.10.4 py33_1 defaults
4.10.4 py34_1 defaults
4.11.4 py27_0 defaults
4.11.4 py35_0 defaults
4.11.4 py27_2 defaults
4.11.4 py34_2 defaults
4.11.4 py35_2 defaults
4.11.4 py27_3 defaults
4.11.4 py34_3 defaults
4.11.4 py35_3 defaults
4.11.4 py27_4 defaults
4.11.4 py34_4 defaults
4.11.4 py35_4 defaults
4.11.4 py27_5 defaults
4.11.4 py34_5 defaults
4.11.4 py35_5 defaults
4.11.4 py27_6 defaults
4.11.4 py34_6 defaults
4.11.4 py35_6 defaults
4.11.4 py27_7 defaults
4.11.4 py34_7 defaults
4.11.4 py35_7 defaults
5.6.0 py27_0 defaults
5.6.0 py34_0 defaults
5.6.0 py35_0 defaults
5.6.0 py27_1 defaults
5.6.0 py34_1 defaults
5.6.0 py35_1 defaults
5.6.0 py27_2 defaults
5.6.0 py34_2 defaults
5.6.0 py35_2 defaults
5.6.0 py36_2 defaults
5.6.0 py27h224ed30_5 defaults
5.6.0 py35hd46907b_5 defaults
5.6.0 py36hb5ed885_5 defaults
But it gives error:
C:\Users\myuser\Anaconda2\Scripts\conda.exe install pyqt=4.11.4
Fetching package metadata .............
Solving package specifications: .
UnsatisfiableError: The following specifications were found to be in conflict:
- navigator-updater -> pyqt >=5.6 -> qt 5.6.*
- pyqt 4.11.4* -> qt >=4.8.6,<5.0
- pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.
Same with -c
parameter:
C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
Fetching package metadata ...............
Solving package specifications: .
UnsatisfiableError: The following specifications were found to be in conflict:
- navigator-updater -> pyqt >=5.6 -> qt 5.6.*
- pyqt 4.11.4* -> qt >=4.8.6,<5.0
- pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.
Then I tried to uninstall pyqt
:
C:\Users\myuser\Anaconda2\Scripts\conda.exe uninstall pyqt
And installed it again:
C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
And finnaly it works!
Its a bit late, however... Full implementation:
[HttpGet]
public async Task<HttpResponseMessage> GetPageFromUriOrBody(RequestQuery requestQuery)
{
log(nameof(GetPageFromUriOrBody), nameof(requestQuery));
var responseResult = await _requestQueryCache.GetOrCreate(
nameof(GetPageFromUriOrBody)
, requestQuery
, (x) => getPageContent(x).Result);
return Request.CreateResponse(System.Net.HttpStatusCode.Accepted, responseResult);
}
static MemoryCacheWithPolicy<RequestQuery, string> _requestQueryCache = new MemoryCacheWithPolicy<RequestQuery, string>();
Here is getPageContent
signature:
async Task<string> getPageContent(RequestQuery requestQuery);
And here is the MemoryCacheWithPolicy
implementation:
public class MemoryCacheWithPolicy<TParameter, TResult>
{
static ILogger _nlogger = new AppLogger().Logger;
private MemoryCache _cache = new MemoryCache(new MemoryCacheOptions()
{
//Size limit amount: this is actually a memory size limit value!
SizeLimit = 1024
});
/// <summary>
/// Gets or creates a new memory cache record for a main data
/// along with parameter data that is assocciated with main main.
/// </summary>
/// <param name="key">Main data cache memory key.</param>
/// <param name="param">Parameter model that assocciated to main model (request result).</param>
/// <param name="createCacheData">A delegate to create a new main data to cache.</param>
/// <returns></returns>
public async Task<TResult> GetOrCreate(object key, TParameter param, Func<TParameter, TResult> createCacheData)
{
// this key is used for param cache memory.
var paramKey = key + nameof(param);
if (!_cache.TryGetValue(key, out TResult cacheEntry))
{
// key is not in the cache, create data through the delegate.
cacheEntry = createCacheData(param);
createMemoryCache(key, cacheEntry, paramKey, param);
_nlogger.Warn(" cache is created.");
}
else
{
// data is chached so far..., check if param model is same (or changed)?
if(!_cache.TryGetValue(paramKey, out TParameter cacheParam))
{
//exception: this case should not happened!
}
if (!cacheParam.Equals(param))
{
// request param is changed, create data through the delegate.
cacheEntry = createCacheData(param);
createMemoryCache(key, cacheEntry, paramKey, param);
_nlogger.Warn(" cache is re-created (param model has been changed).");
}
else
{
_nlogger.Trace(" cache is used.");
}
}
return await Task.FromResult<TResult>(cacheEntry);
}
MemoryCacheEntryOptions createMemoryCacheEntryOptions(TimeSpan slidingOffset, TimeSpan relativeOffset)
{
// Cache data within [slidingOffset] seconds,
// request new result after [relativeOffset] seconds.
return new MemoryCacheEntryOptions()
// Size amount: this is actually an entry count per
// key limit value! not an actual memory size value!
.SetSize(1)
// Priority on removing when reaching size limit (memory pressure)
.SetPriority(CacheItemPriority.High)
// Keep in cache for this amount of time, reset it if accessed.
.SetSlidingExpiration(slidingOffset)
// Remove from cache after this time, regardless of sliding expiration
.SetAbsoluteExpiration(relativeOffset);
//
}
void createMemoryCache(object key, TResult cacheEntry, object paramKey, TParameter param)
{
// Cache data within 2 seconds,
// request new result after 5 seconds.
var cacheEntryOptions = createMemoryCacheEntryOptions(
TimeSpan.FromSeconds(2)
, TimeSpan.FromSeconds(5));
// Save data in cache.
_cache.Set(key, cacheEntry, cacheEntryOptions);
// Save param in cache.
_cache.Set(paramKey, param, cacheEntryOptions);
}
void checkCacheEntry<T>(object key, string name)
{
_cache.TryGetValue(key, out T value);
_nlogger.Fatal("Key: {0}, Name: {1}, Value: {2}", key, name, value);
}
}
nlogger
is just nLog
object to trace MemoryCacheWithPolicy
behavior.
I re-create the memory cache if request object (RequestQuery requestQuery
) is changed through the delegate (Func<TParameter, TResult> createCacheData
) or re-create when sliding or absolute time reached their limit. Note that everything is async too ;)
Scripts are loaded in the order you have defined them in the HTML.
Therefore if you first load:
<script type="text/javascript" src="./javascript.js"></script>
without loading jQuery first, then $ is not defined
.
You need to first load jQuery so that you can use it.
I would also recommend placing your scripts at the bottom of your HTML for performance reasons.
OK, there was a small typo in my key. Apparently when pasting to file the first letter was cut off and it started with sh-rsa instead of ssh-rsa.
nrathathaus - your answer was very helpful, thanks a lot, this answer is credited to you :) I did like you said and set this in sshd_conf:
LogLevel DEBUG3
By looking at the logs I realized that sshd reads the key correctly but rejects it because of the incorrect identifier.
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
I fixed this problem with sql command line:
connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;
Restart database.
You serialize it to JSON to persist in the Database and Deserialize it to reconstitute the .NET collection. This seems to perform better than I expected it to with Entity Framework 6 & SQLite. I know you asked for List<string>
but here's an example of an even more complex collection that works just fine.
I tagged the persisted property with [Obsolete]
so it would be very obvious to me that "this is not the property you are looking for" in the normal course of coding. The "real" property is tagged with [NotMapped]
so Entity framework ignores it.
(unrelated tangent): You could do the same with more complex types but you need to ask yourself did you just make querying that object's properties too hard for yourself? (yes, in my case).
using Newtonsoft.Json;
....
[NotMapped]
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();
/// <summary> <see cref="MetaData"/> for database persistence. </summary>
[Obsolete("Only for Persistence by EntityFramework")]
public string MetaDataJsonForDb
{
get
{
return MetaData == null || !MetaData.Any()
? null
: JsonConvert.SerializeObject(MetaData);
}
set
{
if (string.IsNullOrWhiteSpace(value))
MetaData.Clear();
else
MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
}
}
You were almost there:
You just need to append the li
to ul
and voila!
So just add
ul.appendChild(li);
to the end of your function so the end function will be like this:
function function1() {
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode("Element 4"));
ul.appendChild(li);
}
This probably means that python doesn't know where PyQt5 is located. To check, go into the interactive terminal and type:
import sys
print sys.path
What you probably need to do is add the directory that contains the PyQt5 module to your PYTHONPATH
environment variable. If you use bash
, here's how:
~/.bashrc
export PYTHONPATH=/path/to/PyQt5/directory:$PYTHONPATH
where /path/to/PyQt5/directory
is the path to the folder where the PyQt5 library is located.
I ran in to this recently, and as it turned out, I've imported the wrong annotation in my service class. Netbeans has an option to hide import statements, that's why I did not see it for some time.
I've used @org.jvnet.hk2.annotations.Service
instead of @org.springframework.stereotype.Service
.
In SQL Developer ..Go to Preferences-->NLS-->and change your date format accordingly
In your example, you prepended your source string with AccountKey=
but not your target string.
$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='
By not including that in the target string, the resulting string will remove AccountKey=
instead of replacing it. You correctly do this with the AccountName=
example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.
We faced the same issue and fixed it. Below is the reason and solution.
Problem
When the connection pool mechanism is used, the application server (in our case, it is JBOSS) creates connections according to the min-connection
parameter. If you have 10 applications running, and each has a min-connection
of 10, then a total of 100 sessions will be created in the database. Also, in every database, there is a max-session
parameter, if your total number of connections crosses that border, then you will get Got minus one from a read call
.
FYI: Use the query below to see your total number of sessions:
SELECT username, count(username) FROM v$session
WHERE username IS NOT NULL group by username
Solution: With the help of our DBA, we increased that max-session
parameter, so that all our application min-connection
can accommodate.
in Eike Thies's response above, if we use underscore.js, filter could be simplified to :
var app = angular.module('myApp', []).filter('object2Array', function() {
return function(input) {
return _.toArray(input);
}
});
Just install the latest version from nondefault repository:
$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-4.7-dev
Another approach in integration testing is to define a new Configuration class and provide it as your @ContextConfiguration
. Into the configuration you will be able to mock your beans and also you must define all types of beans which you are using in test/s flow.
To provide an example :
@RunWith(SpringRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class)
public class MockTest{
@Configuration
static class ContextConfiguration{
// ... you beans here used in test flow
@Bean
public MockMvc mockMvc() {
return MockMvcBuilders.standaloneSetup(/*you can declare your controller beans defines on top*/)
.addFilters(/*optionally filters*/).build();
}
//Defined a mocked bean
@Bean
public MyService myMockedService() {
return Mockito.mock(MyService.class);
}
}
@Autowired
private MockMvc mockMvc;
@Autowired
MyService myMockedService;
@Before
public void setup(){
//mock your methods from MyService bean
when(myMockedService.myMethod(/*params*/)).thenReturn(/*my answer*/);
}
@Test
public void test(){
//test your controller which trigger the method from MyService
MvcResult result = mockMvc.perform(get(CONTROLLER_URL)).andReturn();
// do your asserts to verify
}
}
I have faced same type of issue and followed the below steps to resolved the issue
Go to Tools --> Library Package Manager --> Package Manager Console and run the below command
Install-Package Microsoft.ASPNet.WebAPI -pre
Your footer element won't inherently be fixed to the bottom of your viewport unless you style it that way.
So if you happen to have a page that doesn't have enough content to push it all the way down it'll end up somewhere in the middle of the viewport; looking very awkward and not sure what to do with itself, like my first day of high school.
Positioning the element by declaring the fixed
rule is great if you always want your footer visible regardless of initial page height - but then remember to set a bottom margin so that it doesn't overlay the last bit of content on that page. This becomes tricky if your footer has a dynamic height; which is often the case with responsive sites since it's in the nature of elements to stack.
You'll find a similar problem with absolute
positioning. And although it does take the element in question out of the natural flow of the document, it still won't fix it to the bottom of the screen should you find yourself with a page that has little to no content to flesh it out.
Consider achieving this by:
<body>
& <html>
tagsminimum-height
value to the nested wrapper element, usually the element which wraps all your descendant elements contained within the body structure (this wouldn't include your footer
element)$("#addBodyContent").on("click", function() {_x000D_
$("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo(".flex-col:first-of-type");_x000D_
});_x000D_
_x000D_
$("#resetBodyContent").on("click", function() {_x000D_
$(".flex-col p").remove();_x000D_
});_x000D_
_x000D_
$("#addFooterContent").on("click", function() {_x000D_
$("<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>").appendTo("footer");_x000D_
});_x000D_
_x000D_
$("#resetFooterContent").on("click", function() {_x000D_
$("footer p").remove();_x000D_
});
_x000D_
html, body {_x000D_
height: 91%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
width: 100%;_x000D_
left: 0;_x000D_
right: 0;_x000D_
box-sizing: border-box;_x000D_
padding: 10px;_x000D_
display: block;_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
footer {_x000D_
background: black;_x000D_
text-align: center;_x000D_
color: white;_x000D_
box-sizing: border-box;_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.flex {_x000D_
display: flex;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.flex-col {_x000D_
flex: 1 1;_x000D_
background: #ccc;_x000D_
margin: 0px 10px;_x000D_
box-sizing: border-box;_x000D_
padding: 20px;_x000D_
}_x000D_
_x000D_
.flex-btn-wrapper {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
flex-direction: row;_x000D_
}_x000D_
_x000D_
.btn {_x000D_
box-sizing: border-box;_x000D_
padding: 10px;_x000D_
transition: .7s;_x000D_
margin: 10px 10px;_x000D_
min-width: 200px;_x000D_
}_x000D_
_x000D_
.btn:hover {_x000D_
background: transparent;_x000D_
cursor: pointer;_x000D_
}_x000D_
_x000D_
.dark {_x000D_
background: black;_x000D_
color: white;_x000D_
border: 3px solid black;_x000D_
}_x000D_
_x000D_
.light {_x000D_
background: white;_x000D_
border: 3px solid white;_x000D_
}_x000D_
_x000D_
.light:hover {_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.dark:hover {_x000D_
color: black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="wrapper">_x000D_
<div class="flex-btn-wrapper">_x000D_
<button id="addBodyContent" class="dark btn">Add Content</button>_x000D_
<button id="resetBodyContent" class="dark btn">Reset Content</button>_x000D_
</div>_x000D_
<div class="flex">_x000D_
<div class="flex-col">_x000D_
lorem ipsum dolor..._x000D_
</div>_x000D_
<div class="flex-col">_x000D_
lorem ipsum dolor..._x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<footer>_x000D_
<div class="flex-btn-wrapper">_x000D_
<button id="addFooterContent" class="light btn">Add Content</button>_x000D_
<button id="resetFooterContent" class="light btn">Reset Content</button>_x000D_
</div>_x000D_
lorem ipsum dolor..._x000D_
</footer>
_x000D_
try adding compile("org.springframework.boot:spring-boot-starter-thymeleaf") dependency to your gradle file.Thymeleaf helps mapping views.
It's very simple for Python 3.x (docs).
import csv
with open('output_file_name', 'w', newline='', encoding='utf-8') as csv_file:
writer = csv.writer(csv_file, delimiter=';')
writer.writerow('my_utf8_string')
For Python 2.x, look here.
I too have struggled with this new pagespeed metric.
Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.
Combining all css into one file helped a lot. All my sites are back up to %95 - %98.
The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.
The scope <scope>provided</scope>
gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.
Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.
Change groupId
to <groupId>net.sourceforge.ant4x</groupId>
to get the latest jar.
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
Another solution for this problem is:
Where http://localhost/repo is your local repo URL:
<repositories>
<repository>
<id>wmc-central</id>
<url>http://localhost/repo</url>
</repository>
<-- Other repository config ... -->
</repositories>
I would recomment the Fixed-Point ("F") format specifier (as mentioned by Ehsan). See the Standard Numeric Format Strings.
With this option you can even have a configurable number of decimal places:
public string ValueAsString(double value, int decimalPlaces)
{
return value.ToString($"F{decimalPlaces}");
}
Although you may have already found a resolution to your issue, I'm still going to post this note to benefit someone else. I ran into a similar issue. I basically used a different domain account to test and compare. The task ran just fine with "Run whether user is logged on or not" checked.
A couple of things to keep in mind and make sure of:
Check this link and hopefully you or someone else can benefit from this info: https://technet.microsoft.com/en-us/library/cc722152.aspx
I had similar problem in SQL Workbench.
URL:
jdbc:oracle:thin:@111.111.111.111:1111:xe
doesn't work.
URL:
jdbc:oracle:thin:@111.111.111.111:1111:asdb
works.
This help me in my concrete situation. I afraid, that could exists many other reasons with different solutions.
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic & modern design.</span></p>
Remove <br>
effect using CSS.
<style> p br{ display:none; } </style>
There can be multiple root causes for this exception. For me, my mockMvc wasn't getting auto-configured. I solved this exception by using @WebMvcTest(MyController.class)
at the class level. This annotation will disable full auto-configuration and instead apply only configuration relevant to MVC tests.
An alternative to this is, If you are looking to load your full application configuration and use MockMVC, you should consider @SpringBootTest
combined with @AutoConfigureMockMvc
rather than @WebMvcTest
Read the message:
Only one
<configSections>
element allowed per config file and if present must be the first child of the root<configuration>
element.
Move the configSections element to the top - just above where system.data is currently.
If you're using Anaconda to manage Python on your system, you can install it with:
$ conda install pyqt=4
Omit the =4
to install the most current version.
Answer from How to install PyQt4 in anaconda?
I use the following maven dependencies to get java mail working. The first one includes the javax.mail API (with no implementation) and the second one is the SUN implementation of the javax.mail API.
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.5.5</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.5.5</version>
</dependency>
The fallthrough
answers by others are good ones.
However another approach would be extract methods out of the contents of your case statements and then just call the appropriate method from each case.
In the example below, both case 'text1' and case 'text4' behave the same:
switch (name) {
case text1: {
method1();
break;
}
case text2: {
method2();
break;
}
case text3: {
method3();
break;
}
case text4: {
method1();
break;
}
I personally find this style of writing case statements more maintainable and slightly more readable, especially when the methods you call have good descriptive names.
Install qt using:
sudo apt install qt5-qmake
Open ~/.bashrc
file:
vim ~/.bashrc
Added the path below to the ~/.bashrc
file:
export PATH="/opt/Qt/5.15.1/gcc_64/bin/:$PATH"
Execute/load a ~/.bashrc
file in your current shell
source ~/.bashrc`
Try now qmake
by using the version command below:
qmake --version
Update for Spring 4: since 4.0.1 you can use PathMatchConfigurer
(via your WebMvcConfigurer
), e.g.
@Configuration
protected static class AllResources extends WebMvcConfigurerAdapter {
@Override
public void configurePathMatch(PathMatchConfigurer matcher) {
matcher.setUseRegisteredSuffixPatternMatch(true);
}
}
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
}
In xml, it would be (https://jira.spring.io/browse/SPR-10163):
<mvc:annotation-driven>
[...]
<mvc:path-matching registered-suffixes-only="true"/>
</mvc:annotation-driven>
Suppose there's a file test.txt
in Root Folder, and want to move it to \TxtFolder
,
You can try
move %~dp0\test.txt %~dp0\TxtFolder
.
reference answer: relative path in BAT script
If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.
Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.
Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"
In my case, I was creating an HttpClient inside a method that actually did the service call. Something like:
public void DoServiceCall() {
var client = new HttpClient();
await client.PostAsync();
}
In an Azure worker role, after repeatedly calling this method (without disposing the HttpClient), it would eventually fail with SocketException
(connection attempt failed).
I made the HttpClient an instance variable (disposing it at the class level) and the issue went away. So I would say, yes, dispose the HttpClient, assuming its safe (you don't have outstanding async calls) to do so.
Remove "SSLv2ClientHello" from the enabled protocols on the client SSLSocket or HttpsURLConnection.
One easy way to select random items is to shuffle then slice.
import random
a = [1,2,3,4,5,6,7,8,9]
random.shuffle(a)
print a[:4] # prints 4 random variables
Add this at the start of main
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");
//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
Probably, you need to insert schema identifier here:
in.addValue("po_system_users", null, OracleTypes.ARRAY, "your_schema.T_SYSTEM_USER_TAB");
This one drove me crazy for Xamarin.
I ran into this with a ViewPager implementation for TabLayout WITHIN a Fragment, that is itself implemented in the DrawerLayout:
- DrawerLayout
- DrawerFragment
- TabLayout
- TabViewPager
- TabViewPagerFragments
So you have to implement the following code in your DrawerFragment. Be aware to choose the correct FragmentManager-Path. Because you might have two different FragmentManager References:
--> Choose the one you use. If you want to make use of the ChildFragmentManager, you had to use the class declaration Android.App.FragmentManager for your ViewPager!
Android.Support.V4.App.FragmentManager
Implement the following Method in your "Main" Fragment - in this example: DrawerFragment
public override void OnDetach() {
base.OnDetach();
try {
Fragment x = this;
var classRefProp = typeof(Fragment).GetProperty("class_ref", BindingFlags.NonPublic | BindingFlags.Static);
IntPtr classRef = (IntPtr)classRefProp.GetValue(x);
var field = JNIEnv.GetFieldID(classRef, "mChildFragmentManager", "Landroid/support/v4/app/FragmentManagerImpl;");
JNIEnv.SetField(base.Handle, field, IntPtr.Zero);
}
catch (Exception e) {
Log.Debug("Error", e+"");
}
}
Android.App.FragmentManager
public class TabViewPager: Android.Support.V13.App.FragmentPagerAdapter {}
That means you had to init the ViewPager with Android.App.FragmentManager.
Implement the following Method in your "Main" Fragment - in this example: DrawerFragment
public override void OnDetach() {
base.OnDetach();
try {
Fragment x = this;
var classRefProp = typeof(Fragment).GetProperty("class_ref", BindingFlags.NonPublic | BindingFlags.Static);
IntPtr classRef = (IntPtr)classRefProp.GetValue(x);
var field = JNIEnv.GetFieldID(classRef, "mChildFragmentManager", "Landroid/app/FragmentManagerImpl;");
JNIEnv.SetField(base.Handle, field, IntPtr.Zero);
}
catch (Exception e) {
Log.Debug("Error", e+"");
}
}
Here is an example for those who want to Test Spring MockMvc Security Config using Base64 basic authentication.
String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("<username>:<password>").getBytes()));
this.mockMvc.perform(get("</get/url>").header("Authorization", basicDigestHeaderValue).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
Maven Dependency
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency>
I received this error when the class was annotated with @Ignore and I tried to run a specific test via right clicking on it. Removing the @Ignore fixed the problem.
If you are using Java 9 or above you may need to require the junit dependency in your module-info.java
module myModule {
requires junit;
}
This seems more straightforward using data.table
as it performs the sort while setting the key.
So, if I were to get the top 3 records in sort (ascending order), then,
require(data.table)
d <- data.table(mtcars, key="cyl")
d[, head(.SD, 3), by=cyl]
does it.
And if you want the descending order
d[, tail(.SD, 3), by=cyl] # Thanks @MatthewDowle
Edit: To sort out ties using mpg
column:
d <- data.table(mtcars, key="cyl")
d.out <- d[, .SD[mpg %in% head(sort(unique(mpg)), 3)], by=cyl]
# cyl mpg disp hp drat wt qsec vs am gear carb rank
# 1: 4 22.8 108.0 93 3.85 2.320 18.61 1 1 4 1 11
# 2: 4 22.8 140.8 95 3.92 3.150 22.90 1 0 4 2 1
# 3: 4 21.5 120.1 97 3.70 2.465 20.01 1 0 3 1 8
# 4: 4 21.4 121.0 109 4.11 2.780 18.60 1 1 4 2 6
# 5: 6 18.1 225.0 105 2.76 3.460 20.22 1 0 3 1 7
# 6: 6 19.2 167.6 123 3.92 3.440 18.30 1 0 4 4 1
# 7: 6 17.8 167.6 123 3.92 3.440 18.90 1 0 4 4 2
# 8: 8 14.3 360.0 245 3.21 3.570 15.84 0 0 3 4 7
# 9: 8 10.4 472.0 205 2.93 5.250 17.98 0 0 3 4 14
# 10: 8 10.4 460.0 215 3.00 5.424 17.82 0 0 3 4 5
# 11: 8 13.3 350.0 245 3.73 3.840 15.41 0 0 3 4 3
# and for last N elements, of course it is straightforward
d.out <- d[, .SD[mpg %in% tail(sort(unique(mpg)), 3)], by=cyl]
Whilst @Didzis has the correct answer, I will expand on a few points
Aesthetics can be set or mapped within a ggplot call.
An aesthetic defined within aes(...) is mapped from the data, and a legend created.
An aesthetic may also be set to a single value, by defining it outside aes().
As far as I can tell, what you want is to set size to a single value, not map within the call to aes()
When you call aes(size = 2)
it creates a variable called `2`
and uses that to create the size, mapping it from a constant value as it is within a call to aes
(thus it appears in your legend).
Using size = 1 (and without reg_labeller
which is perhaps defined somewhere in your script)
Figure29 +
geom_line(aes(group=factor(tradlib)),size=1) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(
colour = 'black', angle = 90, size = 13,
hjust = 0.5, vjust = 0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
and with size = 2
Figure29 +
geom_line(aes(group=factor(tradlib)),size=2) +
facet_grid(regionsFull~., scales="free_y") +
scale_colour_brewer(type = "div") +
theme(axis.text.x = element_text(colour = 'black', angle = 90,
size = 13, hjust = 0.5, vjust =
0.5),axis.title.x=element_blank()) +
ylab("FSI (%Change)") +
theme(axis.text.y = element_text(colour = 'black', size = 12),
axis.title.y = element_text(size = 12,
hjust = 0.5, vjust = 0.2)) +
theme(strip.text.y = element_text(size = 11, hjust = 0.5,
vjust = 0.5, face = 'bold'))
You can now define the size to work appropriately with the final image size and device type.
File pathBinary = new File("Firefox.exe location");
FirefoxBinary ffBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);
You need to add binary of the browser
or
Best and forever solution: Just add Firefox.exe location to environmental variables
you would have to write down some method to create a temporary array and then copy it like
public String[] increaseArray(String[] theArray, int increaseBy)
{
int i = theArray.length;
int n = ++i;
String[] newArray = new String[n];
for(int cnt=0;cnt<theArray.length;cnt++)
{
newArray[cnt] = theArray[cnt];
}
return newArray;
}
or The ArrayList would be helpful to resolve your problem.
Just in case some other poor sod ends up here because they are having the same issue I was: if you have multiple data sources and this is happening with the non-primary data source, then the problem might be with that config. The data source, entity manager factory, and transaction factory all need to be correctly configured, but also -- and this is what tripped me up -- MAKE SURE TO TIE THEM ALL TOGETHER! @EnableJpaRepositories
(configuration class annotation) must include entityManagerFactoryRef
and transactionManagerRef
to pick up all the configuration!
The example in this blog finally helped me see what I was missing, which (for quick reference) were the refs here:
@EnableJpaRepositories(
entityManagerFactoryRef = "barEntityManagerFactory",
transactionManagerRef = "barTransactionManager",
basePackages = "com.foobar.bar")
Hope this helps save someone else from the struggle I've endured!
After some days searching the Internet I found that this error usually occurs when an html element id has the same id as some variable in the javascript function. After changing the name of one of them my code was working fine.
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
The best approach here is to remove @ActiveProfiles annotation and do the following:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ContextConfiguration(locations = {
"classpath:config/test-context.xml" })
public class TestContext {
@BeforeClass
public static void setSystemProperty() {
Properties properties = System.getProperties();
properties.setProperty("spring.profiles.active", "localtest");
}
@AfterClass
public static void unsetSystemProperty() {
System.clearProperty("spring.profiles.active");
}
@Test
public void testContext(){
}
}
And your test-context.xml should have the following:
<context:property-placeholder
location="classpath:META-INF/spring/config_${spring.profiles.active}.properties"/>
Whenever you print any instance of your class, the default
toString
implementation of Object
class is called, which returns the representation that you are getting.
It contains two parts: - Type
and Hashcode
So, in student.Student@82701e that you get as output ->
student.Student
is the Type
, and82701e
is the HashCode
So, you need to override a toString
method in your Student
class to get required String representation
: -
@Override
public String toString() {
return "Student No: " + this.getStudentNo() +
", Student Name: " + this.getStudentName();
}
So, when from your main
class, you print your ArrayList
, it will invoke the toString
method for each instance, that you overrided
rather than the one in Object
class: -
List<Student> students = new ArrayList();
// You can directly print your ArrayList
System.out.println(students);
// Or, iterate through it to print each instance
for(Student student: students) {
System.out.println(student); // Will invoke overrided `toString()` method
}
In both the above cases, the toString
method overrided in Student
class will be invoked and appropriate representation of each instance will be printed.
For Bootstrap 3.x and Ace Template wrapbootstrap
Datepicker and Timepicker inside a Modal
<style>
body.modal-open .datepicker {
z-index: 1050 !important;
}
body.modal-open .bootstrap-timepicker-widget {
z-index: 1050 !important;
}
</style>
I ran into a similar problem where Visual Studio (2017) said it could not find my project's PDB file. I could see the PDB file did exist in the correct path. I had to Clean and Rebuild the project, then Visual Studio recognized the PDB file and debugging worked.
> S = matrix(c(1,2,3,4,5,2,1,2,3,4,3,2,1,2,3,4,3,2,1,2,5,4,3,2,1),ncol = 5,byrow = TRUE);S
[,1] [,2] [,3] [,4] [,5]
[1,] 1 2 3 4 5
[2,] 2 1 2 3 4
[3,] 3 2 1 2 3
[4,] 4 3 2 1 2
[5,] 5 4 3 2 1
> S<-S[,-2]
> S
[,1] [,2] [,3] [,4]
[1,] 1 3 4 5
[2,] 2 2 3 4
[3,] 3 1 2 3
[4,] 4 2 1 2
[5,] 5 3 2 1
Just use the command S <- S[,-2]
to remove the second column. Similarly to delete a row, for example, to delete the second row use S <- S[-2,]
.
Update-Package -reinstall Microsoft.Web.Infrastructure
didn't work for me, as I kept receiving errors that it was already installed.
I had to navigate to the Microsoft.Web.Infrastructure.1.0.0.0 folder in the packages folder and manually delete that folder.
After doing this, running Install-Package Microsoft.Web.Infrastructure
installed it.
Note: CopyLocal
was automatically set to true.
Call the function in this way:
self.parse_file()
You also need to define your parse_file() function like this:
def parse_file(self):
The parse_file
method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is self
.
In addition to adding @Transactional
on @Test
method, you also need to add @Rollback(false)
Below is an adaptation of previous code for using under PyQt5 and Matplotlib 2.0. There are a number of small changes: structure of PyQt submodules, other submodule from matplotlib, deprecated method has been replaced...
import sys
from PyQt5.QtWidgets import QDialog, QApplication, QPushButton, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
import matplotlib.pyplot as plt
import random
class Window(QDialog):
def __init__(self, parent=None):
super(Window, self).__init__(parent)
# a figure instance to plot on
self.figure = plt.figure()
# this is the Canvas Widget that displays the `figure`
# it takes the `figure` instance as a parameter to __init__
self.canvas = FigureCanvas(self.figure)
# this is the Navigation widget
# it takes the Canvas widget and a parent
self.toolbar = NavigationToolbar(self.canvas, self)
# Just some button connected to `plot` method
self.button = QPushButton('Plot')
self.button.clicked.connect(self.plot)
# set the layout
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.canvas)
layout.addWidget(self.button)
self.setLayout(layout)
def plot(self):
''' plot some random stuff '''
# random data
data = [random.random() for i in range(10)]
# instead of ax.hold(False)
self.figure.clear()
# create an axis
ax = self.figure.add_subplot(111)
# discards the old graph
# ax.hold(False) # deprecated, see above
# plot data
ax.plot(data, '*-')
# refresh canvas
self.canvas.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Window()
main.show()
sys.exit(app.exec_())
A little bit simpler and more effective variation of @yannis solution:
SELECT
title,
description,
CHAR_LENGTH(description) - CHAR_LENGTH( REPLACE ( description, 'value', '1234') )
AS `count`
FROM <table>
The difference is that I replace the "value" string with a 1-char shorter string ("1234" in this case). This way you don't need to divide and round to get an integer value.
Generalized version (works for every needle string):
SET @needle = 'value';
SELECT
description,
CHAR_LENGTH(description) - CHAR_LENGTH(REPLACE(description, @needle, SPACE(LENGTH(@needle)-1)))
AS `count`
FROM <table>
I think it is a problem(aka. bug) with the API you are using. JSONArray
implements Collection
(the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject
has an overloaded put()
method which takes a Collection and wraps it in a JSONArray
(thus causing the problem). I think you need to force the other JSONObject.put()
method to be used:
jsonObject.put("aoColumnDefs",(Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection)
method is broken.
In case it helps anyone, the error message:
'does not contain a definition for 'GetAwaiter'' etc.
also occurs if the await is incorrectly placed before the variable like this:
instead of:
RtfAsTextLines = await OpenNoUserInterface(FilePath);
Use the attribute selector
[id^=product]{property:value}
Try this
mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name
I suggest keeping your icons separate from FontAwesome and create and maintain your own custom library. Personally, I think it is much easier to maintain keeping FontAwesome separate if you are going to be creating your own icon library. You can then have FontAwesome loaded into your site from a CDN and never have to worry about keeping it up-to-date.
When creating your own custom icons, create each icon via Adobe Illustrator or similar software. Once your icons are created, save each individually in SVG
format on your computer.
Next, head on over to IcoMoon: http://icomoon.io , which has the best font generating software (in my opinion), and it's free. IcoMoon will allow you to import your individual svg-saved fonts into a font library, then generate your custom icon glyph library in eot
, ttf
, woff
, and svg
. One format IcoMoon does not generate is woff2
.
After generating your icon pack at IcoMoon, head over to FontSquirrel: http://fontsquirrel.com and use their font generator. Use your ttf
file generated at IcoMoon. In the newly generated icon pack created, you'll now have your icon pack in woff2
format.
Make sure the files for eot
, ttf
, svg
, woff
, and woff2
are all the same name. You are generating an icon pack from two different websites/software, and they do name their generated output differently.
You'll have CSS generated for your icon pack at both locations. But the CSS generated at IcoMoon will not include the woff2
format in your @font-face {}
declaration. Make sure to add that when you're adding your CSS to your project:
@font-face {
font-family: 'customiconpackname';
src: url('../fonts/customiconpack.eot?lchn8y');
src: url('../fonts/customiconpack.eot?lchn8y#iefix') format('embedded-opentype'),
url('../fonts/customiconpack.ttf?lchn8y') format('truetype'),
url('../fonts/customiconpack.woff2?lchn8y') format('woff'),
url('../fonts/customiconpack.woff?lchn8y') format('woff'),
url('../fonts/customiconpack.svg?lchn8y#customiconpack') format('svg');
font-weight: normal;
font-style: normal;
}
Keep in mind that you can get the glyph unicode values of each icon in your icon pack using the IcoMoon software. These values can be helpful in assigning your icons via CSS, as in (assuming we're using the font-family
declared in the example @font-face {...}
above):
selector:after {
font-family: 'customiconpackname';
content: '\e953';
}
You can also get the glyph unicode value e953
if you open the font-pack-generated svg
file in a text editor. E.g.:
<glyph unicode="" glyph-name="eye" ... />
In my case the issue was caused by custom ActionFilterAttribute which was a kind of global filter attribute. The attribute instantiated a service through Autofac but the service crashed in constructor:
public ActionFilterAttribute()
{
_service = ContainerManager.Resolve<IService>();
}
public class Service: IService
{
public Service()
{
throw new Exception('Oops!');
}
}
import re
re.sub(r'''(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))''', " ", text)
You can set the System properties as VM arguments.
If your project is a maven project then you can execute following command while running the test class:
mvn test -Dapp.url="https://stackoverflow.com"
Test class:
public class AppTest {
@Test
public void testUrl() {
System.out.println(System.getProperty("app.url"));
}
}
If you want to run individual test class or method in eclipse then :
1) Go to Run -> Run Configuration
2) On left side select your Test class under the Junit section.
3) do the following :
The error:
'int' object has no attribute '__getitem__'
means that you're attempting to apply the index operator []
on an int, not a list. So is col
not a list, even when it should be? Let's start from that.
Look here:
col = [[0 for col in range(5)] for row in range(6)]
Use a different variable name inside, looks like the list comprehension overwrites the col
variable during iteration. (Not during the iteration when you set col
, but during the following ones.)
Full Working HTML Code. Cut+Paste into new .HTML file:
Contains Two Examples:
Tested In:
<!DOCTYPE HTML >
<html lang="en">
<head>
<meta charset="UTF-8">
<title> #SAVE_CANVAS_TEST# </title>
<meta
name ="author"
content="John Mark Isaac Madison"
>
<!-- EMAIL: J4M4I5M7 -[AT]- Hotmail.com -->
</head>
<body>
<div id="about_the_code">
Illustrates:
<ol>
<li>How to save a canvas from HTML page. </li>
<li>How to save a dynamically created canvas.</li>
</ol>
</div>
<canvas id="DOM_CANVAS"
width ="300"
height="300"
></canvas>
<div id="controls">
<button type="button" style="width:300px;"
onclick="obj.SAVE_CANVAS()">
SAVE_CANVAS ( Dynamically Made Canvas )
</button>
<button type="button" style="width:300px;"
onclick="obj.SAVE_CANVAS('DOM_CANVAS')">
SAVE_CANVAS ( Canvas In HTML Code )
</button>
</div>
<script>
var obj = new MyTestCodeClass();
function MyTestCodeClass(){
//Publically exposed functions:
this.SAVE_CANVAS = SAVE_CANVAS;
//:Private:
var _canvas;
var _canvas_id = "ID_OF_DYNAMIC_CANVAS";
var _name_hash_counter = 0;
//:Create Canvas:
(function _constructor(){
var D = document;
var CE = D.createElement.bind(D);
_canvas = CE("canvas");
_canvas.width = 300;
_canvas.height= 300;
_canvas.id = _canvas_id;
})();
//:Before saving the canvas, fill it so
//:we can see it. For demonstration of code.
function _fillCanvas(input_canvas, r,g,b){
var ctx = input_canvas.getContext("2d");
var c = input_canvas;
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.fillRect(0, 0, c.width, c.height);
}
//:Saves canvas. If optional_id supplied,
//:will save canvas off the DOM. If not,
//:will save the dynamically created canvas.
function SAVE_CANVAS(optional_id){
var c = _getCanvas( optional_id );
//:Debug Code: Color canvas from DOM
//:green, internal canvas red.
if( optional_id ){
_fillCanvas(c,0,255,0);
}else{
_fillCanvas(c,255,0,0);
}
_saveCanvas( c );
}
//:If optional_id supplied, get canvas
//:from DOM. Else, get internal dynamically
//:created canvas.
function _getCanvas( optional_id ){
var c = null; //:canvas.
if( typeof optional_id == "string"){
var id = optional_id;
var d = document;
var c = d.getElementById( id );
}else{
c = _canvas;
}
return c;
}
function _saveCanvas( canvas ){
if(!window){ alert("[WINDOW_IS_NULL]"); }
//:We want to give the window a unique
//:name so that we can save multiple times
//:without having to close previous
//:windows.
_name_hash_counter++ ;
var NHC = _name_hash_counter ;
var URL = 'about:blank' ;
var name= 'UNIQUE_WINDOW_ID' + NHC;
var w=window.open( URL, name ) ;
if(!w){ alert("[W_IS_NULL]");}
//:Create the page contents,
//:THEN set the tile. Order Matters.
var DW = "" ;
DW += "<img src='" ;
DW += canvas.toDataURL("image/png");
DW += "' alt='from canvas'/>" ;
w.document.write(DW) ;
w.document.title = "NHC"+NHC ;
}
}//:end class
</script>
</body>
<!-- In IE: Script cannot be outside of body. -->
</html>
Just a little addition to the answer of @dAm2k :
In addition to sudo apt-get remove --purge mysql\*
I've done a sudo apt-get remove --purge mariadb\*
.
I seems that in the new release of debian (stretch), when you install mysql it install mariadb package with it.
Hope it helps.
If we want to add custom HTTP headers to a POST request, we must pass them through a dictionary to the headers
parameter.
Here is an example with a non-empty body and headers:
import requests
import json
url = 'https://somedomain.com'
body = {'name': 'Maryja'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(body), headers=headers)
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
Try this - click on the name of your project on the list of files/folders on the left in Xcode (at the very top of the list). Look at the "Targets" section on the left-hand side of the window to the right. Likely, there's two listed with the second being a "test" item. Right-click on that item and select "delete". Then try to run the project again.
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.
public async Task<Stuff> GetStuff(string id)
{
string path = $"/api/v2/stuff/{id}";
try
{
HttpResponseMessage response = await client.GetAsync(path);
if (response.StatusCode == HttpStatusCode.OK)
{
string json = await response.Content.ReadAsStringAsync();
return JsonUtility.FromJson<Stuff>(json);
}
else
{
Debug.LogError($"Could not retrieve stuff {id}");
}
}
catch (Exception exception)
{
Debug.LogError($"Exception when retrieving stuff {exception}");
}
return null;
}
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
1) Change your .net profile from Client profile to to .Net Framework 4.0 http://msdn.microsoft.com/en-us/library/bb398202.aspx
2) Check your Embed Interop Types flag
(parent window)
<html>
<script language="javascript">
function openWindow() {
window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
</script>
<body>
<form name=frm>
<input id=text1 type=text>
<input type=button onclick="javascript:openWindow()" value="Open window..">
</form>
</body>
</html>
(child window)
<html>
<script language="javascript">
function changeParent() {
window.opener.document.getElementById('text1').value="Value changed..";
window.close();
}
</script>
<body>
<form>
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value..">
</form>
</body>
</html>
Selenium Web Driver Handling Frames
It is impossible to click iframe directly through XPath since it is an iframe. First we have to switch to the frame and then we can click using xpath.
driver.switchTo().frame()
has multiple overloads.
driver.switchTo().frame(name_or_id)
Here your iframe
doesn't have id or name, so not for you.
driver.switchTo().frame(index)
This is the last option to choose, because using index is not stable enough as you could imagine. If this is your only iframe in the page, try driver.switchTo().frame(0)
driver.switchTo().frame(iframe_element)
The most common one. You locate your iframe like other elements, then pass it into the method.
driver.switchTo().
defaultContent(); [parentFrame, defaultContent, frame]
// Based on index position:
int frameIndex = 0;
List<WebElement> listFrames = driver.findElements(By.tagName("iframe"));
System.out.println("list frames "+listFrames.size());
driver.switchTo().frame(listFrames.get( frameIndex ));
// XPath|CssPath Element:
WebElement frameCSSPath = driver.findElement(By.cssSelector("iframe[title='Fill Quote']"));
WebElement frameXPath = driver.findElement(By.xpath(".//iframe[1]"));
WebElement frameTag = driver.findElement(By.tagName("iframe"));
driver.switchTo().frame( frameCSSPath ); // frameXPath, frameTag
driver.switchTo().frame("relative=up"); // focus to parent frame.
driver.switchTo().defaultContent(); // move to the most parent or main frame
// For alert's
Alert alert = driver.switchTo().alert(); // Switch to alert pop-up
alert.accept();
alert.dismiss();
XML Test:
<html>
<IFame id='1'>... parentFrame() « context remains unchanged. <IFame1>
|
-> <IFrame id='2'>... parentFrame() « Change focus to the parent context. <IFame1>
</html>
</html>
<frameset cols="50%,50%">
<Fame id='11'>... defaultContent() « driver focus to top window/first frame. <html>
|
-> <Frame id='22'>... defaultContent() « driver focus to top window/first frame. <Fame11>
frame("relative=up") « focus to parent frame. <Fame11>
</frameset>
</html>
Conversion of RC to Web-Driver Java commands. link.
<frame>
is an HTML element which defines a particular area in which another HTML document can be displayed. A frame should be used within a <frameset>
. « Deprecated. Not for use in new websites.
Yes, set the cell as a RANGE object one time and then use that RANGE object in your code:
Sub RangeExample()
Dim MyRNG As Range
Set MyRNG = Sheets("Sheet1").Cells(23, 4)
Debug.Print MyRNG.Value
End Sub
Alternately you can simply store the value of that cell in memory and reference the actual value, if that's all you really need. That variable can be Long or Double or Single if numeric, or String:
Sub ValueExample()
Dim MyVal As String
MyVal = Sheets("Sheet1").Cells(23, 4).Value
Debug.Print MyVal
End Sub
Simple to me is like this:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables
If you have a lot of columns, then create a variable like $NewRow
like:
$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).
$NewRow | Add-Content -Path $File # Keep no space between content variables
Please note the difference between Set-Content
(overwrites the existing contents) and Add-Content
(appends to the existing contents) of the file.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
For Asp.Net MVC
@Html.ListBox("parameterName", ViewBag.ParameterValueList as MultiSelectList,
new {
@class = "chosen-select form-control"
})
or
@Html.ListBoxFor(model => model.parameterName,
ViewBag.ParameterValueList as MultiSelectList,
new{
data_placeholder = "Select Options ",
@class = "chosen-select form-control"
})
import java.net.DatagramSocket;
import java.net.InetAddress;
try(final DatagramSocket socket = new DatagramSocket()){
socket.connect(InetAddress.getByName("8.8.8.8"), 10002);
ip = socket.getLocalAddress().getHostAddress();
}
This way works well when there are multiple network interfaces. It always returns the preferred outbound IP. The destination 8.8.8.8
is not needed to be reachable.
Connect
on a UDP socket has the following effect: it sets the destination for Send/Recv, discards all packets from other addresses, and - which is what we use - transfers the socket into "connected" state, settings its appropriate fields. This includes checking the existence of the route to the destination according to the system's routing table and setting the local endpoint accordingly. The last part seems to be undocumented officially but it looks like an integral trait of Berkeley sockets API (a side effect of UDP "connected" state) that works reliably in both Windows and Linux across versions and distributions.
So, this method will give the local address that would be used to connect to the specified remote host. There is no real connection established, hence the specified remote ip can be unreachable.
Edit:
As @macomgil says, for MacOS you can do this:
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
System.out.println(socket.getLocalAddress());
I had to go look for ojdbc compatible with version on oracle that was installed this fixed my problem, my bad was thinking one ojdbc would work for all
As Baptiste said, you need to specify the data argument at the geom level. Either
#df1 is the default dataset for all geoms
(plot1 <- ggplot(df1, aes(v, p)) +
geom_point() +
geom_step(data = df2)
)
or
#No default; data explicitly specified for each geom
(plot2 <- ggplot(NULL, aes(v, p)) +
geom_point(data = df1) +
geom_step(data = df2)
)
ok i had the same problem and i fix it like this by removing []
from [{"key":"value"}]
:
- in your php file make shure that you print like this
echo json_encode(array_shift($your_variable));
- in your success function do this
success: function (data) {
var result = $.parseJSON(data);
('.yourclass').append(result['your_key1']);
('.yourclass').append(result['your_key2']);
..
}
and also you can loop it if you want
You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).
All you need to do is (see here)
Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
Note that to convert from degrees to radians, use
glm::radians(degrees)
That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.
note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6
Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
You have a selector ul
on line 252
which is setting list-style: square outside none
(a square bullet). You'll have to change it to list-style: none
or just remove the line.
If you only want to remove the bullets from that specific instance, you can use the specific selector for that list and its items as follows:
ul#groups-list.items-list { list-style: none }
savefig
specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi
kwarg to savefig
). It doesn't inheret it from the DPI of the original figure.
The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi
to fig.savefig
.
E.g.
import matplotlib.pyplot as plt
fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)
You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.
I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.
The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.
and note that:
please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.
The simplest and shorter method would be the following.
string[] stringArray = { "text1", "text2", "text3", "text4" };
string value = "text3";
if(stringArray.Contains(value))
{
// Do something if the value is available in Array.
}
Another case: If you are sending date parameters to a parameterized sql, make sure you sent java.sql.Timestamp
and not java.util.Date
. Otherwise you get
java.sql.SQLRecoverableException
: No more data to read from socket
Example statement:
In our java code, we are using org.apache.commons.dbutils
and we have the following:
final String sqlStatement = "select x from person where date_of_birth between ? and ?";
java.util.Date dtFrom = new Date(); //<-- this will fail
java.util.Date dtTo = new Date(); //<-- this will fail
Object[] params = new Object[]{ dtFrom , dtTo };
final List mapList = (List) query.query(conn, sqlStatement, new MapListHandler(),params);
The above was failing until we changed the date parameters to be java.sql.Timestamp
java.sql.Timestamp tFrom = new java.sql.Timestamp (dtFrom.getTime()); //<-- this is OK
java.sql.Timestamp tTo = new java.sql.Timestamp(dtTo.getTime()); //<-- this is OK
Object[] params = new Object[]{ tFrom , tTo };
final List mapList = (List) query.query(conn, sqlStatement, new MapListHandler(),params);
When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.
So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.
A couple solutions for async loading:
//this function will work cross-browser for loading scripts asynchronously
function loadScript(src, callback)
{
var s,
r,
t;
r = false;
s = document.createElement('script');
s.type = 'text/javascript';
s.src = src;
s.onload = s.onreadystatechange = function() {
//console.log( this.readyState ); //uncomment this line to see which ready states are called.
if ( !r && (!this.readyState || this.readyState == 'complete') )
{
r = true;
callback();
}
};
t = document.getElementsByTagName('script')[0];
t.parentNode.insertBefore(s, t);
}
If you've already got jQuery on the page, just use:
$.getScript(url, successCallback)
*
Additionally, it's possible that your scripts are being loaded/executed before the document is done loading, meaning that you'd need to wait for document.ready
before events can be bound to the elements.
It's not possible to tell specifically what your issue is without seeing the code.
The simplest solution is to keep all of your scripts inline at the bottom of the page, that way they don't block the loading of HTML content while they execute. It also avoids the issue of having to asynchronously load each required script.
If you have a particularly fancy interaction that isn't always used that requires a larger script of some sort, it could be useful to avoid loading that particular script until it's needed (lazy loading).
* scripts loaded with $.getScript
will likely not be cached
For anyone who can use modern features such as the Promise
object, the loadScript
function has become significantly simpler:
function loadScript(src) {
return new Promise(function (resolve, reject) {
var s;
s = document.createElement('script');
s.src = src;
s.onload = resolve;
s.onerror = reject;
document.head.appendChild(s);
});
}
Be aware that this version no longer accepts a callback
argument as the returned promise will handle callback. What previously would have been loadScript(src, callback)
would now be loadScript(src).then(callback)
.
This has the added bonus of being able to detect and handle failures, for example one could call...
loadScript(cdnSource)
.catch(loadScript.bind(null, localSource))
.then(successCallback, failureCallback);
...and it would handle CDN outages gracefully.
Last chance (if other ways don't work): define _ALLOW_ITERATOR_DEBUG_LEVEL_MISMATCH macro in all projects. It will disable "#pragma detect_mismatch" feature which is used in CRT headers.
As mentioned in the comments, you need to install the python-qt4
package - no need to recompile it yourself.
sudo apt-get install python-qt4
You can try this,
UPDATE *tableName* SET *field1* = *your_data*, *field2* = *your_data* ... WHERE 1 = 1;
Well in your case if you want to update your online_status to some value, you can try this,
UPDATE thisTable SET online_status = 'Online' WHERE 1 = 1;
Hope it helps. :D
I agree the number mapp task depends upon the input split but in some of the scenario i could see its little different
case-1 I created a simple mapp task only it creates 2 duplicate out put file (data ia same) command I gave below
bin/hadoop jar contrib/streaming/hadoop-streaming-1.2.1.jar -D mapred.reduce.tasks=0 -input /home/sample.csv -output /home/sample_csv112.txt -mapper /home/amitav/workpython/readcsv.py
Case-2 So I restrcted the mapp task to 1 the out put came correctly with one output file but one reducer also lunched in the UI screen although I restricted the reducer job. The command is given below.
bin/hadoop jar contrib/streaming/hadoop-streaming-1.2.1.jar -D mapred.map.tasks=1 mapred.reduce.tasks=0 -input /home/sample.csv -output /home/sample_csv115.txt -mapper /home/amitav/workpython/readcsv.py
It's a time zone change on December 31st in Shanghai.
See this page for details of 1927 in Shanghai. Basically at midnight at the end of 1927, the clocks went back 5 minutes and 52 seconds. So "1927-12-31 23:54:08" actually happened twice, and it looks like Java is parsing it as the later possible instant for that local date/time - hence the difference.
Just another episode in the often weird and wonderful world of time zones.
EDIT: Stop press! History changes...
The original question would no longer demonstrate quite the same behaviour, if rebuilt with version 2013a of TZDB. In 2013a, the result would be 358 seconds, with a transition time of 23:54:03 instead of 23:54:08.
I only noticed this because I'm collecting questions like this in Noda Time, in the form of unit tests... The test has now been changed, but it just goes to show - not even historical data is safe.
EDIT: History has changed again...
In TZDB 2014f, the time of the change has moved to 1900-12-31, and it's now a mere 343 second change (so the time between t
and t+1
is 344 seconds, if you see what I mean).
EDIT: To answer a question around a transition at 1900... it looks like the Java timezone implementation treats all time zones as simply being in their standard time for any instant before the start of 1900 UTC:
import java.util.TimeZone;
public class Test {
public static void main(String[] args) throws Exception {
long startOf1900Utc = -2208988800000L;
for (String id : TimeZone.getAvailableIDs()) {
TimeZone zone = TimeZone.getTimeZone(id);
if (zone.getRawOffset() != zone.getOffset(startOf1900Utc - 1)) {
System.out.println(id);
}
}
}
}
The code above produces no output on my Windows machine. So any time zone which has any offset other than its standard one at the start of 1900 will count that as a transition. TZDB itself has some data going back earlier than that, and doesn't rely on any idea of a "fixed" standard time (which is what getRawOffset
assumes to be a valid concept) so other libraries needn't introduce this artificial transition.
You can get the actual height of called layout with this code:
public int getLayoutSize() {
// Get the layout id
final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
final AtomicInteger layoutHeight = new AtomicInteger();
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop);
// By now we got the height of titleBar & statusBar
// Now lets get the screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
// Now calculate the height that our layout can be set
// If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also
layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
Log.i("MY", "Layout Height = " + layoutHeight);
// Lastly, set the height of the layout
FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
rootParams.height = layoutHeight.get();
root.setLayoutParams(rootParams);
}
});
return layoutHeight.get();
}
//To send from the activity that is calling another activity via myIntent
myIntent.putExtra("id","10");
startActivity(myIntent);
//To receive from another Activity
Bundle bundle = getIntent().getExtras();
String id=bundle.getString("id");
after generating XML you can just Replace your XML <Marks>... content here </Marks>
tags with <SubjectMarks>... content here </SubjectMarks>tag
. and pass updated XML to your DB.
Edit: I here explain complete process here.
Your XML Generate Like as below.
<NewDataSet>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>80</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>79</Marks>
</StudentMarks>
<StudentMarks>
<StudentID>1</StudentID>
<CourseID>100</CourseID>
<SubjectCode>MT400</SubjectCode>
<Marks>88</Marks>
</StudentMarks>
</NewDataSet>
Here you can assign XML to string variable like as
string strXML = DataSet.GetXML();
strXML = strXML.Replace ("<Marks>","<SubjectMarks>");
strXML = strXML.Replace ("<Marks/>","<SubjectMarks/>");
and now pass strXML To your DB. Hope it will help for you.
This can be done using an attribute selector.
[class~='list']:last-of-type {
background: #000;
}
The class~
selects a specific whole word. This allows your list item to have multiple classes if need be, in various order. It'll still find the exact class "list" and apply the style to the last one.
See a working example here: http://codepen.io/chasebank/pen/ZYyeab
Read more on attribute selectors:
http://css-tricks.com/attribute-selectors/ http://www.w3schools.com/css/css_attribute_selectors.asp
I also had similar issue, after exploring found that testng dependency is causing this issue. After removing the testng dependency from pom (as I dont need it anymore), it started to work fine for me.
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
If you want the text value of a QString object you can use the __str__
property, like this:
>>> a = QtCore.QString("Happy Happy, Joy Joy!")
>>> a
PyQt4.QtCore.QString(u'Happy Happy, Joy Joy!')
>>> a.__str__()
u'Happy Happy, Joy Joy!'
Hope that helps.
Which version of JUnit is this? I've only ever seen delta, not epsilon - but that's a side issue!
From the JUnit javadoc:
delta - the maximum delta between expected and actual for which both numbers are still considered equal.
It's probably overkill, but I typically use a really small number, e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertEquals(123.456, 123.456, DELTA);
}
If you're using hamcrest assertions, you can just use the standard equalTo()
with two doubles (it doesn't use a delta). However if you want a delta, you can just use closeTo()
(see javadoc), e.g.
private static final double DELTA = 1e-15;
@Test
public void testDelta(){
assertThat(123.456, equalTo(123.456));
assertThat(123.456, closeTo(123.456, DELTA));
}
FYI the upcoming JUnit 5 will also make delta optional when calling assertEquals()
with two doubles. The implementation (if you're interested) is:
private static boolean doublesAreEqual(double value1, double value2) {
return Double.doubleToLongBits(value1) == Double.doubleToLongBits(value2);
}
I think the differences are:
Code first
Database first
Model first
I expect that in case of EF 4.1 there are several other features related to Code First vs. Model/Database first. Fluent API used in Code first doesn't offer all features of EDMX. I expect that features like stored procedures mapping, query views, defining views etc. works when using Model/Database first and DbContext
(I haven't tried it yet) but they don't in Code first.
According to this: http://www.vistax64.com/vista-installation-setup/33219-regsvr32-error-0x80004005.html
Run it in a elevated command prompt.
Distinct will sort records in ascending order. If you want to sort in desc order use:
SELECT DISTINCT Category
FROM MonitoringJob
ORDER BY Category DESC
If you want to sort records based on CreationDate field then this field must be in the select statement:
SELECT DISTINCT Category, creationDate
FROM MonitoringJob
ORDER BY CreationDate DESC
That data:image/png;base64
URL is cool, I’ve never run into it before. The long encrypted link is the actual image, i.e. no image call to the server. See RFC 2397 for details.
Side note: I have had trouble getting larger base64 images to render on IE8. I believe IE8 has a 32K limit that can be problematic for larger files. See this other StackOverflow thread for details.
I faced this issue, and that is when a Bean (@Bean) was not instantiated properly as it was not given the correct parameters in my test class.
I was having the same problem. Don't know if you've solved this or not, but what I was really trying to do was access a network share with AD credentials. WNetAddConnection2()
is what you need to use in that case.
Or, if you want to see output in the Output window of Visual Studio, System.Diagnostics.Debug.WriteLine(stuff)
This kind of problems are caused by two reasons:
If most of dependencies can be downloaded, then the reason 1 may be the most likely bug. On the contrary, if most of dependencies have the problem, then u should take a look at settings.xml.
Well, I have tried to fix my problem the whole afternoon, and finally I got it. My problem occurs in settings.xml, not the lose or wrong spelling of settings.xml, but the lose of activeProfiles.
Because I don't like to have duplicate files (log4j.properties in test and main), and I have quite many test classes, they each runwith SpringJUnit4ClassRunner class, so I have to customize it. This is what I use:
import java.io.FileNotFoundException;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;
public class MySpringJUnit4ClassRunner extends SpringJUnit4ClassRunner {
static {
String log4jLocation = "classpath:log4j-oops.properties";
try {
Log4jConfigurer.initLogging(log4jLocation);
} catch (FileNotFoundException ex) {
System.err.println("Cannot Initialize log4j at location: " + log4jLocation);
}
}
public MySpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
}
When you use it, replace SpringJUnit4ClassRunner with MySpringJUnit4ClassRunner
@RunWith(MySpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:conf/applicationContext.xml")
public class TestOrderController {
private Logger LOG = LoggerFactory.getLogger(this.getClass());
private MockMvc mockMvc;
...
}
We Use:
@ContextConfiguration(locations="file:WebContent/WEB-INF/spitterMVC-servlet.xml")
the project is a eclipse dynamic web project, then the path is:
{project name}/WebContent/WEB-INF/spitterMVC-servlet.xml
There is an odd way to do this with xcopy:
echo nnnnnnnnnnn | xcopy /-y source target
Just include as many n's as files you're copying, and it will answer n to all of the overwrite questions.
Try below steps:
It worked for me.
Those are zero-length strings, not null. But if you want to remove them:
firstArray[0] refers to the first element
firstArray[1] refers to the second element
You can move the second into the first thusly:
firstArray[0] = firstArray[1]
If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?
None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:
SET serveroutput on;
DECLARE
testvar varchar(100);
BEGIN
testvar := 'dude';
schema.MY_PROC(testvar);
dbms_output.enable;
dbms_output.put_line(testvar);
END;
And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).
NOTE (differences with mine vs. others):
:
prior to the variable name.package.
or .packages.
between the schema name and the procedure name&
in the variable's value.print
anywherevar
to declare the variableAll of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.
"build & run" > Default for "Run in terminal" --> Enable
to flush the buffer use this command --> fflush(stdout);
you can also use "\n" in printf
or cout
.
Please check out this one: https://github.com/TransparentMarket/junit. It runs the test in the order they are specified (defined within the compiled class file). Also it features a AllTests suite to run tests defined by sub package first. Using the AllTests implementation one can extend the solution in also filtering for properties (we used to use @Fast annotations but those were not published yet).
The memset function is designed to be flexible and simple, even at the expense of speed. In many implementations, it is a simple while loop that copies the specified value one byte at a time over the given number of bytes. If you are wanting a faster memset (or memcpy, memmove, etc), it is almost always possible to code one up yourself.
The simplest customization would be to do single-byte "set" operations until the destination address is 32- or 64-bit aligned (whatever matches your chip's architecture) and then start copying a full CPU register at a time. You may have to do a couple of single-byte "set" operations at the end if your range doesn't end on an aligned address.
Depending on your particular CPU, you might also have some streaming SIMD instructions that can help you out. These will typically work better on aligned addresses, so the above technique for using aligned addresses can be useful here as well.
For zeroing out large sections of memory, you may also see a speed boost by splitting the range into sections and processing each section in parallel (where number of sections is the same as your number or cores/hardware threads).
Most importantly, there's no way to tell if any of this will help unless you try it. At a minimum, take a look at what your compiler emits for each case. See what other compilers emit for their standard 'memset' as well (their implementation might be more efficient than your compiler's).
In my case the Exception occurred because I had removed the "hibernate.enable_lazy_load_no_trans=true" in the "hibernate.properties" file...
I had made a copy and paste typo...
A visual workaround to animating height using CSS3 transitions is to animate the padding instead.
You don't quite get the full wipe effect, but playing around with the transition-duration and padding values should get you close enough. If you don't want to explicitly set height/max-height, this should be what you're looking for.
div {
height: 0;
overflow: hidden;
padding: 0 18px;
-webkit-transition: all .5s ease;
-moz-transition: all .5s ease;
transition: all .5s ease;
}
div.animated {
height: auto;
padding: 24px 18px;
}
http://jsfiddle.net/catharsis/n5XfG/17/ (riffed off stephband's above jsFiddle)
In my case the reason was a bug in the code. The test relied on a certain order of elements in a HashSet
, which turned out to be different when run either in Eclipse or in Maven Surefire.
I am not sure how to see the actual rows/records that come back.
Stored procedures do not return records. They may have a cursor as an output parameter, which is a pointer to a select statement. But it requires additional action to actually bring back rows from that cursor.
In SQL Developer, you can execute a procedure that returns a ref cursor as follows
var rc refcursor
exec proc_name(:rc)
After that, if you execute the following, it will show the results from the cursor:
print rc
Using DISTINCT will work
SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table
REf:- this
My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.
Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.
A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit
and see the there is a text
method.
To answer your specific question:
To make your GUI elements available to the rest of the object, preface them with self.
import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print shost
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
If you could not found run the command,
CentOS:
# yum install dos2unix*
# dos2unix filename.sh
dos2unix: converting file filename.sh to Unix format ...
Ubuntu / Debian:
# apt-get install dos2unix
Make your object something like
public class MyObject : IComparable
{
public string a;
public string b;
virtual public int CompareTo(object obj)
{
if (obj is MyObject)
{
var compareObj = (MyObject)obj;
if (this.a.CompareTo(compareObj.a) == 0)
{
// compare second value
return this.b.CompareTo(compareObj.b);
}
return this.a.CompareTo(compareObj.b);
}
else
{
throw new ArgumentException("Object is not a MyObject ");
}
}
}
also note that the returns for CompareTo :
http://msdn.microsoft.com/en-us/library/system.icomparable.compareto.aspx
Then, if you have a List of MyObject, call .Sort() ie
var objList = new List<MyObject>();
objList.Sort();
Since the tests will be instantiated like a Spring bean too, you just need to implement the ApplicationContextAware interface:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/services-test-config.xml"})
public class MySericeTest implements ApplicationContextAware
{
@Autowired
MyService service;
...
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException
{
// Do something with the context here
}
}
For Windows, you can also whitelist your extension through Windows policies. The full steps are details in this answer, but there are quicker steps:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist
.For instance, in order to whitelist 2 extensions with ID aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
and bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
, create a string value with name 1
and value aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
, and a second value with name 2
and value bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
. This can be sum up by this registry file:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallWhitelist]
"1"="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"2"="bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
EDIT: actually, Chromium docs also indicate how to do it for other OS.
PermGen Space stands for memory allocation for Permanent generation All Java immutable objects come under this category, like String
which is created with literals or with String.intern()
methods and for loading the classes into memory. PermGen Space speeds up our String equality searching.
I came across a similar problem with a meta tag. In the designer.cs
, the control was defined as:
protected global::System.Web.UI.HtmlControl.HtmlGenericControl metatag;
I had to move the definition to the .aspx.cs
file and define as:
protected global::System.Web.UI.HtmlControl.HtmlMeta metatag;
Yea, Indeed @Evert answer is perfectly correct. In addition I'll like to add one more reason that could encounter such error.
>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,200))])
This will be perfectly fine, However, This leads to error:
>>> np.array([np.zeros((20,200)),np.zeros((20,200)),np.zeros((20,201))])
ValueError: could not broadcast input array from shape (20,200) into shape (20)
The numpy arry within the list, must also be the same size.
truncate tableName
That is what you are looking for.
Truncate will delete all records in the table, emptying it.
I think I got what I was looking for..
data.train <- read.table("Assign2.WineComplete.csv",sep=",",header=T)
fit <- rpart(quality ~ ., method="class",data=data.train)
plot(fit)
text(fit, use.n=TRUE)
summary(fit)
Select the block of code that you want indented.
Right-click (or, on Mac, Ctrl-click).
Structure → Re-indent
Visual Studio : Right Bottom : Look for OVR label. Double Click on it.
Bingo...
First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.
Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).
The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)
The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.
In my case, I was using a fixed size header for each section but with a dynamically cell size in each header. The cell's height, depends on the label's height.
Working with:
tableView.estimatedRowHeight = SomeNumber
tableView.rowHeight = UITableViewAutomaticDimension
Works but when using:
tableView.reloadSections(IndexSet(integer: sender.tag) , with: .automatic)
when a lot of headers are not collapsed, creates a lot of bugs such as header duplication (header type x below the same type) and weird animations when the framework reloads with animation, even when using with type .none
(FYI, a fixed header height and cell height works).
The solution is making the use of heightForRowAt
callback and calculate the height of the label by your self (plus the animation looks a lot better). Remember that the height is being called first.
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
{
let object = dataDetailsController.getRowObject(forIndexPath: indexPath)
let label = UILabel(frame: tableView.frame)
let font = UIFont(name: "HelveticaNeue-Bold", size: 25)
label.text = object?.name
label.font = font
label.numberOfLines = 0
label.textAlignment = .center
label.sizeToFit()
let size = label.frame.height
return Float(size) == 0 ? 34 : size
}
The problem with your code is :
String show[]= {rs4.getString(1)};
String actuate[]={rs4.getString(2)};
This will create a new array every time your loop (an not append as you might be assuming) and hence in the end you will have only one element per array.
Here is one more way to solve this :
StringBuilder sids = new StringBuilder ();
StringBuilder lids = new StringBuilder ();
while (rs4.next()) {
sids.append(rs4.getString(1)).append(" ");
lids.append(rs4.getString(2)).append(" ");
}
String show[] = sids.toString().split(" ");
String actuate[] = lids.toString().split(" ");
These arrays will have all the required element.
High performance - every Double
object wraps a single double
value. If you want to store all these values into a double[]
array, then you have to iterate over the collection of Double
instances. A O(1)
mapping is not possible, this should be the fastest you can get:
double[] target = new double[doubles.size()];
for (int i = 0; i < target.length; i++) {
target[i] = doubles.get(i).doubleValue(); // java 1.4 style
// or:
target[i] = doubles.get(i); // java 1.5+ style (outboxing)
}
Thanks for the additional question in the comments ;) Here's the sourcecode of the fitting ArrayUtils#toPrimitive
method:
public static double[] toPrimitive(Double[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return EMPTY_DOUBLE_ARRAY;
}
final double[] result = new double[array.length];
for (int i = 0; i < array.length; i++) {
result[i] = array[i].doubleValue();
}
return result;
}
(And trust me, I didn't use it for my first answer - even though it looks ... pretty similiar :-D )
By the way, the complexity of Marcelos answer is O(2n), because it iterates twice (behind the scenes): first to make a Double[]
from the list, then to unwrap the double
values.
Using JACOB call Office Word is a 100% perfect solution. But it only supports on Windows platform because need Office Word installed.
Using JACOB API call Office Word to convert doc/docx to pdf.
public void convertDocx2pdf(String docxFilePath) {
File docxFile = new File(docxFilePath);
String pdfFile = docxFilePath.substring(0, docxFilePath.lastIndexOf(".docx")) + ".pdf";
if (docxFile.exists()) {
if (!docxFile.isDirectory()) {
ActiveXComponent app = null;
long start = System.currentTimeMillis();
try {
ComThread.InitMTA(true);
app = new ActiveXComponent("Word.Application");
Dispatch documents = app.getProperty("Documents").toDispatch();
Dispatch document = Dispatch.call(documents, "Open", docxFilePath, false, true).toDispatch();
File target = new File(pdfFile);
if (target.exists()) {
target.delete();
}
Dispatch.call(document, "SaveAs", pdfFile, 17);
Dispatch.call(document, "Close", false);
long end = System.currentTimeMillis();
logger.info("============Convert Finished:" + (end - start) + "ms");
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
throw new RuntimeException("pdf convert failed.");
} finally {
if (app != null) {
app.invoke("Quit", new Variant[] {});
}
ComThread.Release();
}
}
}
}
int puts(const char *s);
puts() writes the string s and a trailing newline to stdout.
int printf(const char *format, ...);
The function printf() writes output to stdout, under the control of a format string that specifies how subsequent arguments are converted for output.
I'll use this opportunity to ask you to read the documentation.
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
Coming at it from the perspective of an object oriented programming mindset, REST is analogous to the interface to be implemented, and a RESTfull service is analogous to the actual implementation of the REST "interface".
REST just defines a set of rules that says what it is to be a REST api, and a RESTfull service follows those rules.
Allot of answers above already laid out most of those rules, but I know one of the big things that is required, and in my experience often overlooked, as that a true REST api has to be hyperlink driven, in addition to all of the HTTP PUT, POST, GET, DELETE jazz.
Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:
$('#cat').hover(function()
{
// Mouse Over Callback
}, function()
{
// Mouse Leave callback
});
Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):
$('#cat').hover(function()
{
if($('#dog').is(':visible'))
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
}, function()
{
// Mouse Leave callback
});
You could do
telnet stackoverflow.com 80
And then paste
GET /questions HTTP/1.0
Host: stackoverflow.com
# add the 2 empty lines above but not this one
Here is a transcript
$ telnet stackoverflow.com 80
Trying 151.101.65.69...
Connected to stackoverflow.com.
Escape character is '^]'.
GET /questions HTTP/1.0
Host: stackoverflow.com
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
...
The best version of this I've found on Windows is Joseph Newcomer's "whereis" utility, which is available (with source) from his site.
The article about the development of "whereis" is worth reading.
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
The xlsxwriter
library is great for creating .xlsx
files. The following snippet generates an .xlsx
file from a list of dicts while stating the order and the displayed names:
from xlsxwriter import Workbook
def create_xlsx_file(file_path: str, headers: dict, items: list):
with Workbook(file_path) as workbook:
worksheet = workbook.add_worksheet()
worksheet.write_row(row=0, col=0, data=headers.values())
header_keys = list(headers.keys())
for index, item in enumerate(items):
row = map(lambda field_id: item.get(field_id, ''), header_keys)
worksheet.write_row(row=index + 1, col=0, data=row)
headers = {
'id': 'User Id',
'name': 'Full Name',
'rating': 'Rating',
}
items = [
{'id': 1, 'name': "Ilir Meta", 'rating': 0.06},
{'id': 2, 'name': "Abdelmadjid Tebboune", 'rating': 4.0},
{'id': 3, 'name': "Alexander Lukashenko", 'rating': 3.1},
{'id': 4, 'name': "Miguel Díaz-Canel", 'rating': 0.32}
]
create_xlsx_file("my-xlsx-file.xlsx", headers, items)
Note 1 - I'm purposely not answering to the exact case the OP presented. Instead, I'm presenting a more generic solution IMHO most visitors seek. This question's title is well-indexed in search engines and tracks lots of traffic
Note 2 - If you're not using Python3.6 or newer, consider using
OrderedDict
inheaders
. Before Python3.6 the order indict
was not preserved.
Thanks a lot this note was very useful for me! Was able to send the variable defined under /group_var/vars in the ansible playbook as indicated below.
tasks:
- name: check service account password expiry
- command:
sh /home/monit/get_ldap_attr.sh {{ item }} {{ LDAP_AUTH_USR }}
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
padding-right works for me in Firefox/Chrome on Windows but not in IE. Welcome to the wonderful world of IE standards non-compliance.
See: http://jsfiddle.net/SfPju/466/
HTML
<input type="text" class="foo" value="abcdefghijklmnopqrstuvwxyz"/>
CSS
.foo
{
padding-right: 20px;
}
There is no hostname verification in standard Java SSL sockets or indeed SSL, so that's why you can't set it at that level. Hostname verification is part of HTTPS (RFC 2818): that's why it manifests itself as javax.net.ssl.HostnameVerifier, which is applied to an HttpsURLConnection.
Sometimes a lot of troubles with it. In attribute value of datapicker data is 28-06-2014, but datepicker is show or today or nothing. I decided it in a such way:
<input type="text" class="form-control datepicker" data-value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" />
I added to the input of datapicker attribute data-value, because if call jQuery(this).val() OR jQuery(this).attr('value') - nothing works. I decided init in cycle each datapicker and take its value from attribute data-value:
$("form .datepicker").each(function() {
var time = jQuery(this).data('value');
time = time.split('-');
$(this).datepicker('setDate', new Date(time[2], time[1], time[0], 0, 0, 0));
});
and it is works fine =)
Also if your working directory is different than you can use lpDirectory
procInfo = ShellExecuteEx(nShow=showCmd,
lpVerb=lpVerb,
lpFile=cmd,
lpDirectory= unicode(direc),
lpParameters=params)
Will come handy if changing the path is not a desirable option remove unicode for python 3.X
Heads up that FLUSHALL
may be overkill. FLUSHDB
is the one to flush a database only. FLUSHALL
will wipe out the entire server. As in every database on the server. Since the question was about flushing a database I think this is an important enough distinction to merit a separate answer.
I think your issue is the line:**
sp.DataReceived += port_OnReceiveDatazz;
Shouldn't it be:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
**Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).
I've also seen suggestions that you should turn the following options on for your serial port:
sp.DtrEnable = true; // Data-terminal-ready
sp.RtsEnable = true; // Request-to-send
You may also have to set the handshake to RequestToSend (via the handshake enumeration).
UPDATE:
Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?
So instead of this:
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
sp.Open();
Do this:
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
Let me know how that goes.
This isn't a direct answer as this has already been answered, but everyone was talking about sending the data, but nobody really said what you do when it gets there, and it took me a good half an hour to work it out. So I thought I would help out here.
I will repeat this bit
$data = array(
'cat' => 'moggy',
'dog' => 'mutt'
);
$query = http_build_query(array('mydata' => $data));
$query=urlencode($query);
Obviously you would format it better than this www.someurl.com?x=$query
And to get the data back
parse_str($_GET['x']);
echo $mydata['dog'];
echo $mydata['cat'];
Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:
import static javax.swing.JOptionPane.*;
public class SimpleDialog(){
public static void main(String argv[]) {
showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
}
}
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
To compile you could just initiate a shell call to the csc compiler. You may have a headache trying to keep your paths and switches straight but it certainly can be done.
EDIT: Or better yet, use the CodeDOM as Noldorin suggested...
This works really well for me:
.image-upload>input {_x000D_
display: none;_x000D_
}
_x000D_
<div class="image-upload">_x000D_
<label for="file-input">_x000D_
<img src="https://icon-library.net/images/upload-photo-icon/upload-photo-icon-21.jpg"/>_x000D_
</label>_x000D_
_x000D_
<input id="file-input" type="file" />_x000D_
</div>
_x000D_
Basically the for attribute of the label makes it so that clicking the label is the same as clicking the specified input.
Also, the display property set to none makes it so that the file input isn't rendered at all, hiding it nice and clean.
Tested in Chrome but according to the web should work on all major browsers. :)
EDIT: Added JSFiddle here: https://jsfiddle.net/c5s42vdz/
stopPropagation
will prevent any parent handlers from being executed stopImmediatePropagation
will prevent any parent handlers and also any other handlers from executing
Quick example from the jquery documentation:
$("p").click(function(event) {_x000D_
event.stopImmediatePropagation();_x000D_
});_x000D_
_x000D_
$("p").click(function(event) {_x000D_
// This function won't be executed_x000D_
$(this).css("background-color", "#f00");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>example</p>
_x000D_
Note that the order of the event binding is important here!
$("p").click(function(event) {_x000D_
// This function will now trigger_x000D_
$(this).css("background-color", "#f00");_x000D_
});_x000D_
_x000D_
$("p").click(function(event) {_x000D_
event.stopImmediatePropagation();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>example</p>
_x000D_
You can use assertj-fluent assertions. It has lot of capabilities to write assertions in more human readable - user friendly manner.
In your case, it would be
String x = "foo bar";
assertThat(x).contains("foo");
It is not only for the strings, it can be used to assert lists, collections etc.. in a friendlier way
If you're only running the commands in one shot then you can just use subprocess.check_output
convenience function:
def subprocess_cmd(command):
output = subprocess.check_output(command, shell=True)
print output
I think placing text inbetween the tags is reserved for browsers that cant handle iframes i.e...
<iframe src ="html_intro.asp" width="100%" height="300">
<p>Your browser does not support iframes.</p>
</iframe>
You use the 'src' attribute to set the source of the iframes html...
Hope that helps :)
Simply add spaces for { 2 3 4 5 6 } like these:
cout<<"{";
for(){
cout<<" "<<n; //n is the element to print !
}
cout<<" }";
If you have downloaded these files locally then you can change following classes in bootstrap-social.css, just added border-radius: 50%;
.btn-social-icon.btn-lg{height:45px;width:45px;
padding-left:0;padding-right:0; border-radius: 50%; }
And here is teh HTML
<a class="btn btn-social-icon btn-lg btn-twitter" >
<i class="fa fa-twitter"></i>
</a>
<a class=" btn btn-social-icon btn-lg btn-facebook">
<i class="fa fa-facebook sbg-facebook"></i>
</a>
<a class="btn btn-social-icon btn-lg btn-google-plus">
<i class="fa fa-google-plus"></i>
</a>
It works smooth for me.
file: path=/etc/nologin state=touch
Full equivalent of touch (new in 1.4+) - use stat if you don't want to change file timestamp.
>>> import re
>>> string1 = "498results should get"
>>> int(re.search(r'\d+', string1).group())
498
If there are multiple integers in the string:
>>> map(int, re.findall(r'\d+', string1))
[498]
To GET first paragraph of an article:
https://en.wikipedia.org/w/api.php?action=query&titles=Belgrade&prop=extracts&format=json&exintro=1
I have created short Wikipedia API docs for my own needs. There are working examples on how to get article(s), image(s) and similar.
This is what you need :
if (Value1.StartsWith("abc"))
{
found = true;
}
Aforementioned (?:(?!hede).)*
is great because it can be anchored.
^(?:(?!hede).)*$ # A line without hede
foo(?:(?!hede).)*bar # foo followed by bar, without hede between them
But the following would suffice in this case:
^(?!.*hede) # A line without hede
This simplification is ready to have "AND" clauses added:
^(?!.*hede)(?=.*foo)(?=.*bar) # A line with foo and bar, but without hede
^(?!.*hede)(?=.*foo).*bar # Same
Before pasting into the terminal, try :set paste
and then :set nopaste
after you're done. This will turn off the auto-indent, line-wrap and other features that are messing up your paste.
edit: Also, I should point out that a much better result than =
indenting can usually be obtained by using an external program. For example, I run :%!perltidy
all the time. astyle
, cindent
, etc. can also be used. And, of course, you can map those to a key stroke, and map different ones to the same keystroke depending on file type.
Exit code 137 (128+9) indicates that your program exited due to receiving signal 9, which is SIGKILL
. This also explains the killed
message. The question is, why did you receive that signal?
The most likely reason is probably that your process crossed some limit in the amount of system resources that you are allowed to use. Depending on your OS and configuration, this could mean you had too many open files, used too much filesytem space or something else. The most likely is that your program was using too much memory. Rather than risking things breaking when memory allocations started failing, the system sent a kill signal to the process that was using too much memory.
As I commented earlier, one reason you might hit a memory limit after printing finished counting
is that your call to counter.items()
in your final loop allocates a list that contains all the keys and values from your dictionary. If your dictionary had a lot of data, this might be a very big list. A possible solution would be to use counter.iteritems()
which is a generator. Rather than returning all the items in a list, it lets you iterate over them with much less memory usage.
So, I'd suggest trying this, as your final loop:
for key, value in counter.iteritems():
writer.writerow([key, value])
Note that in Python 3, items
returns a "dictionary view" object which does not have the same overhead as Python 2's version. It replaces iteritems
, so if you later upgrade Python versions, you'll end up changing the loop back to the way it was.
For those of you who need to convert hexadecimal representation of a signed byte from two-character String into byte (which in Java is always signed), there is an example. Parsing a hexadecimal string never gives negative number, which is faulty, because 0xFF is -1 from some point of view (two's complement coding). The principle is to parse the incoming String as int, which is larger than byte, and then wrap around negative numbers. I'm showing only bytes, so that example is short enough.
String inputTwoCharHex="FE"; //whatever your microcontroller data is
int i=Integer.parseInt(inputTwoCharHex,16);
//negative numbers is i now look like 128...255
// shortly i>=128
if (i>=Integer.parseInt("80",16)){
//need to wrap-around negative numbers
//we know that FF is 255 which is -1
//and FE is 254 which is -2 and so on
i=-1-Integer.parseInt("FF",16)+i;
//shortly i=-256+i;
}
byte b=(byte)i;
//b is now surely between -128 and +127
This can be edited to process longer numbers. Just add more FF's or 00's respectively. For parsing 8 hex-character signed integers, you need to use Long.parseLong, because FFFF-FFFF, which is integer -1, wouldn't fit into Integer when represented as a positive number (gives 4294967295). So you need Long to store it. After conversion to negative number and casting back to Integer, it will fit. There is no 8 character hex string, that wouldn't fit integer in the end.
SELECT REPLACE(CONVERT(varchar, MONTH(GetDate()) * 0.01), '0.', '')
Step 1: Simply put all the required code in a "MAIN.BAT" file.
Step 2: Create another bat file, say MainCaller.bat, and just copy/paste these 3 lines of code:
REM THE MAIN FILE WILL BE CALLED FROM HERE..........
CD "File_Path_Where_Main.bat_is_located"
MAIN.BAT > log.txt
Step 3: Just double click "MainCaller.bat".
All the output will be logged into the text file named "log".
What is a DLL?
Dynamic Link Libraries (DLL)s are like EXEs but they are not directly executable. They are similar to .so files in Linux/Unix. That is to say, DLLs are MS's implementation of shared libraries.
DLLs are so much like an EXE that the file format itself is the same. Both EXE and DLLs are based on the Portable Executable (PE) file format. DLLs can also contain COM components and .NET libraries.
What does a DLL contain?
A DLL contains functions, classes, variables, UIs and resources (such as icons, images, files, ...) that an EXE, or other DLL uses.
Types of libraries:
On virtually all operating systems, there are 2 types of libraries. Static libraries and dynamic libraries. In windows the file extensions are as follows: Static libraries (.lib) and dynamic libraries (.dll). The main difference is that static libraries are linked to the executable at compile time; whereas dynamic linked libraries are not linked until run-time.
More on static and dynamic libraries:
You don't normally see static libraries though on your computer, because a static library is embedded directly inside of a module (EXE or DLL). A dynamic library is a stand-alone file.
A DLL can be changed at any time and is only loaded at runtime when an EXE explicitly loads the DLL. A static library cannot be changed once it is compiled within the EXE. A DLL can be updated individually without updating the EXE itself.
Loading a DLL:
A program loads a DLL at startup, via the Win32 API LoadLibrary, or when it is a dependency of another DLL. A program uses the GetProcAddress to load a function or LoadResource to load a resource.
Further reading:
Please check MSDN or Wikipedia for further reading. Also the sources of this answer.
UPD Today I avoid Docker Swarm, secrets, and configs. I'd run it with docker-compose
and the .env
file. As long as I don't need autoscaling. If I do, I'd probably choose k8s. And database passwords, root account or not... Do they really matter when you're running a single database in a container not connected to the outside world?.. I'd like to know what you think about it, but Stack Overflow is probably not well suited for this sort of communication.
Mongo image can be affected by MONGO_INITDB_DATABASE
variable, but it won't create the database. This variable determines current database when running /docker-entrypoint-initdb.d/*
scripts. Since you can't use environment variables in scripts executed by Mongo, I went with a shell script:
docker-swarm.yml
:
version: '3.1'
secrets:
mongo-root-passwd:
file: mongo-root-passwd
mongo-user-passwd:
file: mongo-user-passwd
services:
mongo:
image: mongo:3.2
environment:
MONGO_INITDB_ROOT_USERNAME: $MONGO_ROOT_USER
MONGO_INITDB_ROOT_PASSWORD_FILE: /run/secrets/mongo-root-passwd
MONGO_INITDB_USERNAME: $MONGO_USER
MONGO_INITDB_PASSWORD_FILE: /run/secrets/mongo-user-passwd
MONGO_INITDB_DATABASE: $MONGO_DB
volumes:
- ./init-mongo.sh:/docker-entrypoint-initdb.d/init-mongo.sh
secrets:
- mongo-root-passwd
- mongo-user-passwd
init-mongo.sh
:
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
var admin = db.getSiblingDB('admin');
admin.auth(rootUser, rootPassword);
var user = '$MONGO_INITDB_USERNAME';
var passwd = '$(cat "$MONGO_INITDB_PASSWORD_FILE")';
db.createUser({user: user, pwd: passwd, roles: ["readWrite"]});
EOF
Alternatively, you can store init-mongo.sh
in configs (docker config create
) and mount it with:
configs:
init-mongo.sh:
external: true
...
services:
mongo:
...
configs:
- source: init-mongo.sh
target: /docker-entrypoint-initdb.d/init-mongo.sh
And secrets can be not stored in a file.
Have you closed the < web-app > tag in your web.xml? From what you have posted, the closing tag seems to be missing.
Another possibility is that you need to add ?wsdl at the end of your service url for SoapUI. That one got me as I'm used to WCFClient which didn't need it.
If the function is not defined when using that function in html, such as onclick = ‘function () ', it means function is in a callback, in my case is 'DOMContentLoaded'.
Here you have an example working on py2.6 and py3.2:
from scipy.stats import norm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
# read data from a text file. One number per line
arch = "test/Log(2)_ACRatio.txt"
datos = []
for item in open(arch,'r'):
item = item.strip()
if item != '':
try:
datos.append(float(item))
except ValueError:
pass
# best fit of data
(mu, sigma) = norm.fit(datos)
# the histogram of the data
n, bins, patches = plt.hist(datos, 60, normed=1, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = mlab.normpdf( bins, mu, sigma)
l = plt.plot(bins, y, 'r--', linewidth=2)
#plot
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=%.3f,\ \sigma=%.3f$' %(mu, sigma))
plt.grid(True)
plt.show()
You should be able to do something like:
ArrayList<String> list = new ArrayList<String>();
for( String s : foo )
{
list.add(s);
}
To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:
UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'
If you're using a stack which lets you use SASS, you can use the lighten
function:
$linkcolour: #0000FF;
a {
color: $linkcolour;
}
a.lighter {
color: lighten($linkcolour, 50%);
}
pandas to the rescue:
import pandas as pd
print pd.read_csv('value.txt')
Date price factor_1 factor_2
0 2012-06-11 1600.20 1.255 1.548
1 2012-06-12 1610.02 1.258 1.554
2 2012-06-13 1618.07 1.249 1.552
3 2012-06-14 1624.40 1.253 1.556
4 2012-06-15 1626.15 1.258 1.552
5 2012-06-16 1626.15 1.263 1.558
6 2012-06-17 1626.15 1.264 1.572
This returns pandas DataFrame that is similar to R's
.
Situation:
Solution:
= delete
is a feature introduce in C++11. As per =delete
it will not allowed to call that function.
In detail.
Suppose in a class.
Class ABC{
Int d;
Public:
ABC& operator= (const ABC& obj) =delete
{
}
};
While calling this function for obj assignment it will not allowed. Means assignment operator is going to restrict to copy from one object to another.
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
I hit this issue working with Server Sent Events. The problem was solved when I noticed that the domain name I used to initiate the connection included a trailing slash, e.g. https://foo.bar.bam/
failed with ERR_HTTP_PROTOCOL_ERROR
while https://foo.bar.bam
worked.
That's because if a class is abstract, then by definition you are required to create subclasses of it to instantiate. The subclasses will be required (by the compiler) to implement any interface methods that the abstract class left out.
Following your example code, try making a subclass of AbstractThing
without implementing the m2
method and see what errors the compiler gives you. It will force you to implement this method.
for windows 10 use relativePanel instead of stack panel, and use
relativepanel.alignrightwithpanel="true"
for the contained elements.
float_num.toFixed(2);
Note:toFixed()
will round or pad with zeros if necessary to meet the specified length.
If you want to table do following steps:-
views.py:
def view_info(request):
objs=Model_name.objects.all()
............
return render(request,'template_name',{'objs':obj})
.html page
{% for item in objs %}
<tr>
<td>{{ item.field1 }}</td>
<td>{{ item.field2 }}</td>
<td>{{ item.field3 }}</td>
<td>{{ item.field4 }}</td>
</tr>
{% endfor %}
realpath($_SERVER['SCRIPT_FILENAME'])
For script run under web server $_SERVER['SCRIPT_FILENAME']
will contain the full path to the initially called script, so probably your index.php. realpath()
is not required in this case.
For the script run from console $_SERVER['SCRIPT_FILENAME']
will contain relative path to your initially called script from your current working dir. So unless you changed working directory inside your script it will resolve to the absolute path.
The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:
body {
margin: 0;
padding: 0;
text-align: center;
}
#main_container {
margin: 0 auto;
text-align: left;
}
Below Test Init will also do the job.
[TestInitialize]
public void TestInit()
{
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
YourControllerToBeTestedController = GetYourToBeTestedController();
}
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
First)
Second)
I tried the accepted solution of using the Invoke-Expression cmdlet but it didn't work for me because my arguments had spaces on them. I tried to parse the arguments and escape the spaces but I couldn't properly make it work and also it was really a dirty work around in my opinion. So after some experimenting, my take on the problem is this:
function Invoke-Script
{
param
(
[Parameter(Mandatory = $true)]
[string]
$Script,
[Parameter(Mandatory = $false)]
[object[]]
$ArgumentList
)
$ScriptBlock = [Scriptblock]::Create((Get-Content $Script -Raw))
Invoke-Command -NoNewScope -ArgumentList $ArgumentList -ScriptBlock $ScriptBlock -Verbose
}
# example usage
Invoke-Script $scriptPath $argumentList
The only drawback of this solution is that you need to make sure that your script doesn't have a "Script" or "ArgumentList" parameter.
If you're using Docker Desktop, you can increase Disk image size in Advanced Settings by going to Docker's Preferences.
Here is the screenshot from macOS:
You must set the height of the container explicitly
#container {
height:100%;
width:100%;
position:absolute;
}
I found the same issue with Node 12.19.0 and yarn 1.22.5 on Windows 10. I fixed the problem by installing latest stable python 64-bit with adding the path to Environment Variables during python installation. After python installation, I restarted my machine for env vars.
You must specify that the friend is a template function:
MyClass<T>& operator+=<>(const MyClass<T>& classObj);
See this C++ FAQ Lite answer for details.
You can use this solution. (Use nuget package) The source code is available on : Github: https://github.com/michelcedric/UserImpersonation
More detail https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/
Use:
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
The option you should use is iDisplayLength:
$('#adminProducts').dataTable({
'iDisplayLength': 100
});
$('#table').DataTable({
"lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});
It will Load by default all entries.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
iDisplayLength: -1
});
Or if using 1.10+
$('#example').dataTable({
paging: false
});
If you want to load by default 25 not all do this.
$('#example').dataTable({
aLengthMenu: [
[25, 50, 100, 200, -1],
[25, 50, 100, 200, "All"]
],
});
SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).
The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.
Edited: As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's Java web site, and in particular from the Java SE section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).
Edited 2011-04-06:
The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the sun.com
domain is supposed to go dark. The new page (based on a redirect) is this Java page at the Oracle Tech Network. (See also java.com.)
Edited 2013-01-11: And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. Oracle says no more public updates to Java 6 after February 2013.
Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.
Edited 2015-04-29: And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle affirmed that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).
i usually use this in sh scripts
SCRIPTSRC=`readlink -f "$0" || echo "$0"`
RUN_PATH=`dirname "${SCRIPTSRC}" || echo .`
echo "Running from ${RUN_PATH}"
...
cd ${RUN_PATH}/subfolder
you can use this to automate things ...
You can save the whole jstl object as a Javascript object by converting the whole object to json. It is possible by Jackson in java.
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtil{
public static String toJsonString(Object obj){
ObjectMapper objectMapper = ...; // jackson object mapper
return objectMapper.writeValueAsString(obj);
}
}
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<tlib-version>1.0</tlib-version>
<uri>http://www.your.url/util-functions</uri>
<function>
<name>toJsonString</name>
<function-class>your.package.JsonUtil</function-class>
<function-signature>java.lang.String toJsonString(java.lang.Object)</function-signature>
</function>
</taglib>
<jsp-config>
<tablib>
<taglib-uri>http://www.your.url/util-functions</taglib-uri>
<taglib-location>/WEB-INF/tags/util-functions.tld</taglib-location>
</taglib>
</jsp-confi>
<%@ taglib prefix="uf" uri="http://www.your.url/util-functions" %>
<script>
var myJavaScriptObject = JSON.parse('${uf:toJsonString(myJstlObject)}');
</script>
I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.
I am in the same boot like you. In the case you mention, I would implement the input validation UI component as a React component.
I agree the implementation of the validation logic itself should (must) not be coupled. Therefore I would put it into a separate JS module.
That is, for logic that should not be coupled use a JS module/class in separate file, and use require/import to de-couple the component from the "service".
This allows for dependency injection and unit testing of the two independently.
For Ubunutu 18.04 inside a vagrant box ... This is what helped me
Ensure www-data has permissions to the .htaccess file
sudo chown www-data.www-data .htaccess
edit the apache2 conf to allow for symlinks etc
sudo nano /etc/apache2/apache2.conf
Add this to the file
<Directory /var/www/html/>_x000D_
Options Indexes FollowSymLinks_x000D_
AllowOverride all_x000D_
Require all granted_x000D_
</Directory>
_x000D_
Restart your apache2 server
sudo service apache2 restart
I hope this helps someone.
No you can't they are different. When the app was deployed your controller mappings would be borked for example.
Why do you want to anyway, a controller is not a service, and vice versa.
I had this problem just now, I had to do git rm -f .idea/workspace.xml
now it seems to be gone (I also had to put it into .gitignore
)
Using = avoids wildcards and special characters conflicts in the string when you build the query at run time.
This makes the programmer's life easier by not having to escape all special wildcard characters that might slip in the LIKE clause and not producing the intended result. After all, = is the 99% use case scenario, it would be a pain to have to escape them every time.
rolls eyes at '90s
I also suspect it's a little bit slower, but I doubt it's significant if there are no wildcards in the pattern.
There is a chance that application pool created for you application by default is version 2. So although you see a handler for .svc extension in the list it does not work and treat it as static file. All you need is to open application pool properties and switch it to version 4.
I use TeXMaker. If you're using Ubuntu, it should be in the apt-get repository. To install texmaker
, run:
sudo apt-get install texmaker
In jQuery just use an attribute selector like
$('input[name="locationthemes"]:checked');
to select all checked inputs with name "locationthemes"
console.log($('input[name="locationthemes"]:checked').serialize());
//or
$('input[name="locationthemes"]:checked').each(function() {
console.log(this.value);
});
In VanillaJS
[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {
console.log(cb.value);
});
In ES6/spread operator
[...document.querySelectorAll('input[name="locationthemes"]:checked')]
.forEach((cb) => console.log(cb.value));
There is a function in c called isdigit()
. That will suit you just fine. Example:
int var1 = 'h';
int var2 = '2';
if( isdigit(var1) )
{
printf("var1 = |%c| is a digit\n", var1 );
}
else
{
printf("var1 = |%c| is not a digit\n", var1 );
}
if( isdigit(var2) )
{
printf("var2 = |%c| is a digit\n", var2 );
}
else
{
printf("var2 = |%c| is not a digit\n", var2 );
}
From here
I had this issue when I forgot to add the new .h/.c file I created to the meson recipe so this is just a friendly reminder.
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
I faced the same issue and successfully solved it. My use-case is this.
"Post JSON data to the server and receive an excel file. That excel file is created by the server and returned as a response to the client. Download that response as a file with custom name in browser"
$("#my-button").on("click", function(){
// Data to post
data = {
ids: [1, 2, 3, 4, 5]
};
// Use XMLHttpRequest instead of Jquery $ajax
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var a;
if (xhttp.readyState === 4 && xhttp.status === 200) {
// Trick for making downloadable link
a = document.createElement('a');
a.href = window.URL.createObjectURL(xhttp.response);
// Give filename you wish to download
a.download = "test-file.xls";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
}
};
// Post data to URL which handles post request
xhttp.open("POST", excelDownloadUrl);
xhttp.setRequestHeader("Content-Type", "application/json");
// You should set responseType as blob for binary responses
xhttp.responseType = 'blob';
xhttp.send(JSON.stringify(data));
});
The above snippet is just doing following
Here we need to carefully set few things at the server side. I set few headers in Python Django HttpResponse. You need to set them accordingly if you use other programming languages.
# In python django code
response = HttpResponse(file_content, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
Since I download xls(excel) here, I adjusted contentType to above one. You need to set it according to your file type. You can use this technique to download any kind of files.
It's worth noting that you must open project folder in Visual Studio Code for the debugger to work. I lost few hours to make it work while having only individual file opened in the editor.
Issue explained here
This would also work I believe:
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
var url = '@Html.Raw(Url.Action("Artists", new { NestId = @NestId }))';
window.location.href = url;
})
I came here to find out how to make VSCode (Mac OS) create a new window when a file or folder is opened and VSCode is already running. The same as GitHub Atom does. The answers above haven't answered my query, bit I've found answer myself so will share.
Setting:
window.openFilesInNewWindow
- if set to on
, files will open in a new window.
window.openFoldersInNewWindow
- if set to on
, folders will open in a new window.
Bonus to make it behave like Atom: Set window.newWindowDimensions
to maximised
.
you can use grep, then take lines in jumps:
grep -A1 'blah' logfile | awk 'NR%3==2'
you can also take n lines after match, for example:
seq 100 | grep -A3 .2 | awk 'NR%5==4'
15
25
35
45
55
65
75
85
95
explanation -
here we want to grep all lines that are *2 and take 3 lines after it, which is *5.
seq 100 | grep -A3 .2
will give you:
12
13
14
15
--
22
23
24
25
--
...
the number in the modulo (NR%5) is the added rows by grep (here it's 3 by the flag -A3), +2 extra lines because you have current matching line and also the -- line that the grep is adding.
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
If you can't just use filter join but need to perform some operations on the array's entry:
{% for entry in array %}
User {{ entry.attribute1 }} has id {{ entry.attribute2 }}
{% if not loop.last %}, {% endif %}
{% endfor %}
To change your background color of the botton use:
yourBtn.backgroundColor = UIColor.black
if you are using storyBoard
make sure you have connected your storyBoard
with your viewController
and also that your items are linked.
if you don´t know how to do this check the next link:
How to connect ViewController.swift to ViewController in Storyboard?
Dynamic linking is the only practical way to meet some license requirements such as the LGPL.
To people using Codeigniter (i'm on C3):
The index.php file overwrite php.ini configuration, so on index.php file, line 68:
case 'development':
error_reporting(-1);
ini_set('display_errors', 1);
break;
You can change this option to set what you need. Here's the complete list:
1 E_ERROR
2 E_WARNING
4 E_PARSE
8 E_NOTICE
16 E_CORE_ERROR
32 E_CORE_WARNING
64 E_COMPILE_ERROR
128 E_COMPILE_WARNING
256 E_USER_ERROR
512 E_USER_WARNING
1024 E_USER_NOTICE
6143 E_ALL
2048 E_STRICT
4096 E_RECOVERABLE_ERROR
Hope it helps.
@Jonathan Leffler: Thank you. Your solution works.
A complete working example:
/** compile-time dispatch
$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>
#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)
#ifndef TEST_FUN
# define TEST_FUN some_func
#endif
#define TEST_FUN_NAME STR(TEST_FUN)
void some_func(void)
{
printf("some_func() called\n");
}
void another_func(void)
{
printf("do something else\n");
}
int main(void)
{
TEST_FUN();
printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
return 0;
}
Example:
$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
do something else
TEST_FUN_NAME=another_func
Add library 'Server Runtime' to your java build path, and it shall resolve the issue.
I use the following script to update the default alternative after install jdk.
#!/bin/bash
export JAVA_BIN_DIR=/usr/java/default/bin # replace with your installed directory
cd ${JAVA_BIN_DIR}
a=(java javac javadoc javah javap javaws)
for exe in ${a[@]}; do
sudo update-alternatives --install "/usr/bin/${exe}" "${exe}" "${JAVA_BIN_DIR}/${exe}" 1
sudo update-alternatives --set ${exe} ${JAVA_BIN_DIR}/${exe}
done
You also can do this directly on Frames
In [104]: df = DataFrame(dict(A = True, B = False),index=range(3))
In [105]: df
Out[105]:
A B
0 True False
1 True False
2 True False
In [106]: df.dtypes
Out[106]:
A bool
B bool
dtype: object
In [107]: df.astype(int)
Out[107]:
A B
0 1 0
1 1 0
2 1 0
In [108]: df.astype(int).dtypes
Out[108]:
A int64
B int64
dtype: object
using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
sw.WriteLine(message);
}
Invoke-Expression
, also aliased as iex
. The following will work on your examples #2 and #3:
iex $command
Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:
$command = 'C:\somepath\someexe.exe somearg'
iex $command
However, if the exe is in quotes, you need the help of &
to get it running, as in this example, as run from the commandline:
>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"
And then in the script:
$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"
Likely, you could handle nearly all cases by detecting if the first character of the command string is "
, like in this naive implementation:
function myeval($command) {
if ($command[0] -eq '"') { iex "& $command" }
else { iex $command }
}
But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}
, perhaps for specific exception types/messages, or examine the command string.
If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.
If you follow the principle of Occam's razor, you might think setting all the weights to 0 or 1 would be the best solution. This is not the case.
With every weight the same, all the neurons at each layer are producing the same output. This makes it hard to decide which weights to adjust.
# initialize two NN's with 0 and 1 constant weights
model_0 = Net(constant_weight=0)
model_1 = Net(constant_weight=1)
Validation Accuracy
9.625% -- All Zeros
10.050% -- All Ones
Training Loss
2.304 -- All Zeros
1552.281 -- All Ones
A uniform distribution has the equal probability of picking any number from a set of numbers.
Let's see how well the neural network trains using a uniform weight initialization, where low=0.0
and high=1.0
.
Below, we'll see another way (besides in the Net class code) to initialize the weights of a network. To define weights outside of the model definition, we can:
- Define a function that assigns weights by the type of network layer, then
- Apply those weights to an initialized model using
model.apply(fn)
, which applies a function to each model layer.
# takes in a module and applies the specified weight initialization
def weights_init_uniform(m):
classname = m.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# apply a uniform distribution to the weights and a bias=0
m.weight.data.uniform_(0.0, 1.0)
m.bias.data.fill_(0)
model_uniform = Net()
model_uniform.apply(weights_init_uniform)
Validation Accuracy
36.667% -- Uniform Weights
Training Loss
3.208 -- Uniform Weights
The general rule for setting the weights in a neural network is to set them to be close to zero without being too small.
Good practice is to start your weights in the range of [-y, y] where
y=1/sqrt(n)
(n is the number of inputs to a given neuron).
# takes in a module and applies the specified weight initialization
def weights_init_uniform_rule(m):
classname = m.__class__.__name__
# for every Linear layer in a model..
if classname.find('Linear') != -1:
# get the number of the inputs
n = m.in_features
y = 1.0/np.sqrt(n)
m.weight.data.uniform_(-y, y)
m.bias.data.fill_(0)
# create a new model with these weights
model_rule = Net()
model_rule.apply(weights_init_uniform_rule)
below we compare performance of NN, weights initialized with uniform distribution [-0.5,0.5) versus the one whose weight is initialized using general rule
Validation Accuracy
75.817% -- Centered Weights [-0.5, 0.5)
85.208% -- General Rule [-y, y)
Training Loss
0.705 -- Centered Weights [-0.5, 0.5)
0.469 -- General Rule [-y, y)
The normal distribution should have a mean of 0 and a standard deviation of
y=1/sqrt(n)
, where n is the number of inputs to NN
## takes in a module and applies the specified weight initialization
def weights_init_normal(m):
'''Takes in a module and initializes all linear layers with weight
values taken from a normal distribution.'''
classname = m.__class__.__name__
# for every Linear layer in a model
if classname.find('Linear') != -1:
y = m.in_features
# m.weight.data shoud be taken from a normal distribution
m.weight.data.normal_(0.0,1/np.sqrt(y))
# m.bias.data should be 0
m.bias.data.fill_(0)
below we show the performance of two NN one initialized using uniform-distribution and the other using normal-distribution
Validation Accuracy
85.775% -- Uniform Rule [-y, y)
84.717% -- Normal Distribution
Training Loss
0.329 -- Uniform Rule [-y, y)
0.443 -- Normal Distribution
Combining @comte's answer and dmdip's answer in Get index of a row of a pandas dataframe as an integer
df.tail(1).index.item()
gives you the value of the index.
Note that indices are not always well defined not matter they are multi-indexed or single indexed. Modifying dataframes using indices might result in unexpected behavior. We will have an example with a multi-indexed case but note this is also true in a single-indexed case.
Say we have
df = pd.DataFrame({'x':[1,1,3,3], 'y':[3,3,5,5]}, index=[11,11,12,12]).stack()
11 x 1
y 3
x 1
y 3
12 x 3
y 5 # the index is (12, 'y')
x 3
y 5 # the index is also (12, 'y')
df.tail(1).index.item() # gives (12, 'y')
Trying to access the last element with the index df[12, "y"]
yields
(12, y) 5
(12, y) 5
dtype: int64
If you attempt to modify the dataframe based on the index (12, y)
, you will modify two rows rather than one. Thus, even though we learned to access the value of last row's index, it might not be a good idea if you want to change the values of last row based on its index as there could be many that share the same index. You should use df.iloc[-1]
to access last row in this case though.
Reference
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.item.html
I like to avoid jquery (and other 90-140k libs), and as noted browsers handle onclick first, so here is what I did on a website I created (this example also covers getting a clicked location local x y )
clicksNow-0; //global js, owell
function notify2(e, right) { // called from onclick= and oncontextmenu= (rc)
var x,y,xx,yy;
var ele = document.getElementById('wrap');
// offset fixed parent for local win x y
var xxx= ele.offsetLeft;
var yyy= ele.offsetTop;
//NScape
if (document.layers || document.getElementById&&!document.all) {
xx= e.pageX;
yy= e.pageY;
} else {
xx= e.clientX;
yy= e.clientY;
}
x=xx-xxx;
y=yy-yyy;
clicksNow++;
// 200 (2/10ths a sec) is about a low as i seem to be able to go
setTimeout( "processClick( " + right + " , " + x + " , " + y + ")", 200);
}
function processClick(right, x, y) {
if (clicksNow==0) return; // already processed as dblclick
if (clicksNow==2) alert('dbl');
clicksNow=0;
... handle, etc ...
}
hope that helps
Some Google tooling such as GWT has an embedded version of commons-codec with a pre-1.4 Base64 class. You may need to make such tooling JARs inaccessible to your code by refactoring your project such that only the parts of your code that need that tooling can see the dependency.
I found more accurate way to adding views like linear layouts in kotlin (Pass parent layout in inflate() and false)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
This has worked for me in both SQL Server 2005 and 2008:
SELECT * from TABLE
WHERE FIELDNAME > {ts '2013-02-01 15:00:00.001'}
AND FIELDNAME < {ts '2013-08-05 00:00:00.000'}
Move your code inside of the src
folder. Once it's there, it'll be compiled on-the-fly every time it's saved.
IntelliJ only recognizes files in specific locations as part of the project - namely, anything inside of a blue folder is specifically considered to be source code.
Also - while I can't see all of your source code - be sure that it's proper Java syntax, with a class declared the same as the file and that it has a main
method (specifically public static void main(String[] args)
). IntelliJ won't run code without a main
method (rather, it can't - neither it nor Java would know where to start).
I hit similar issue - in my case Source contained <
, >
characters. 64 bit machines are using new even log - xml base I would say and these characters (set from string) create invalid xml which causes exception. Arguably this should be consider Microsoft issue - not handling the Source (name/string) correctly.
I am totally unable to connect to localdb with any tool including MSSMA, sqlcmd, etc. You would think Microsoft would document this, but I find nothing on MSDN. I have v12 and tried (localdb)\v12.0
and that didn't work. Issuing the command sqllocaldb i MSSQLLocalDB
shows that the local instance is running, but there is no way to connect to it.
c:\> sqllocaldb i MSSQLLocalDB
Name: MSSQLLocalDB
Version: 12.0.2000.8
Shared name:
Owner: CWOLF-PC\cwolf
Auto-create: Yes
State: Running
Last start time: 6/12/2014 8:34:11 AM
Instance pipe name: np:\\.\pipe\LOCALDB#C86052DD\tsql\query
c:\>
c:\> sqlcmd -L
Servers:
;UID:Login ID=?;PWD:Password=?;Trusted_Connection:Use Integrated Security=?;
*APP:AppName=?;*WSID:WorkStation ID=?;
I finally figured it out!! the connect string is (localdb)\MSSQLLocalDB
, e.g.:
$ sqlcmd -S \(localdb\)\\MSSQLLocalDB
1> select 'hello!'
2> go
------
hello!
(1 rows affected)
class Node:
rChild,lChild,parent,data = None,None,None,0
def __init__(self,key):
self.rChild = None
self.lChild = None
self.parent = None
self.data = key
class Tree:
root,size = None,0
def __init__(self):
self.root = None
self.size = 0
def insert(self,someNumber):
self.size = self.size+1
if self.root is None:
self.root = Node(someNumber)
else:
self.insertWithNode(self.root, someNumber)
def insertWithNode(self,node,someNumber):
if node.lChild is None and node.rChild is None:#external node
if someNumber > node.data:
newNode = Node(someNumber)
node.rChild = newNode
newNode.parent = node
else:
newNode = Node(someNumber)
node.lChild = newNode
newNode.parent = node
else: #not external
if someNumber > node.data:
if node.rChild is not None:
self.insertWithNode(node.rChild, someNumber)
else: #if empty node
newNode = Node(someNumber)
node.rChild = newNode
newNode.parent = node
else:
if node.lChild is not None:
self.insertWithNode(node.lChild, someNumber)
else:
newNode = Node(someNumber)
node.lChild = newNode
newNode.parent = node
def printTree(self,someNode):
if someNode is None:
pass
else:
self.printTree(someNode.lChild)
print someNode.data
self.printTree(someNode.rChild)
def main():
t = Tree()
t.insert(5)
t.insert(3)
t.insert(7)
t.insert(4)
t.insert(2)
t.insert(1)
t.insert(6)
t.printTree(t.root)
if __name__ == '__main__':
main()
My solution.
example of string subtraction on date
and time
to get file named "YYYY-MM-DD HH:MM:SS.txt"
echo test > "%date:~0,4%-%date:~5,2%-%date:~8,2% %time:~0,2%_%time:~3,2%_%time:~6,2%.txt"
I use color
to indicate if my script end up successfully, failed, or need some input by changing color of text and background. It really helps when you have some machine in reach of your view but quite far away
color XY
where X and Y is hex value from 0
to F
, where X - background, Y - text, when X = Y color will not change.
color Z
changes text color to 'Z' and sets black background, 'color 0' won't work
for names of colors call
color ?
There is a thorough instruction on GitLab Docs:
https://docs.gitlab.com/ee/user/project/import/github.html
Ensure that any GitHub users who you want to map to GitLab users have either:
From the top navigation bar, click + and select New project.
But Please read the GitLab Docs page for details and hooks!
(it's not much)
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
Trying to access an undefined variable will throw you a ReferenceError
.
A solution to this is to use typeof
:
if (typeof window === "undefined") {
console.log("Oops, `window` is not defined")
}
or a try catch:
try { window } catch (err) {
console.log("Oops, `window` is not defined")
}
While typeof window
is probably the cleanest of the two, the try catch can still be useful in some cases.
Use Console.SetOut
to redirect to a TextWriter
as described here:
http://msdn.microsoft.com/en-us/library/system.console.setout.aspx
If you are using Hg Tortoise just activate the extension "strip" in:
- File/Settings/Extensions/
- Select strip
Then select the bottom revision from where you want to start striping, by doing right click
on it, and selecting:
- Modify history
- Strip
Just like this:
In this example it will erase from the 19th revision to the last one commited(22).
Surprised that nobody's posted this yet -- if you need the indices of the elements while you're looping through the array, you can do this:
arr=(foo bar baz)
for i in ${!arr[@]}
do
echo $i "${arr[i]}"
done
Output:
0 foo
1 bar
2 baz
I find this a lot more elegant than the "traditional" for-loop style (for (( i=0; i<${#arr[@]}; i++ ))
).
(${!arr[@]}
and $i
don't need to be quoted because they're just numbers; some would suggest quoting them anyway, but that's just personal preference.)
import com.github.fge.jackson.JsonLoader;
JsonLoader.fromString("{\"k1\":\"v1\"}")
== JsonNode = {"k1":"v1"}
The Scipy (>=0.11) function scipy.stats.binned_statistic specifically addresses the above question.
For the same example as in the previous answers, the Scipy solution would be
import numpy as np
from scipy.stats import binned_statistic
data = np.random.rand(100)
bin_means = binned_statistic(data, data, bins=10, range=(0, 1))[0]
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
If you want to run it from console, this is what you are looking for:
$ rails console
irb(main)> require "#{Rails.root.to_s}/db/migrate/XXXXX_my_migration.rb"
irb(main)> AddFoo.migrate(:up)
I tried the other answers, but requiring without Rails.root
didnt work for me.
Also, .migrate(:up)
part forces the migration to rerun regardless if it has already run or not. This is useful for when you already ran a migration, have kinda undone it by messing around with the db and want a quick solution to have it up again.
Here is how I have been able to generate multiple maps on the same page using Google Map API V3
. Kindly note that this is an off the cuff code that addresses the issue above.
The HTML bit
<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>
Javascript for map initialization
<script type="text/javascript">
var map, map2;
function initialize(condition) {
// create the maps
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(0.0, 0.0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script>
You can use the default traceroute
command for this purpose, then there will be nothing to install.
traceroute -T -p 9100 <IP address/hostname>
The -T
argument is required so that the TCP protocol is used instead of UDP.
In the rare case when traceroute
isn't available, you can also use ncat
.
nc -Czvw 5 <IP address/hostname> 9100
You can download and import all of Bootstrap, and Popper, with a single command using Fetch Injection:
fetchInject([
'https://npmcdn.com/[email protected]/dist/js/bootstrap.min.js',
'https://cdn.jsdelivr.net/popper.js/1.0.0-beta.3/popper.min.js'
], fetchInject([
'https://cdn.jsdelivr.net/jquery/3.1.1/jquery.slim.min.js',
'https://npmcdn.com/[email protected]/dist/js/tether.min.js'
]));
Add CSS files if you need those too. Adjust versions and external sources to meet your needs and consider using sub-resource integrity checking if you're not hosting the files on your own domain or don't trust the source.
For SQL Server 2008, the command is:
ALTER DATABASE ExampleDB SET RECOVERY SIMPLE
DBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)
ALTER DATABASE ExampleDB SET RECOVERY FULL
This reduced my 14GB log file down to 1MB.
There's also TryParse.
From MSDN:
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
I have written a SP for the this which returns the search results in form of Table name, the Column names in which the search keyword string was found as well as the searches the corresponding rows as shown in below screen shot.
This might not be the most efficient solution but you can always modify and use it according to your need.
IF OBJECT_ID('sp_KeywordSearch', 'P') IS NOT NULL
DROP PROC sp_KeywordSearch
GO
CREATE PROCEDURE sp_KeywordSearch @KeyWord NVARCHAR(100)
AS
BEGIN
DECLARE @Result TABLE
(TableName NVARCHAR(300),
ColumnName NVARCHAR(MAX))
DECLARE @Sql NVARCHAR(MAX),
@TableName NVARCHAR(300),
@ColumnName NVARCHAR(300),
@Count INT
DECLARE @tableCursor CURSOR
SET @tableCursor = CURSOR LOCAL SCROLL FOR
SELECT N'SELECT @Count = COUNT(1) FROM [dbo].[' + T.TABLE_NAME + '] WITH (NOLOCK) WHERE CAST([' + C.COLUMN_NAME +
'] AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + N'%''',
T.TABLE_NAME,
C.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLES AS T WITH (NOLOCK)
INNER JOIN INFORMATION_SCHEMA.COLUMNS AS C WITH (NOLOCK)
ON T.TABLE_SCHEMA = C.TABLE_SCHEMA AND
T.TABLE_NAME = C.TABLE_NAME
WHERE T.TABLE_TYPE = 'BASE TABLE' AND
C.TABLE_SCHEMA = 'dbo' AND
C.DATA_TYPE NOT IN ('image', 'timestamp')
OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
SET @Count = 0
EXEC sys.sp_executesql
@Sql,
N'@Count INT OUTPUT',
@Count OUTPUT
IF @Count > 0
BEGIN
INSERT INTO @Result
(TableName, ColumnName)
VALUES (@TableName, @ColumnName)
END
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
END
CLOSE @tableCursor
DEALLOCATE @tableCursor
SET @tableCursor = CURSOR LOCAL SCROLL FOR
SELECT SUBSTRING(TB.Sql, 1, LEN(TB.Sql) - 3) AS Sql, TB.TableName, SUBSTRING(TB.Columns, 1, LEN(TB.Columns) - 1) AS Columns
FROM (SELECT R.TableName, (SELECT R2.ColumnName + ', ' FROM @Result AS R2 WHERE R.TableName = R2.TableName FOR XML PATH('')) AS Columns,
'SELECT * FROM ' + R.TableName + ' WITH (NOLOCK) WHERE ' +
(SELECT 'CAST(' + R2.ColumnName + ' AS NVARCHAR(MAX)) LIKE ''%' + @KeyWord + '%'' OR '
FROM @Result AS R2
WHERE R.TableName = R2.TableName
FOR
XML PATH('')) AS Sql
FROM @Result AS R
GROUP BY R.TableName) TB
ORDER BY TB.Sql
OPEN @tableCursor
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
SELECT @TableName AS [Table],
@ColumnName AS Columns
EXEC(@Sql)
FETCH NEXT FROM @tableCursor INTO @Sql, @TableName, @ColumnName
END
CLOSE @tableCursor
DEALLOCATE @tableCursor
END
You have an error in you script tag construction, this:
<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
Should look like this:
<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>
You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.
UPDATE
But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
Not sure if you can open them invisibly in the current excel instance
You can open a new instance of excel though, hide it and then open the workbooks
Dim app as New Excel.Application
app.Visible = False 'Visible is False by default, so this isn't necessary
Dim book As Excel.Workbook
Set book = app.Workbooks.Add(fileName)
'
' Do what you have to do
'
book.Close SaveChanges:=False
app.Quit
Set app = Nothing
As others have posted, make sure you clean up after you are finished with any opened workbooks
I honestly suggest that you use moment.js. Just download moment.min.js
and then use this snippet to get your date in whatever format you want:
<script>
$(document).ready(function() {
// set an element
$("#date").val( moment().format('MMM D, YYYY') );
// set a variable
var today = moment().format('D MMM, YYYY');
});
</script>
Use following chart for date formats:
const updateKey = key => console.log(key.split(' ').join('_'));
updateKey('Hello World');
_x000D_
Try using
unset($v)
It seems the only time a variable is not set is when it is specifically unset($v). It sounds like your meaning of 'existence' is different than PHP's definition. NULL is certainly existing, it is NULL.
I am really surprised no one mentioned htobeXX and betohXX functions. They are defined in endian.h and are very similar to network functions htonXX.
memcpy expects the first two arguments to be void*.
Try:
memcpy( (void*)&RTCclk, (void*)&RTCclkBuffert, sizeof(RTCclk) );
P.S. although not necessary, convention dictates the brackets for the sizeof operator. You can get away with a lot in C that leaves code impossible to maintain, so following convention is the mark of a good (employable) C programmer.
I tried using the iframe embed code and the HTML5 player appeared, however, for some reason the iframe was completely breaking my site.
I messed around with the old object embed code and it works perfectly fine. So if you're having problems with the iframe here's the code i used:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/VIDEO_ID?html5=1&rel=0&hl=en_US&version=3"/>
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/VIDEO_ID?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
hope this is useful for someone
I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:
Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:
- NET STOP iisadmin /y
- NET START w3svc
There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.
rails destroy controller lalala
rails destroy model yadayada
rails destroy scaffold hohoho
Rails 3.2 adds a new d
shortcut to the command, so now you can write:
rails d controller lalala
rails d model yadayada
rails d scaffold hohoho
if you're doing a lot of this kind of thing you should consider using numpy
.
In [56]: import random, numpy
In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list
In [58]: a, b = 1, 3
In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])
In response to Seanny123's question, I used this timing code:
import numpy, timeit, random
a, b = 1, 3
lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])
def numpy_way():
numpy.flatnonzero((lst > 1) & (lst < 3))[:10]
def list_comprehension():
[e for e in lst if 1 < e < 3][:10]
print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)
The numpy version is over 60 times faster.
I'm not entirely sure I know what you're asking about, but you can use string functions to create the actual ID that you're looking for.
var base = "common";
var num = 3;
var o = document.getElementById(base + num); // will find id="common3"
If you don't know the actual ID, then you can't look up the object with getElementById, you'd have to find it some other way (by class name, by tag type, by attribute, by parent, by child, etc...).
Now that you've finally given us some of the HTML, you could use this plain JS to find all form elements that have an ID that starts with "poll-":
// get a list of all form objects that have the right type of ID
function findPollForms() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
results.push(list[i]);
}
}
return(results);
}
// return the ID of the first form object that has the right type of ID
function findFirstPollFormID() {
var list = getElementsByTagName("form");
var results = [];
for (var i = 0; i < list.length; i++) {
var id = list[i].id;
if (id && id.search(/^poll-/) != -1) {
return(id);
}
}
return(null);
}
Just to expand on juanchopanza's answer a bit...
for (int i=0; i=((Main.size())-1); i++) {
cout << Main[i] << '\n';
}
does this:
i
and set it to 0
.i
to Main.size() - 1
. Since Main
is empty, Main.size()
is 0
, and i
gets set to -1
.Main[-1]
is an out-of-bounds access. Kaboom.I would add this as a comment to haridsv's response, but I lack the reputation to do so:
Some of us are still stuck on a version of Python older than 2.6 (required for Thread.ident), so I got the code working in Python 2.5 (though without the thread name being displayed) as such:
import traceback
import sys
def dumpstacks(signal, frame):
code = []
for threadId, stack in sys._current_frames().items():
code.append("\n# Thread: %d" % (threadId))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
print "\n".join(code)
import signal
signal.signal(signal.SIGQUIT, dumpstacks)
Try:
ORDER BY x_field='F', x_field='P', x_field='A', x_field='I'
You were on the right track, but by putting x_field only on the F value, the other 3 were treated as constants and not compared against anything in the dataset.
Found on Bytes.com:
string temp = mystring.Replace('\n', '\0');// '\0'
represents an empty char
Cleaning the build folder (Cmd + Shift + Alt + K) worked for me
This is my pure HTML & Javascript solution:
var setHeight = function (element, height) {
if (!element) {;
return false;
}
else {
var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10),
toggleButton = document.createElement('a'),
text = document.createTextNode('...Show more'),
parent = element.parentNode;
toggleButton.src = '#';
toggleButton.className = 'show-more';
toggleButton.style.float = 'right';
toggleButton.style.paddingRight = '15px';
toggleButton.appendChild(text);
parent.insertBefore(toggleButton, element.nextSibling);
element.setAttribute('data-fullheight', elementHeight);
element.style.height = height;
return toggleButton;
}
}
var toggleHeight = function (element, height) {
if (!element) {
return false;
}
else {
var full = element.getAttribute('data-fullheight'),
currentElementHeight = parseInt(element.style.height, 10);
element.style.height = full == currentElementHeight ? height : full + 'px';
}
}
var toggleText = function (element) {
if (!element) {
return false;
}
else {
var text = element.firstChild.nodeValue;
element.firstChild.nodeValue = text == '...Show more' ? '...Show less' : '...Show more';
}
}
var applyToggle = function(elementHeight){
'use strict';
return function(){
toggleHeight(this.previousElementSibling, elementHeight);
toggleText(this);
}
}
var modifyDomElements = function(className, elementHeight){
var elements = document.getElementsByClassName(className);
var toggleButtonsArray = [];
for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) {
var currentElement = elements[index];
var toggleButton = setHeight(currentElement, elementHeight);
toggleButtonsArray.push(toggleButton);
}
for (var index=0, arrayLength=toggleButtonsArray.length; index<arrayLength; index++){
toggleButtonsArray[index].onclick = applyToggle(elementHeight);
}
}
You can then call modifyDomElements function to apply text shortening on all the elements that have shorten-text class name. For that you would need to specify the class name and the height that you would want your elements to be shortened to:
modifyDomElements('shorten-text','50px');
Lastly, in your your html, just set the class name on the element you would want your text to get shorten:
<div class="shorten-text">Your long text goes here...</div>
<input type='text'
name='t1'
id='t1'
maxlength=10
placeholder='typing some text' >
<p></p>
This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character
The problem was the table width. I had used width: 100%
for the table. The table columns are adjusted automatically after removing the width tag.
The best way to do this is to open the file in text mode, read each line with ReadLine(), and then write it to a new file with WriteLine(), skipping the one line you want to delete.
There is no generic delete-a-line-from-file function, as far as I know.
This configuration in httpd.conf work fine for me.
<Directory "c:/wamp/www/">
Options Indexes FollowSymLinks
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
</Directory>
You can make use of cut
, sort
and uniq
commands as follows:
cat input_file | cut -f 1 | sort | uniq
gets unique values in field 1, replacing 1 by 2 will give you unique values in field 2.
Avoiding UUOC :)
cut -f 1 input_file | sort | uniq
EDIT:
To count the number of unique occurences you can make use of wc
command in the chain as:
cut -f 1 input_file | sort | uniq | wc -l
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
Visual Studio 2017 or 2019 is totally unthoughtful on this, because Visual Studio itself requires the output to be in json format, while Visual Studio's default format is "XmlFormat" (config.Formatters.XmlFormatter).
Visual Studio should do this automatically instead of giving developers so much trouble.
To correct this problem, go to the WebApiConfig.cs file, and add
var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter);
after "config.MapHttpAttributeRoutes();" in the Register(HttpConfiguration config) method. This would allow your project to produce json output.
If using VueJS, import all the js dependencies for jQuery extensions first, then import $ second...
import "../assets/js/jquery-2.2.3.min.js"
import "../assets/js/jquery-ui-1.12.1.min.js"
import "../assets/js/jquery.validate.min.js"
import $ from "jquery";
You then need to use jquery from a javascript function called from a custom wrapper defined globally in the VueJS prototype method.
This safeguards use of jQuery and jQuery UI from fighting with VueJS.
Vue.prototype.$fValidateTag = function( sTag, rRules )
{
return ValidateTag( sTag, rRules );
};
function ValidateTag( sTag, rRules )
{
Var rTagT = $( sTag );
return rParentTag.validate( sTag, rRules );
}
You can actually compare files natively right in Sublime Text.
Open Folder...
or
in a projectDiff files...
option.Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables
After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory
should be set to your M2_HOME variable.
Create a file called MoveFiles.bat with the syntax
move c:\Sourcefoldernam\*.* e:\destinationFolder
then schedule a task to run that MoveFiles.bat every 10 hours.
maybe doesnt exists javaee-api-7.0.jar. download this jar and on your project right clik
If the JPEG encoding step is too performance intensive, you could always store the frames uncompressed as BMP images:
ffmpeg -i file.mpg -r 1/1 $filename%03d.bmp
This also has the advantage of not incurring more quality loss through quantization by transcoding to JPEG. (PNG is also lossless but tends to take much longer than JPEG to encode.)
For Intellij IDEA version 11.0.2
File | Project Structure | Artifacts then you should press alt+insert or click the plus icon and create new artifact choose --> jar --> From modules with dependencies.
Next goto Build | Build artifacts --> choose your artifact.
source: http://blogs.jetbrains.com/idea/2010/08/quickly-create-jar-artifact/
Here are some pros/cons I came up with.
multiprocessing
module includes useful abstractions with an interface much like threading.Thread
Queue
module), then manual use of synchronization primitives become a necessity (decisions are needed for the granularity of locking)There are two main reasons why you can use an atomic boolean. First its mutable, you can pass it in as a reference and change the value that is a associated to the boolean itself, for example.
public final class MyThreadSafeClass{
private AtomicBoolean myBoolean = new AtomicBoolean(false);
private SomeThreadSafeObject someObject = new SomeThreadSafeObject();
public boolean doSomething(){
someObject.doSomeWork(myBoolean);
return myBoolean.get(); //will return true
}
}
and in the someObject class
public final class SomeThreadSafeObject{
public void doSomeWork(AtomicBoolean b){
b.set(true);
}
}
More importantly though, its thread safe and can indicate to developers maintaining the class, that this variable is expected to be modified and read from multiple threads. If you do not use an AtomicBoolean you must synchronize the boolean variable you are using by declaring it volatile or synchronizing around the read and write of the field.
How about this
private Object element[] = new Object[] {};
Building off of Kevin Trowbridge's answer
response.header['Content-Type'].should include 'application/json'
If you need to produce "real" Word documents you need a Windows-based web server and COM automation. I highly recommend Joel's article on this subject.
A rather common (but unreliable) alternative is:
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment; filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<b>Fake word document</b>";
echo "</body>";
echo "</html>"
Make sure you don't use external stylesheets. Everything should be in the same file.
Note that this does not send an actual Word document. It merely tricks browsers into offering it as download and defaulting to a .doc
file extension. Older versions of Word may often open this without any warning/security message, and just import the raw HTML into Word. PHP sending sending that misleading Content-Type
header along does not constitute a real file format conversion.
This can be done using HTML5, but will only work in browsers that support it. Here's an example.
Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.
//Date to milliseconds
func currentTimeInMiliseconds() -> Int {
let currentDate = Date()
let since1970 = currentDate.timeIntervalSince1970
return Int(since1970 * 1000)
}
//Milliseconds to date
extension Int {
func dateFromMilliseconds() -> Date {
return Date(timeIntervalSince1970: TimeInterval(self)/1000)
}
}
I removed seemingly useless conversion via string and all those random !
.
It's an iterator returned by the filter function.
If you want a list, just do
list(filter(f, range(2, 25)))
Nonetheless, you can just iterate over this object with a for
loop.
for e in filter(f, range(2, 25)):
do_stuff(e)
For me, I got the "unbound prefix" error on first line here, although I had misspelled android on the fourth line.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
anrdoid:fillViewport="true"
>
For new
you should use delete
. For new[]
use delete[]
. Your second variant is correct.
No, but it has similar behavior, internally.
In C# delegates are used to creates a separate entry point and they work much like a function pointer.
In java there is no thing as function pointer (on a upper look) but internally Java needs to do the same thing in order to achieve these objectives.
For example, creating threads in Java requires a class extending Thread or implementing Runnable, because a class object variable can be used a memory location pointer.
In my case, I found out that the breakpoints have been accidentally deactivated. You can reactivate it again via Debug->Activate Breakpoints [Cmd+Y]. If you notice grey'ed out breakpoint markers instead of the usual blue marker, this is likely the case.
As it turned out you can always toggle breakpoints activation with Cmd+Y keys, you might have hits this combination key not noticing it. This report is based on Xcode 7.2.
There a small difference when u use rgba(255,255,255,a),background color becomes more and more lighter as the value of 'a' increase from 0.0 to 1.0. Where as when use rgba(0,0,0,a), the background color becomes more and more darker as the value of 'a' increases from 0.0 to 1.0. Having said that, its clear that both (255,255,255,0) and (0,0,0,0) make background transparent. (255,255,255,1) would make the background completely white where as (0,0,0,1) would make background completely black.
Since Android 11 (API level 30), most user-installed apps are not visible by default. In your manifest, you must statically declare which apps you are going to get info about, as in the following:
<manifest>
<queries>
<!-- Explicit apps you know in advance about: -->
<package android:name="com.example.this.app"/>
<package android:name="com.example.this.other.app"/>
</queries>
...
</manifest>
Then, @RobinKanters' answer works:
private boolean isPackageInstalled(String packageName, PackageManager packageManager) {
try {
packageManager.getPackageInfo(packageName, 0);
return true;
} catch (PackageManager.NameNotFoundException e) {
return false;
}
}
// ...
// This will return true on Android 11 if the app is installed,
// since we declared it above in the manifest.
isPackageInstalled("com.example.this.app", pm);
// This will return false on Android 11 even if the app is installed:
isPackageInstalled("another.random.app", pm);
Learn more here:
You can use:
new JSONObject(map);
Caution: This will only work for a Map<String, String>!
Other functions you can get from its documentation
http://stleary.github.io/JSON-java/index.html
There is a free open source tool called Anchore that you can use to scan container images. This command will allow you to list all files in a container image
anchore-cli image content myrepo/app:latest files
Basically, tree conflicts arise if there is some restructure in the folder structure on the branch.
You need to delete the conflict folder and use svn clean
once.
Hope this solves your conflict.
The simplest of them all:
<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
(I don't have enough reputation to comment on toscho's answer.)
I have no experience with screen readers and I'm sure your points are valid.
However as far as using a keyboard to manipulate selects, it is trivial to select any option by using the keyboard:
TAB to the control
SPACE to open the select list
UP or DOWN arrows to scroll to the desired list item
ENTER to select the desired item
Only on ENTER does the onchange or (JQuery .change()) event fire.
While I personally would not use a form control for simple menus, there are many web applications that use form controls to change the presentation of the page (eg., sort order.) These can be implemented either by AJAX to load new content into the page, or, in older implementations, by triggering new page loads, which is essentially a page link.
IMHO these are valid uses of a form control.
ADDENDUM: For Windows 8 this will not work; see this excellent answer instead.
Found this solution here: http://www.robvanderwoude.com/clevertricks.php
AT > NUL
IF %ERRORLEVEL% EQU 0 (
ECHO you are Administrator
) ELSE (
ECHO you are NOT Administrator. Exiting...
PING 127.0.0.1 > NUL 2>&1
EXIT /B 1
)
Assuming that doesn't work and since we're talking Win7 you could use the following in Powershell if that's suitable:
$principal = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
If not (and probably not, since you explicitly proposed batch files) then you could write the above in .NET and return an exit code from an exe based on the result for your batch file to use.
According to: https://docs.npmjs.com/files/folders
- Local install (default): puts stuff in ./node_modules of the current package root.
- Global install (with -g): puts stuff in /usr/local or wherever node is installed.
- Install it locally if you're going to require() it.
- Install it globally if you're going to run it on the command line. -> If you need both, then install it in both places, or use npm link.
prefix Configuration
The prefix config defaults to the location where node is installed. On most systems, this is
/usr/local
. On windows, this is the exact location of the node.exe binary.
The docs might be a little outdated, but they explain why global installs can end up in different directories:
(dev) go|c:\srv> npm config ls -l | grep prefix
; prefix = "C:\\Program Files\\nodejs" (overridden)
prefix = "C:\\Users\\bjorn\\AppData\\Roaming\\npm"
Based on the other answers, it may seem like the override is now the default location on Windows, and that I may have installed my office version prior to this override being implemented.
This also suggests a solution for getting all team members to have globals stored in the same absolute path relative to their PC, i.e. (run as Administrator):
mkdir %PROGRAMDATA%\npm
setx PATH "%PROGRAMDATA%\npm;%PATH%" /M
npm config set prefix %PROGRAMDATA%\npm
open a new cmd.exe window and reinstall all global packages.
Explanation (by lineno.):
setx .. /M
to set the
system path (under HKEY_LOCAL_MACHINE). This is what requires you to run
this in a shell with administrator permissions.npm
to use this new path. (Note: folder isn't visible in %PATH% in
this shell, so you must open a new window).Here's a generic helper function with assumption checking:
func assumeNoError(value interface{}, err error) interface{} {
if err != nil {
panic("error encountered when none assumed:" + err.Error())
}
return value
}
Since this returns as an interface{}
, you'll generally need to cast it back to your function's return type.
For example, the OP's example called Get(1)
, which returns (Item, error)
.
item := assumeNoError(Get(1)).(Item)
The trick that makes this possible: Multi-values returned from one function call can be passed in as multi-variable arguments to another function.
As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order.
This answer borrows heavily from existing answers, but none had provided a simple, generic solution of this form.
You need to leverage the @ViewChild
decorator to reference the child component from the parent one by injection:
import { Component, ViewChild } from 'angular2/core';
(...)
@Component({
selector: 'my-app',
template: `
<h1>My First Angular 2 App</h1>
<child></child>
<button (click)="submit()">Submit</button>
`,
directives:[App]
})
export class AppComponent {
@ViewChild(Child) child:Child;
(...)
someOtherMethod() {
this.searchBar.someMethod();
}
}
Here is the updated plunkr: http://plnkr.co/edit/mrVK2j3hJQ04n8vlXLXt?p=preview.
You can notice that the @Query
parameter decorator could also be used:
export class AppComponent {
constructor(@Query(Child) children:QueryList<Child>) {
this.childcmp = children.first();
}
(...)
}
It is possible in 12.1.
Find idea.properties in the BIN folder inside of wherever your IDE is installed, e.g. C:\Program Files (x86)\JetBrains\IntelliJ\bin
Add a new line to the end of that file:
auto.show.quick.doc=true
Start IDEA and just hover your mouse over something:
If you like to do this for open files on Notepad++, you can use Combine plugin: http://www.scout-soft.com/combine/
The correct answer is don't do that, use the HTML Agility Pack.
Edited to add:
To shamelessly steal from the comment below by jesse, and to avoid being accused of inadequately answering the question after all this time, here's a simple, reliable snippet using the HTML Agility Pack that works with even most imperfectly formed, capricious bits of HTML:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Properties.Resources.HtmlContents);
var text = doc.DocumentNode.SelectNodes("//body//text()").Select(node => node.InnerText);
StringBuilder output = new StringBuilder();
foreach (string line in text)
{
output.AppendLine(line);
}
string textOnly = HttpUtility.HtmlDecode(output.ToString());
There are very few defensible cases for using a regular expression for parsing HTML, as HTML can't be parsed correctly without a context-awareness that's very painful to provide even in a nontraditional regex engine. You can get part way there with a RegEx, but you'll need to do manual verifications.
Html Agility Pack can provide you a robust solution that will reduce the need to manually fix up the aberrations that can result from naively treating HTML as a context-free grammar.
A regular expression may get you mostly what you want most of the time, but it will fail on very common cases. If you can find a better/faster parser than HTML Agility Pack, go for it, but please don't subject the world to more broken HTML hackery.
You can do this way:
if($(selector).filter('.class1, .class2').length){
// Or logic
}
if($(selector).filter('.class1, .class2').length){
// And logic
}