This one did work for me in ES 1.7.5:
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
public static void main(String[] args) throws IOException {
Settings settings = ImmutableSettings.settingsBuilder()
.put("client.transport.sniff",true)
.put("cluster.name","elasticcluster").build();
Client client = new TransportClient(settings)
.addTransportAddress(new InetSocketTransportAddress("[ipaddress]",9300));
XContentBuilder builder = null;
try {
builder = jsonBuilder().startObject().field("user", "testdata").field("postdata",new Date()).field("message","testmessage")
.endObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(builder.string());
IndexResponse response = client.prepareIndex("twitter","tweet","1").setSource(builder).execute().actionGet();
client.close();
}
For me this was resolved by adding an explicit default constructor
public MyClassName (){}
Simplest way to achieve pretty logging in Preethi Jain szenario:
LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
loggingInInterceptor.setPrettyLogging(true);
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
loggingOutInterceptor.setPrettyLogging(true);
factory.getInInterceptors().add(loggingInInterceptor);
factory.getOutInterceptors().add(loggingOutInterceptor);
If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code.
Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard Assert
methods to validate it. For example:
// Arrange
MyObject saveObject;
mock.Setup(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()))
.Callback<int, MyObject>((i, obj) => saveObject = obj)
.Returns("xyzzy");
// Act
// ...
// Assert
// Verify Method was called once only
mock.Verify(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()), Times.Once());
// Assert about saveObject
Assert.That(saveObject.TheProperty, Is.EqualTo(2));
The NoSuchMethodError javadoc says this:
Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
In your case, this Error is a strong indication that your webapp is using the wrong version of the JAR defining the org.objectweb.asm.*
classes.
EH is good, generally. But C++'s implementation is not very friendly as it's really hard to tell how good your exception catching coverage is. Java for instance makes this easy, the compiler will tend to fail if you don't handle possible exceptions .
I'm used "for" operator.
try
{
string s = textBox2.Text;
string[] f = s.Split(',');
for (int i = 0; i < f.Length; i++)
{
MailMessage message = new MailMessage(); // Create instance of message
message.To.Add(f[i]); // Add receiver
message.From = new System.Net.Mail.MailAddress(c);// Set sender .In this case the same as the username
message.Subject = label3.Text; // Set subject
message.Body = richTextBox1.Text; // Set body of message
client.Send(message); // Send the message
message = null; // Clean up
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault(); (like Neal mentioned) or by returning false :
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
Interesting question on the differences between prevent default and return false.
In this case, return false will work just fine because the event doesn't need to be propagated.
The proposed solutions I found so far do not cover more complex scenarios.
I needed to convert a query string like
https://random.url.com?Target=Offer&Method=findAll&filters%5Bhas_goals_enabled%5D%5BTRUE%5D=1&filters%5Bstatus%5D=active&fields%5B%5D=id&fields%5B%5D=name&fields%5B%5D=default_goal_name
into an object like:
{
"Target": "Offer",
"Method": "findAll",
"fields": [
"id",
"name",
"default_goal_name"
],
"filters": {
"has_goals_enabled": {
"TRUE": "1"
},
"status": "active"
}
}
OR:
https://random.url.com?Target=Report&Method=getStats&fields%5B%5D=Offer.name&fields%5B%5D=Advertiser.company&fields%5B%5D=Stat.clicks&fields%5B%5D=Stat.conversions&fields%5B%5D=Stat.cpa&fields%5B%5D=Stat.payout&fields%5B%5D=Stat.date&fields%5B%5D=Stat.offer_id&fields%5B%5D=Affiliate.company&groups%5B%5D=Stat.offer_id&groups%5B%5D=Stat.date&filters%5BStat.affiliate_id%5D%5Bconditional%5D=EQUAL_TO&filters%5BStat.affiliate_id%5D%5Bvalues%5D=1831&limit=9999
INTO:
{
"Target": "Report",
"Method": "getStats",
"fields": [
"Offer.name",
"Advertiser.company",
"Stat.clicks",
"Stat.conversions",
"Stat.cpa",
"Stat.payout",
"Stat.date",
"Stat.offer_id",
"Affiliate.company"
],
"groups": [
"Stat.offer_id",
"Stat.date"
],
"limit": "9999",
"filters": {
"Stat.affiliate_id": {
"conditional": "EQUAL_TO",
"values": "1831"
}
}
}
CODE:
var getParamsAsObject = function (query) {
query = query.substring(query.indexOf('?') + 1);
var re = /([^&=]+)=?([^&]*)/g;
var decodeRE = /\+/g;
var decode = function (str) {
return decodeURIComponent(str.replace(decodeRE, " "));
};
var params = {}, e;
while (e = re.exec(query)) {
var k = decode(e[1]), v = decode(e[2]);
if (k.substring(k.length - 2) === '[]') {
k = k.substring(0, k.length - 2);
(params[k] || (params[k] = [])).push(v);
}
else params[k] = v;
}
var assign = function (obj, keyPath, value) {
var lastKeyIndex = keyPath.length - 1;
for (var i = 0; i < lastKeyIndex; ++i) {
var key = keyPath[i];
if (!(key in obj))
obj[key] = {}
obj = obj[key];
}
obj[keyPath[lastKeyIndex]] = value;
}
for (var prop in params) {
var structure = prop.split('[');
if (structure.length > 1) {
var levels = [];
structure.forEach(function (item, i) {
var key = item.replace(/[?[\]\\ ]/g, '');
levels.push(key);
});
assign(params, levels, params[prop]);
delete(params[prop]);
}
}
return params;
};
You were looking for help on installations with pip. You can find it with the following command:
pip install --help
Running pip install -e /path/to/package
installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.
There's also UJMP
The Array.find
method support for Microsoft's browsers started with Edge.
The W3Schools compatibility table states that the support started on version 12, while the Can I Use compatibility table says that the support was unknown between version 12 and 14, being officially supported starting at version 15.
Based on @tetsuo answer, with java 8 :
Integer i = ...
switch (Optional.ofNullable(i).orElse(DEFAULT_VALUE)) {
case DEFAULT_VALUE:
doDefault();
break;
}
If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet
constructor:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Fix it by adding the context as the constructor arg:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Visual Code restart is needed if any update or install or clear cache
Below are some technics which you can use to remove this error:-
Although the given responses are correct, they modify the initial data frame, which is not always desirable (and, given the OP asked for examples "using apply
", it might be they wanted a version that returns a new data frame, as apply
does).
This is possible using assign
: it is valid to assign
to existing columns, as the documentation states (emphasis is mine):
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones. Existing columns that are re-assigned will be overwritten.
In short:
In [1]: import pandas as pd
In [2]: df = pd.DataFrame([{'a': 15, 'b': 15, 'c': 5}, {'a': 20, 'b': 10, 'c': 7}, {'a': 25, 'b': 30, 'c': 9}])
In [3]: df.assign(a=lambda df: df.a / 2)
Out[3]:
a b c
0 7.5 15 5
1 10.0 10 7
2 12.5 30 9
In [4]: df
Out[4]:
a b c
0 15 15 5
1 20 10 7
2 25 30 9
Note that the function will be passed the whole dataframe, not only the column you want to modify, so you will need to make sure you select the right column in your lambda.
Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']
<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['Make']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
echo $maker;
}
?>
I've setup xampp for my localhost as well, I've not done anything with the files created by xampp during or after setup.
But in the '.htaccess' file, make sure you've set it to something like this. Works for me, and this should not make any difference for you.
RewriteEngine On
RewriteRule ^filename/?$ filename.html
Change .html to whatever format you're using.
Make sure your install is clean, and just make the .htaccess file. Also remember to put one .htaccess file for each directory (don't really know if you can use ONE file for all folders, but to be safe, just do this and it will always work.
For those, who wonder how it goes in VS.
MSVC 2015 Update 1, cl.exe version 19.00.24215.1:
#include <iostream>
template<typename X, typename Y>
struct A
{
template<typename Z>
static void f()
{
std::cout << "from A::f():" << std::endl
<< __FUNCTION__ << std::endl
<< __func__ << std::endl
<< __FUNCSIG__ << std::endl;
}
};
void main()
{
std::cout << "from main():" << std::endl
<< __FUNCTION__ << std::endl
<< __func__ << std::endl
<< __FUNCSIG__ << std::endl << std::endl;
A<int, float>::f<bool>();
}
output:
from main(): main main int __cdecl main(void) from A::f(): A<int,float>::f f void __cdecl A<int,float>::f<bool>(void)
Using of __PRETTY_FUNCTION__
triggers undeclared identifier error, as expected.
This can be achieved without body-parser
dependency as well, listen to request:data
and request:end
and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var express = require('express');
var app = express.createServer(express.logger());
app.post('/', function(request, response) {
// push the data to body
var body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
// on end of data, perform necessary action
body = Buffer.concat(body).toString();
response.write(request.body.user);
response.end();
});
});
When you call $("#my_input").val();
it returns as string variable. So use parseFloat
and parseInt
for converting.
When you use parseFloat
your desktop or phone ITSELF understands the meaning of variable.
And plus you can convert a float to string by using toFixed
which has an argument the count of digits as below:
var i = 0.011;
var ss = i.toFixed(2); //It returns 0.01
To show date with time and time-zone
date +"%d-%m-%Y %T.%N %Z"
Output : 22-04-2020 18:01:35.970289239 IST
The best way to go about it would be to get a SynchronizationContext
from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher
directly). For example:
class MyViewModel
{
private readonly SynchronizationContext _syncContext;
public MyViewModel()
{
// we assume this ctor is called from the UI thread!
_syncContext = SynchronizationContext.Current;
}
// ...
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
_syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
}
}
In more complicated build scenarios, it is common to break compilation into stages, with compilation and assembly happening first (output to object files), and linking object files into a final executable or library afterward--this prevents having to recompile all object files when their source files haven't changed. That's why including the linking flag -lm
isn't working when you put it in CFLAGS
(CFLAGS
is used in the compilation stage).
The convention for libraries to be linked is to place them in either LOADLIBES
or LDLIBS
(GNU make includes both, but your mileage may vary):
LDLIBS=-lm
This should allow you to continue using the built-in rules rather than having to write your own linking rule. For other makes, there should be a flag to output built-in rules (for GNU make, this is -p
). If your version of make does not have a built-in rule for linking (or if it does not have a placeholder for -l
directives), you'll need to write your own:
client.o: client.c
$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -c -o $@ $<
client: client.o
$(CC) $(LDFLAGS) $(TARGET_ARCH) $^ $(LOADLIBES) $(LDLIBS) -o $@
I have cooked up a plugin for IntelliJ that – in a way – gives you var
in Java. It's a hack, so the usual disclaimers apply, but if you use IntelliJ for your Java development and want to try it out, it's at https://bitbucket.org/balpha/varsity.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
I don't think answer from Vincent Malgrat is correct. When NVARCHAR2
was introduced long time ago nobody was even talking about Unicode.
Initially Oracle provided VARCHAR2
and NVARCHAR2
to support localization. Common data (include PL/SQL) was hold in VARCHAR2
, most likely US7ASCII
these days. Then you could apply NLS_NCHAR_CHARACTERSET
individually (e.g. WE8ISO8859P1
) for each of your customer in any country without touching the common part of your application.
Nowadays character set AL32UTF8
is the default which fully supports Unicode. In my opinion today there is no reason anymore to use NLS_NCHAR_CHARACTERSET
, i.e. NVARCHAR2
, NCHAR2
, NCLOB
. Note, there are more and more Oracle native functions which do not support NVARCHAR2, so you should really avoid it. Maybe the only reason is when you have to support mainly Asian characters where AL16UTF16
consumes less storage compared to AL32UTF8
.
getElementById
Return Value: An Element Object, representing an element with the specified ID. Returns null if no elements with the specified ID exists see: https://www.w3schools.com/jsref/met_document_getelementbyid.asp
Truthy vs Falsy
In JavaScript, a truthy value is a value that is considered true when evaluated in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN). see: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
When the dom element is not found in the document
it will return null
. null is a Falsy and can be used as boolean expression
in the if statement.
var myElement = document.getElementById("myElement");
if(myElement){
// Element exists
}
in iis manager click directory to protect.
choose authorization rules.
add deny anonymous users rule.
add allow all users rule.
go back to: "in iis manager click directory to protect" click authentication disable all except basic authentication.
the directory is now protected. only people with user accounts can access the folder over the web.
You can call the button_click event by simply passing the arguments to it:
private void SubGraphButton_Click(object sender, RoutedEventArgs args)
{
}
private void ChildNode_Click(object sender, RoutedEventArgs args)
{
SubGraphButton_Click(sender, args);
}
Apparently there is a way to do this efficiently since MongoDB 3.4, see styvane's answer.
Obsolete answer below
You cannot refer to the document itself in an update (yet). You'll need to iterate through the documents and update each document using a function. See this answer for an example, or this one for server-side eval()
.
On Windows 10: Click change security property of myfile.ps1 and change "allow access" by right click / properties on myfile.ps1
This could help, by the way:
The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.
http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
FWIW, here is a sort method for showing which processes are using the most virt memory.
memstat | sort -k 1 -t':' -g -r | less
Sort options are set to first column, using : as column seperator, numeric sort and sort in reverse.
Neither, because both are quite verbose for a very simple task. You can just do:
let result = ({
1: 'One',
2: 'Two',
3: 'Three'
})[opt] ?? 'Default' // opt can be 1, 2, 3 or anything (default)
This, of course, also works with strings, a mix of both or without a default case:
let result = ({
'first': 'One',
'second': 'Two',
3: 'Three'
})[opt] // opt can be 'first', 'second' or 3
It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.
This returns undefined
if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ??
and return a default value.
console.log('Using a valid case:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[1] ?? 'Default')
console.log('Using an invalid case/defaulting:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking.
# Example 1: a is 1 and b is [2, 3]
a, *b = [1, 2, 3]
# Example 2: a is 1, b is [2, 3], and c is 4
a, *b, c = [1, 2, 3, 4]
# Example 3: b is [1, 2] and c is 3
*b, c = [1, 2, 3]
# Example 4: a is 1 and b is []
a, *b = [1]
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
Try the snipped which is mentioned below, it works for me also.
In my layout xml
where I have my TabLayout
, have added style to the TabLayout
like below :
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
style="@style/MyCustomTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMode="fixed" />
and in my style.xml
I have defined the style that is used in my layout xml, check code for styles added below :
<style name="MyCustomTabLayout" parent="Widget.Design.TabLayout">
<item name="android:background">YOUR BACKGROUND COLOR</item>
<item name="tabTextAppearance">@style/MyCustomTabText</item>
<item name="tabSelectedTextColor">SELECTED TAB TEXT COLOR</item>
<item name="tabIndicatorColor">SELECTED TAB INDICATOR COLOR</item>
</style>
<style name="MyCustomTabText" parent="TextAppearance.AppCompat.Button">
<item name="android:textSize">YOUR TEXT SIZE</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@android:color/white</item>
</style>
I hope it will work for you.....
In the embedded world, there is a lot of code out there that uses the following construct:
while(1)
{
if (RCIF)
gx();
if (command_received == command_we_are_waiting_on)
break;
else if ((num_attempts > MAX_ATTEMPTS) || (TickGet() - BaseTick > MAX_TIMEOUT))
return ERROR;
num_attempts++;
}
if (call_some_bool_returning_function())
return TRUE;
else
return FALSE;
This is a very generic example, lots of things are happening behind the curtain, interrupts in particular. Don't use this as boilerplate code, I'm just trying to illustrate an example.
My personal opinion is that there is nothing wrong with writing a loop in this manner as long as appropriate care is taken to prevent remaining in the loop indefinitely.
There is an open issue in Mockito's GitHub about this exact problem.
I have found a simple workaround that does not force you to use annotations in your tests:
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
public final class MockitoCaptorExtensions {
public static <T> ArgumentCaptor<T> captorFor(final CaptorTypeReference<T> argumentTypeReference) {
return new CaptorContainer<T>().captor;
}
public static <T> ArgumentCaptor<T> captorFor(final Class<T> argumentClass) {
return ArgumentCaptor.forClass(argumentClass);
}
public interface CaptorTypeReference<T> {
static <T> CaptorTypeReference<T> genericType() {
return new CaptorTypeReference<T>() {
};
}
default T nullOfGenericType() {
return null;
}
}
private static final class CaptorContainer<T> {
@Captor
private ArgumentCaptor<T> captor;
private CaptorContainer() {
MockitoAnnotations.initMocks(this);
}
}
}
What happens here is that we create a new class with the @Captor
annotation and inject the captor into it. Then we just extract the captor and return it from our static method.
In your test you can use it like so:
ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(genericType());
Or with syntax that resembles Jackson's TypeReference
:
ArgumentCaptor<Supplier<Set<List<Object>>>> fancyCaptor = captorFor(
new CaptorTypeReference<Supplier<Set<List<Object>>>>() {
}
);
It works, because Mockito doesn't actually need any type information (unlike serializers, for example).
Just making something more stable :
var keys = [];
$(document).keydown(function (e) {
if(e.which == 32 || e.which == 70){
keys.push(e.which);
if(keys.length == 2 && keys.indexOf(32) != -1 && keys.indexOf(70) != -1){
alert("it WORKS !!"); //MAKE SOMETHING HERE---------------->
keys.length = 0;
}else if((keys.indexOf(32) == -1 && keys.indexOf(70) != -1) || (keys.indexOf(32) != -1 && keys.indexOf(70) == -1) && (keys.indexOf(32) > 1 || keys.indexOf(70) > 1)){
}else{
keys.length = 0;
}
}else{
keys.length = 0;
}
});
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
You can use AWS API or console UI to create an AMI(Amazon Machine Image) of your running instance. You can specify to reboot the instance when create your AMI. Then you can use AWS API or console UI to launch more instances with the AMI you created.
Try again with this code snippet:
import java.io.*;
class IO {
public static void main(String[] args) {
try {
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
System.out.println(userInput);
}
} catch(IOException ie) {
ie.printStackTrace();
}
}
}
Using try-catch-finally
is better than using throws
. Finding errors and debugging are easier when you use try-catch-finally
.
There definitely is... Use the spawn, expect, and send commands:
spawn test.sh
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes"
There are more examples all over Stack Overflow, see: Help with Expect within a bash script
You may need to install these commands first, depending on your system.
I had a same problem. In my case, the user did not have write permission to the destination directory. Following command helped in my case :
chmod 777 University
The general solution could be a caching iterator. A properly implemented caching iterator works with any Iterator, and saves memory. PHP SPL has a CachingIterator, but it is very odd, and has very limited functionality. However, you can write your own lookahead iterator like this:
<?php
class NeighborIterator implements Iterator
{
protected $oInnerIterator;
protected $hasPrevious = false;
protected $previous = null;
protected $previousKey = null;
protected $hasCurrent = false;
protected $current = null;
protected $currentKey = null;
protected $hasNext = false;
protected $next = null;
protected $nextKey = null;
public function __construct(Iterator $oInnerIterator)
{
$this->oInnerIterator = $oInnerIterator;
}
public function current()
{
return $this->current;
}
public function key()
{
return $this->currentKey;
}
public function next()
{
if ($this->hasCurrent) {
$this->hasPrevious = true;
$this->previous = $this->current;
$this->previousKey = $this->currentKey;
$this->hasCurrent = $this->hasNext;
$this->current = $this->next;
$this->currentKey = $this->nextKey;
if ($this->hasNext) {
$this->oInnerIterator->next();
$this->hasNext = $this->oInnerIterator->valid();
if ($this->hasNext) {
$this->next = $this->oInnerIterator->current();
$this->nextKey = $this->oInnerIterator->key();
} else {
$this->next = null;
$this->nextKey = null;
}
}
}
}
public function rewind()
{
$this->hasPrevious = false;
$this->previous = null;
$this->previousKey = null;
$this->oInnerIterator->rewind();
$this->hasCurrent = $this->oInnerIterator->valid();
if ($this->hasCurrent) {
$this->current = $this->oInnerIterator->current();
$this->currentKey = $this->oInnerIterator->key();
$this->oInnerIterator->next();
$this->hasNext = $this->oInnerIterator->valid();
if ($this->hasNext) {
$this->next = $this->oInnerIterator->current();
$this->nextKey = $this->oInnerIterator->key();
} else {
$this->next = null;
$this->nextKey = null;
}
} else {
$this->current = null;
$this->currentKey = null;
$this->hasNext = false;
$this->next = null;
$this->nextKey = null;
}
}
public function valid()
{
return $this->hasCurrent;
}
public function hasNext()
{
return $this->hasNext;
}
public function getNext()
{
return $this->next;
}
public function getNextKey()
{
return $this->nextKey;
}
public function hasPrevious()
{
return $this->hasPrevious;
}
public function getPrevious()
{
return $this->previous;
}
public function getPreviousKey()
{
return $this->previousKey;
}
}
header("Content-type: text/plain; charset=utf-8");
$arr = [
"a" => "alma",
"b" => "banan",
"c" => "cseresznye",
"d" => "dio",
"e" => "eper",
];
$oNeighborIterator = new NeighborIterator(new ArrayIterator($arr));
foreach ($oNeighborIterator as $key => $value) {
// you can get previous and next values:
if (!$oNeighborIterator->hasPrevious()) {
echo "{FIRST}\n";
}
echo $oNeighborIterator->getPreviousKey() . " => " . $oNeighborIterator->getPrevious() . " -----> ";
echo "[ " . $key . " => " . $value . " ] -----> ";
echo $oNeighborIterator->getNextKey() . " => " . $oNeighborIterator->getNext() . "\n";
if (!$oNeighborIterator->hasNext()) {
echo "{LAST}\n";
}
}
The method that proposed by 'leoj' does not allow passing parameters with spaces. Us it:
cmd.exe /v /c %CD:~0,2%"%CD:~2%\bat\bat\run.bat" "Par1-1 Par1-2" Par2
Which will be similar double quote written as in path
C:"\Program Files\anyProgram.exe" "Par1-1 Par1-2" Par2
Size of a pointer should be 8 byte on any 64-bit C/C++ compiler, but not necessarily size of int.
Let's approach this like Archimedes would have.
How can we generate a point uniformly in a triangle ABC, where |AB|=|BC|? Let's make this easier by extending to a parallelogram ABCD. It's easy to generate points uniformly in ABCD. We uniformly pick a random point X on AB and Y on BC and choose Z such that XBYZ is a parallelogram. To get a uniformly chosen point in the original triangle we just fold any points that appear in ADC back down to ABC along AC.
Now consider a circle. In the limit we can think of it as infinitely many isoceles triangles ABC with B at the origin and A and C on the circumference vanishingly close to each other. We can pick one of these triangles simply by picking an angle theta. So we now need to generate a distance from the center by picking a point in the sliver ABC. Again, extend to ABCD, where D is now twice the radius from the circle center.
Picking a random point in ABCD is easy using the above method. Pick a random point on AB. Uniformly pick a random point on BC. Ie. pick a pair of random numbers x and y uniformly on [0,R] giving distances from the center. Our triangle is a thin sliver so AB and BC are essentially parallel. So the point Z is simply a distance x+y from the origin. If x+y>R we fold back down.
Here's the complete algorithm for R=1. I hope you agree it's pretty simple. It uses trig, but you can give a guarantee on how long it'll take, and how many random()
calls it needs, unlike rejection sampling.
t = 2*pi*random()
u = random()+random()
r = if u>1 then 2-u else u
[r*cos(t), r*sin(t)]
Here it is in Mathematica.
f[] := Block[{u, t, r},
u = Random[] + Random[];
t = Random[] 2 Pi;
r = If[u > 1, 2 - u, u];
{r Cos[t], r Sin[t]}
]
ListPlot[Table[f[], {10000}], AspectRatio -> Automatic]
A generator expression is probably the most performant and simple solution to your problem:
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2
There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.
The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.
Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:
# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)
We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set?
That's where the advantage of using the generator method comes into play.
Rather than constructing a new list, we'll use your existing list as our iterable, and use next()
to get the first item from our generator.
Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:
worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]
# [10000000]
# 2 function calls in 3.885 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 3.885 3.885 3.885 3.885 so_lc.py:1(<module>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]
# [0]
# 2 function calls in 3.864 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 3.864 3.864 3.864 3.864 so_lc.py:1(<module>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.
# 10000000
# 5 function calls in 1.733 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 2 1.455 0.727 1.455 0.727 so_lc.py:10(<genexpr>)
# 1 0.278 0.278 1.733 1.733 so_lc.py:9(<module>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
# 1 0.000 0.000 1.455 1.455 {next}
best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)
# 0
# 5 function calls in 0.316 seconds
#
# Ordered by: standard name
#
# ncalls tottime percall cumtime percall filename:lineno(function)
# 1 0.316 0.316 0.316 0.316 so_lc.py:6(<module>)
# 2 0.000 0.000 0.000 0.000 so_lc.py:7(<genexpr>)
# 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
# 1 0.000 0.000 0.000 0.000 {next}
WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.
Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.
Note that this is all basic, built-in python. We don't need to import anything or use any libraries.
I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.
Simple solution is Warp your select box inside a div, and style the div matching your design. Set opacity:0 to select box, it will make the select box invisible. Insert a span tag with jQuery and change its value dynamically if user change drop down value. Total demonstration shown in this tutorial with code explanation. Hope it will solve your problem.
JQuery Code looks like similar to this.
<script>
$(document).ready(function(){
$('.dropdown_menu').each(function(){
var baseData = $(this).find("select option:selected").html();
$(this).prepend("<span>" + baseData + "</span>");
});
$(".dropdown_menu select").change(function(e){
var nodeOne = $(this).val();
var currentNode = $(this).find("option[value='"+ nodeOne +"']").text();
$(this).parents(".dropdown_menu").find("span").text(currentNode);
});
});
</script>
@IanDevlin is correct. MDN's rules say the following:
"The HTML Header Element "" defines a page header — typically containing the logo and name of the site and possibly a horizontal menu..."
The word "possibly" there is key. It goes on to say that the header doesn't necessarily need to be a site header. For instance you could include a "header" on a pop-up modal or on other modular parts of the document where there is a header and it would be helpful for a user on a screen reader to know about it.
It terms of the implicit use of NAV you can use it anywhere there is grouped site navigation, although it's usually omitted from the "footer" section for mini-navs / important site links.
Really it comes down to personal / team choice. Decide what you and your team feel is more semantic and more important and the try to be consistent. For me, if the nav is inline with the logo and the main site's "h1" then it makes sense to put it in the "header" but if you have a different design choice then decide on a case by case basis.
Most importantly check out the docs and be sure if you choose to omit or include you understand why you are making that particular decision.
var select =$('#selectbox').val();
The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.
The following code should allow you to check for the existance of the header you're after in Request.Headers
:
if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
// Can now check if the value is true:
var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}
As of Twig 1.5, the correct answer is to use the dump function. It is fully documented in the Twig documentation. Here is the documentation to enable this inside Symfony2.
{{ dump(user) }}
I got rid of the problem by unchecking the option for "Alert before overwriting cells" in Excel options. I'm using Excel 2007
seq 1 100 | python3 -c 'print(__import__("random").choice(__import__("sys").stdin.readlines()))'
declare @d1 datetime, @d2 datetime
select @d1 = '4/19/2017', @d2 = '5/7/2017'
DECLARE @Counter int = datediff(DAY,@d1 ,@d2 )
DECLARE @C int = 0
DECLARE @SUM int = 0
WHILE @Counter > 0
begin
SET @SUM = @SUM + IIF(DATENAME(dw,
DATEADD(day,@c,@d1))IN('Sunday','Monday','Tuesday','Wednesday','Thursday')
,1,0)
SET @Counter = @Counter - 1
set @c = @c +1
end
select @Sum
You can use rebase, for instance, git rebase our-team
when you are on your branch featurex
It will move the start point of the branch at the end of your our-team
branch, merging all changes in your featurex
branch.
Anyone wanting a drop-in fully SLF4J compatible solution to this problem might want to check out Lidalia SLF4J Extensions - it's on Maven Central.
Same as @axtavt, but you can use also the RequestDispatcher constant.
request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
Like the previous comment mention, the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." its a warning because you are missunderstanding this line: mongoose.connect('mongodb://localhost/info'); and browsing this url: http://localhost:28017/
However, if you want to see the mongo's admin web page, you could do it, with this command:
mongod --rest --httpinterface
browsing this url: http://localhost:28017/
the parameter httpinterface activate the admin web page, and the parameter rest its needed for activate the rest services the page require
Here is answer for your question.
db.getCollection('users').aggregate([
{$match : {admin : 1}},
{$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
{$project : {
posts : { $filter : {input : "$posts" , as : "post", cond : { $eq : ['$$post.via' , 'facebook'] } } },
admin : 1
}}
])
Or either you can go with mongodb group option.
db.getCollection('users').aggregate([
{$match : {admin : 1}},
{$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
{$unwind : "$posts"},
{$match : {"posts.via":"facebook"}},
{ $group : {
_id : "$_id",
posts : {$push : "$posts"}
}}
])
When just a single result is needed, then no loop should be used. Just fetch the row right away.
In case you need to fetch the entire row into associative array:
$row = $result->fetch_assoc();
in case you need just a single value
$row = $result->fetch_row();
$value = $row[0] ?? false;
The last example will return the first column from the first returned row, or false
if no row was returned. It can be also shortened to a single line,
$value = $result->fetch_row()[0] ?? false;
Below are complete examples for different use cases
When variables are to be used in the query, then a prepared statement must be used. For example, given we have a variable $id
:
$query = "SELECT ssfullname, ssemail FROM userss WHERE ud=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$row = $result->fetch_assoc();
// in case you need just a single value
$query = "SELECT count(*) FROM userss WHERE id=?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $id);
$stmt->execute()
$result = $stmt->get_result();
$value = $result->fetch_row()[0] ?? false;
The detailed explanation of the above process can be found in my article. As to why you must follow it is explained in this famous question
In your case, where no variables to be used in the query, you can use the query()
method:
$query = "SELECT ssfullname, ssemail FROM userss ORDER BY ssid";
$result = $conn->query($query);
// in case you need an array
$row = $result->fetch_assoc();
// OR in case you need just a single value
$value = $result->fetch_row()[0] ?? false;
By the way, although using raw API while learning is okay, consider using some database abstraction library or at least a helper function in the future:
// using a helper function
$sql = "SELECT email FROM users WHERE id=?";
$value = prepared_select($conn, $sql, [$id])->fetch_row[0] ?? false;
// using a database helper class
$email = $db->getCol("SELECT email FROM users WHERE id=?", [$id]);
As you can see, although a helper function can reduce the amount of code, a class' method could encapsulate all the repetitive code inside, making you to write only meaningful parts - the query, the input parameters and the desired result format (in the form of the method's name).
It would appear that as of now (April of 2017) that the following works:
public string LoggedInUser => User.Identity.Name;
At least while within a Controller
For those who are upgrading to v1.0 of Android Studio and see the error Gradle DSL method not found: 'runProguard', If you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files. i.e.
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
select x.dbname as db_name, x.table_name as table_name, x.bytesize as the_size from
(select
table_schema as dbname,
sum(index_length+data_length) as bytesize,
table_name
from
information_schema.tables
group by table_schema
) x
where
x.bytesize > 999999
order by x.bytesize desc;
Just use the GLYPHICONS and you will be able to change color just setting the CSS:
#myglyphcustom {
color:#F00;
}
YourKit Java Profiler seems to handle them too.
Both, FILL_PARENT
and MATCH_PARENT
are the same properties. FILL_PARENT
was deprecated in API level 8.
I prefer Buffer.from(data.Body).toString('utf8')
. It supports encoding parameters. With other AWS services (ex. Kinesis Streams) someone may want to replace 'utf8'
encoding with 'base64'
.
new AWS.S3().getObject(
{ Bucket: this.awsBucketName, Key: keyName },
function(err, data) {
if (!err) {
const body = Buffer.from(data.Body).toString('utf8');
console.log(body);
}
}
);
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern()
Basically doing String.intern() on a series of strings will ensure that all strings having same contents share same memory. So if you have list of names where 'john' appears 1000 times, by interning you ensure only one 'john' is actually allocated memory.
This can be useful to reduce memory requirements of your program. But be aware that the cache is maintained by JVM in permanent memory pool which is usually limited in size compared to heap so you should not use intern if you don't have too many duplicate values.
More on memory constraints of using intern()
On one hand, it is true that you can remove String duplicates by internalizing them. The problem is that the internalized strings go to the Permanent Generation, which is an area of the JVM that is reserved for non-user objects, like Classes, Methods and other internal JVM objects. The size of this area is limited, and is usually much smaller than the heap. Calling intern() on a String has the effect of moving it out from the heap into the permanent generation, and you risk running out of PermGen space.
-- From: http://www.codeinstructions.com/2009/01/busting-javalangstringintern-myths.html
From JDK 7 (I mean in HotSpot), something has changed.
In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences.
-- From Java SE 7 Features and Enhancements
Update: Interned strings are stored in main heap from Java 7 onwards. http://www.oracle.com/technetwork/java/javase/jdk7-relnotes-418459.html#jdk7changes
This array_group_by function achieves what you are looking for:
$grouped = array_group_by($arr, 'id');
It even supports multi-level groupings:
$grouped = array_group_by($arr, 'id', 'part_no');
I just want to point out, even syntax of itemgetter looks really neat, but it's kinda slow when perform on large list.
import timeit
from operator import itemgetter
start=timeit.default_timer()
for i in range(1000000):
itemgetter(0,2,3)(myList)
print ("Itemgetter took ", (timeit.default_timer()-start))
Itemgetter took 1.065209062149279
start=timeit.default_timer()
for i in range(1000000):
myList[0],myList[2],myList[3]
print ("Multiple slice took ", (timeit.default_timer()-start))
Multiple slice took 0.6225321444745759
This query:
SELECT ROW_NUMBER() OVER(ORDER BY UserId) From Users WHERE UserName='Joe'
will return all rows where the UserName
is 'Joe'
UNLESS you have no UserName='Joe'
They will be listed in order of UserID
and the row_number
field will start with 1 and increment however many rows contain UserName='Joe'
If it does not work for you then your WHERE
command has an issue OR there is no UserID
in the table. Check spelling for both fields UserID
and UserName
.
In the simple case, a repository might have a single .gitignore
file in its root directory, which applies recursively to the entire repository. However, it is also possible to have additional .gitignore
files in subdirectories. The rules in these nested .gitignore
files apply only to the files under the directory where they are located. The Linux kernel source repository has 206 .gitignore
files.
-- this is what i read from progit.pdf
(version 2), P32
The standard way to do division is by implementing binary long-division. This involves subtraction, so as long as you don't discount this as not a bit-wise operation, then this is what you should do. (Note that you can of course implement subtraction, very tediously, using bitwise logical operations.)
In essence, if you're doing Q = N/D
:
N
and D
.t = (N - D);
.(t >= 0)
, then set the least significant bit of Q
to 1, and set N = t
.N
by 1.Q
by 1.Loop for as many output bits (including fractional) as you require, then apply a final shift to undo what you did in Step 1.
You can try putting a new line in the data:
<data>Foo bar baz
baz bar</data>
If that does not work you might need to parse the string manually.
If you need direct XAML that's easy by the way:
<TextBlock>
Lorem <LineBreak/>
Ipsum
</TextBlock>
just change the content-type to application/json when you use JSON with POST/PUT, etc...
Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
Please rather try:
$JAVA_HOME/bin/java -version
Maven uses $JAVA_HOME
for classpath resolution of JRE libs.
To be sure to use a certain JDK, set it explicitly before compiling, for example:
export JAVA_HOME=/usr/java/jdk1.7.0_51
Isn't there a version < 1.7 and you're using Maven 3.3.1? In this case the reason is a new prerequisite: https://issues.apache.org/jira/browse/MNG-5780
Just set the selectIndex
of the associated <select>
tag to -1
as the last step of your processing event.
mySelect = document.getElementById("idlist");
mySelect.selectedIndex = -1;
It works every time, removing the highlight and allowing you to select the same (or different) element again .
mime_content_type() is deprecated, so you won't be able to count on it working in the future. There is a "fileinfo" PECL extension, but I haven't heard good things about it.
If you are running on a *nix server, you can do the following, which has worked fine for me:
$file = escapeshellarg( $filename );
$mime = shell_exec("file -bi " . $file);
$filename should probably include the absolute path.
A simple solution would be doing something like this:
mysqldump -u myuser --no-create-info --extended-insert=FALSE databasename | grep -i "<search string>"
Adding another version based on example above by @ricky89 and @mklement0 with few improvements:
Script to process:
LF-to-CRLF.ps1:
# get current dir
$currentDirectory = Split-Path $MyInvocation.MyCommand.Path -Parent
# create subdir CR-to-CRLF for new files
$outDir = $(Join-Path $currentDirectory "CR-to-CRLF")
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
# get all .txt files
Get-ChildItem $currentDirectory -Force | Where-Object {$_.extension -eq ".txt"} | ForEach-Object {
$file = New-Object System.IO.StreamReader -Arg $_.FullName
# Resulting file will be in CR-to-CRLF subdir
$outstream = [System.IO.StreamWriter] $(Join-Path $outDir $($_.BaseName + $_.Extension))
$count = 0
# read line by line, replace CR with CRLF in each by saving it with $outstream.WriteLine
while ($line = $file.ReadLine()) {
$count += 1
$outstream.WriteLine($line)
}
$file.close()
$outstream.close()
Write-Host ("$_`: " + $count + ' lines processed.')
}
In the past, I had no error logs in two cases:
php_error_log
file..htaccess
, for example wrong rewrite module settings. In this situation errors are logged to Apache error_log
file.I use the trick suggested by Peter Lada all the time, dubbed as "fake submodules":
http://debuggable.com/posts/git-fake-submodules:4b563ee4-f3cc-4061-967e-0e48cbdd56cb
It's very useful in several scenarios (p.e. I use it to keep all my Emacs config in a repository, including the current HEAD of all git repositories inside the elpa/el-get package directories, so I could easily roll back/forward to a known working version when some update breaks something).
The server might require some kind of encryption and secure authentication.
see http://swiftmailer.org/docs/sending.html#encrypted-smtp
It's in fact almost the same in Python.. :-)
import datetime
year = datetime.date.today().year
Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:
import datetime
year = datetime.datetime.today().year
(Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).
One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.
You could create a user form:
The argument associated with the %n
will be treated as an int*
and is filled with the number of total characters printed at that point in the printf
.
Splitting a single number to it's digits (as answered by all):
>>> [int(i) for i in str(12345)]
[1, 2, 3, 4, 5]
But, to get digits from a list of numbers:
>>> [int(d) for d in ''.join(str(x) for x in [12, 34, 5])]
[1, 2, 3, 4, 5]
So like to know, if we can do the above, more efficiently.
Python functions always return a unique value. The comma operator is the constructor of tuples so self.first_name, self.last_name
evaluates to a tuple and that tuple is the actual value the function is returning.
For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:
<ul>
<li *ngFor="let item of items | slice:0:10">
{{ item }}
</li>
</ul>
Your code probably isn't using a correct machine name, you should double check that.
Your error is:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
This is the result you get when a machine is not reachable. So the firewall suggestions are reasonable, but in this case probably not correct because you say this works:
Get-WmiObject win32_SystemEnclosure -Computer hostname
So in your case it seems when this line is executed:
Get-WmiObject win32_SystemEnclosure -Computer $_
$_ doesn't contain a proper computer name. You could check type and contents of $_. Probably there is a problem with the file contents. If the file looks right, then maybe the lines are not properly terminated. Maybe take a closer look using Write-Host:
ForEach ($_ in gc u:\pub\list.txt) {
Write-Host "Get-WmiObject win32_SystemEnclosure -Computer '$_'"
Get-WmiObject win32_SystemEnclosure -Computer $_ | select serialnumber | format-table -auto @{Label="Hostname"; Expression={$_}}, @{Label="Service Tag"; Expression={$_.serialnumber}}
}
The function component return type is limited to JSXElement | null
in TypeScript. This is a current type limitation, pure React allows more return types.
You can either use a type assertion or Fragments as workaround:
const Aux = (props: AuxProps) => <>props.children</>;
const Aux2 = (props: AuxProps) => props.children as ReactElement;
ReactNode
children: React.ReactNode
might be suboptimal, if the goal is to have strong types for Aux
.
Almost anything can be assigned to current ReactNode
type, which is equivalent to {} | undefined | null
. A safer type for your case could be:
interface AuxProps {
children: ReactElement | ReactElement[]
}
Example:
Given Aux
needs React elements as children
, we accidently added a string
to it. Then above solution would error in contrast to ReactNode
- take a look at the linked playgrounds.
Typed children
are also useful for non-JSX props, like a Render Prop callback.
Not seeing it mentioned here, but also possible to use the vue-property-decorator
pattern if you are extending your Vue
class.
import { Watch, Vue } from 'vue-property-decorator';
export default class SomeClass extends Vue {
...
@Watch('item.someOtherProp')
someOtherPropChange(newVal, oldVal) {
// do something
}
...
}
The difference is ternary operator
return condition ? someData : Promise.reject(new Error('not OK'))
return condition ? someData : throw new Error('not OK')
I would use this stored procedure to generate the intervals you need into the temp table named time_intervals, then JOIN and aggregate your data table with the temp time_intervals table.
The procedure can generate intervals of all the different types you see specified in it:
call make_intervals('2009-01-01 00:00:00','2009-01-10 00:00:00',1,'DAY')
.
select * from time_intervals
.
interval_start interval_end
------------------- -------------------
2009-01-01 00:00:00 2009-01-01 23:59:59
2009-01-02 00:00:00 2009-01-02 23:59:59
2009-01-03 00:00:00 2009-01-03 23:59:59
2009-01-04 00:00:00 2009-01-04 23:59:59
2009-01-05 00:00:00 2009-01-05 23:59:59
2009-01-06 00:00:00 2009-01-06 23:59:59
2009-01-07 00:00:00 2009-01-07 23:59:59
2009-01-08 00:00:00 2009-01-08 23:59:59
2009-01-09 00:00:00 2009-01-09 23:59:59
.
call make_intervals('2009-01-01 00:00:00','2009-01-01 02:00:00',10,'MINUTE')
.
select * from time_intervals
.
interval_start interval_end
------------------- -------------------
2009-01-01 00:00:00 2009-01-01 00:09:59
2009-01-01 00:10:00 2009-01-01 00:19:59
2009-01-01 00:20:00 2009-01-01 00:29:59
2009-01-01 00:30:00 2009-01-01 00:39:59
2009-01-01 00:40:00 2009-01-01 00:49:59
2009-01-01 00:50:00 2009-01-01 00:59:59
2009-01-01 01:00:00 2009-01-01 01:09:59
2009-01-01 01:10:00 2009-01-01 01:19:59
2009-01-01 01:20:00 2009-01-01 01:29:59
2009-01-01 01:30:00 2009-01-01 01:39:59
2009-01-01 01:40:00 2009-01-01 01:49:59
2009-01-01 01:50:00 2009-01-01 01:59:59
.
I specified an interval_start and interval_end so you can aggregate the
data timestamps with a "between interval_start and interval_end" type of JOIN.
.
Code for the proc:
.
-- drop procedure make_intervals
.
CREATE PROCEDURE make_intervals(startdate timestamp, enddate timestamp, intval integer, unitval varchar(10))
BEGIN
-- *************************************************************************
-- Procedure: make_intervals()
-- Author: Ron Savage
-- Date: 02/03/2009
--
-- Description:
-- This procedure creates a temporary table named time_intervals with the
-- interval_start and interval_end fields specifed from the startdate and
-- enddate arguments, at intervals of intval (unitval) size.
-- *************************************************************************
declare thisDate timestamp;
declare nextDate timestamp;
set thisDate = startdate;
-- *************************************************************************
-- Drop / create the temp table
-- *************************************************************************
drop temporary table if exists time_intervals;
create temporary table if not exists time_intervals
(
interval_start timestamp,
interval_end timestamp
);
-- *************************************************************************
-- Loop through the startdate adding each intval interval until enddate
-- *************************************************************************
repeat
select
case unitval
when 'MICROSECOND' then timestampadd(MICROSECOND, intval, thisDate)
when 'SECOND' then timestampadd(SECOND, intval, thisDate)
when 'MINUTE' then timestampadd(MINUTE, intval, thisDate)
when 'HOUR' then timestampadd(HOUR, intval, thisDate)
when 'DAY' then timestampadd(DAY, intval, thisDate)
when 'WEEK' then timestampadd(WEEK, intval, thisDate)
when 'MONTH' then timestampadd(MONTH, intval, thisDate)
when 'QUARTER' then timestampadd(QUARTER, intval, thisDate)
when 'YEAR' then timestampadd(YEAR, intval, thisDate)
end into nextDate;
insert into time_intervals select thisDate, timestampadd(MICROSECOND, -1, nextDate);
set thisDate = nextDate;
until thisDate >= enddate
end repeat;
END;
Similar example data scenario at the bottom of this post, where I built a similar function for SQL Server.
I would recommend that you use the jQuery plugin for Verimail.js.
Why?
How?
Include verimail.jquery.js on your site and use the function:
$("input#email-address").verimail({
messageElement: "p#status-message"
});
If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:
if($("input#email-address").getVerimailStatus() < 0){
// Invalid email
}else{
// Valid email
}
In Visual Studio 2019, You can open Command/PowerShell window from Tools > Command Line >
If you want an integrated terminal, try
BuiltinCmd: https://marketplace.visualstudio.com/items?itemName=lkytal.BuiltinCmd
You can also try WhackWhackTerminal (does not support VS 2019 by this date).
https://marketplace.visualstudio.com/items?itemName=dos-cafe.WhackWhackTerminal
you can retrieve value like this
string str = (string)(range.Cells[row, col] as Excel.Range).Value2 ;
select entire used range
Excel.Range range = xlWorkSheet.UsedRange;
source :
http://csharp.net-informations.com/excel/csharp-read-excel.htm
flaming
Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html
$("#iframeID").contents().find("[tokenid=" + token + "]").html();
Place your selector in the find method.
This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.
Go to first line
:1
or Ctrl + Home
Go to last line
:%
or Ctrl + End
Go to another line (f.i. 27)
:27
[Works On VIM 7.4 (2016) and 8.0 (2018)]
NumberFormat nf = DecimalFormat.getInstance(myLocale);
DecimalFormatSymbols customSymbol = new DecimalFormatSymbols();
customSymbol.setDecimalSeparator(',');
customSymbol.setGroupingSeparator(' ');
((DecimalFormat)nf).setDecimalFormatSymbols(customSymbol);
nf.setGroupingUsed(true);
Refer following query for getting nth highest salary. By this way you get nth highest salary in MYSQL. If you want get nth lowest salary only you need to replace DESC by ASC in the query.
First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:
const http = require("http");
const path = require("path");
const fs = require("fs");
const express = require("express");
const app = express();
const httpServer = http.createServer(app);
const PORT = process.env.PORT || 3000;
httpServer.listen(PORT, () => {
console.log(`Server is listening on port ${PORT}`);
});
// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));
Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).
In Express 3.x you could use express.bodyParser
middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:
You need to define a route to handle form posts:
const multer = require("multer");
const handleError = (err, res) => {
res
.status(500)
.contentType("text/plain")
.end("Oops! Something went wrong!");
};
const upload = multer({
dest: "/path/to/temporary/directory/to/store/uploaded/files"
// you might also want to set some limits: https://github.com/expressjs/multer#limits
});
app.post(
"/upload",
upload.single("file" /* name attribute of <file> element in your form */),
(req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, "./uploads/image.png");
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, err => {
if (err) return handleError(err, res);
res
.status(200)
.contentType("text/plain")
.end("File uploaded!");
});
} else {
fs.unlink(tempPath, err => {
if (err) return handleError(err, res);
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
}
);
In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.
In order to show the uploaded image, assuming you already have an HTML page containing an img element:
<img src="/image.png" />
you can define another route in your express app and use res.sendFile
to serve the stored image:
app.get("/image.png", (req, res) => {
res.sendFile(path.join(__dirname, "./uploads/image.png"));
});
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
Take a loot at the Wikipedia article on random numbers as it talks about using sampling techniques. You can find the equation for your normal distribution by plugging into this one
(equation via Wikipedia)
As for the second issue, go into Options under the circle Office icon, go to formulas, and change calculations to "Manual". That will maintain your sheet and not recalculate the formulas each time.
If the problem allows it, try with EXISTS, since it's optimized to end as soon as a result is found (And don't buffer any response), so, if you are just trying to normalize data for a WHERE clause like this
SELECT FROM SOMETHING S WHERE S.ID IN ( SELECT DISTINCT DCR.SOMETHING_ID FROM DIFF_CARDINALITY_RELATIONSHIP DCR ) -- to keep same cardinality
A faster response would be:
SELECT FROM SOMETHING S WHERE EXISTS ( SELECT 1 FROM DIFF_CARDINALITY_RELATIONSHIP DCR WHERE DCR.SOMETHING_ID = S.ID )
This isn't always possible but when available you will see a faster response.
My answer to a similar question is accounting for ties too and it is in plain Javascript, although it doesn't use binary search so it is O(N) and not O(logN):
var searchArray= [0, 30, 60, 90];
var element= 33;
function findClosest(array,elem){
var minDelta = null;
var minIndex = null;
for (var i = 0 ; i<array.length; i++){
var delta = Math.abs(array[i]-elem);
if (minDelta == null || delta < minDelta){
minDelta = delta;
minIndex = i;
}
//if it is a tie return an array of both values
else if (delta == minDelta) {
return [array[minIndex],array[i]];
}//if it has already found the closest value
else {
return array[i-1];
}
}
return array[minIndex];
}
var closest = findClosest(searchArray,element);
Another try at cleaner solution
def grouped(itr, n=2):
itr = iter(itr)
end = object()
while True:
vals = tuple(next(itr, end) for _ in range(n))
if vals[-1] is end:
return
yield vals
Try this, it will insert the list item at index 0;
DropDownList1.Items.Insert(0, new ListItem("Add New", ""));
Testing in Swift 4 shows performance difference in simulator. I made a class with "class func" and struct with "static func" and ran them in test.
static func is:
However, running the same code on iPhone 7 under iOS 10.3 shows exactly the same performance.
Here is sample project in Swift 4 for Xcode 9 if you like to test yourself https://github.com/protyagov/StructVsClassPerformance
We can use assert
here.
def _input(inp_str:str):
try:
assert len(inp_str)<=15,print('More than 15 characters present')
assert all('a'<=i<='z' for i in inp_str),print('Characters other than "a"-"z" are found')
return inp_str
except Exception as e:
pass
_input('abcd')
#abcd
_input('abc d')
#Characters other than "a"-"z" are found
_input('abcdefghijklmnopqrst')
#More than 15 characters present
For example for all users (Builtin\Users), this method works fine - enjoy.
public static bool HasFolderWritePermission(string destDir)
{
if(string.IsNullOrEmpty(destDir) || !Directory.Exists(destDir)) return false;
try
{
DirectorySecurity security = Directory.GetAccessControl(destDir);
SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
foreach(AuthorizationRule rule in security.GetAccessRules(true, true, typeof(SecurityIdentifier)))
{
if(rule.IdentityReference == users)
{
FileSystemAccessRule rights = ((FileSystemAccessRule)rule);
if(rights.AccessControlType == AccessControlType.Allow)
{
if(rights.FileSystemRights == (rights.FileSystemRights | FileSystemRights.Modify)) return true;
}
}
}
return false;
}
catch
{
return false;
}
}
the problem is in url pattern of servlet-mapping.
<url-pattern>/DispatcherServlet</url-pattern>
let's say our controller is
@Controller
public class HomeController {
@RequestMapping("/home")
public String home(){
return "home";
}
}
when we hit some URL on our browser. the dispatcher servlet will try to map this url.
the url pattern of our serlvet currently is /Dispatcher
which means resources are served from {contextpath}/Dispatcher
but when we request http://localhost:8080/home
we are actually asking resources from /
which is not available.
so either we need to say dispatcher servlet to serve from /
by doing
<url-pattern>/</url-pattern>
our make it serve from /Dispatcher by doing /Dispatcher/*
E.g
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID"
version="3.1">
<display-name>springsecuritydemo</display-name>
<servlet>
<description></description>
<display-name>offers</display-name>
<servlet-name>offers</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>offers</servlet-name>
<url-pattern>/Dispatcher/*</url-pattern>
</servlet-mapping>
</web-app>
and request it with http://localhost:8080/Dispatcher/home
or put just /
to request like
http://localhost:8080/home
Integrated Security=true;
doesn't work in all SQL providers, it throws an exception when used with the OleDb
provider.
So basically Integrated Security=SSPI;
is preferred since works with both SQLClient
& OleDB
provider.
Here's the full set of syntaxes according to MSDN - Connection String Syntax (ADO.NET)
So, save yourself some hours that I didn't and try this if it seems not to work:
<additionalJOption>-Xdoclint:none</additionalJOption>
The tag is changed for newer versions.
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
What I use everywhere :
Runtime.getRuntime().exec("pm clear me.myapp");
Executing above piece of code closes application and removes all databases and shared preferences
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
Thanks to @donut I managed to get the never expiring access token in JavaScript.
// Initialize exchange
fetch('https://graph.facebook.com/v3.2/oauth/access_token?grant_type=fb_exchange_token&client_id={client_id}&client_secret={client_secret}&fb_exchange_token={short_lived_token}')
.then((data) => {
return data.json();
})
.then((json) => {
// Get the user data
fetch(`https://graph.facebook.com/v3.2/me?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((userData) => {
// Get the page token
fetch(`https://graph.facebook.com/v3.2/${userData.id}/accounts?access_token=${json.access_token}`)
.then((data) => {
return data.json();
})
.then((pageToken) => {
// Save the access token somewhere
// You'll need it at later point
})
.catch((err) => console.error(err))
})
.catch((err) => console.error(err))
})
.catch((err) => {
console.error(err);
})
and then I used the saved access token like this
fetch('https://graph.facebook.com/v3.2/{page_id}?fields=fan_count&access_token={token_from_the_data_array}')
.then((data) => {
return data.json();
})
.then((json) => {
// Do stuff
})
.catch((err) => console.error(err))
I hope that someone can trim this code because it's kinda messy but it was the only way I could think of.
Using powershell.
If the cmd file is long I use a first one to require elevation and then call the one doing the actual work.
If the script is a simple command everything may fit on one cmd file. Do not forget to include the path on the script files.
Template:
@echo off
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c " comands or another script.cmd go here "'"
Example 1:
@echo off
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c "powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\BIN\x.ps1"'"
Example 2:
@echo off
powershell -Command "Start-Process 'cmd' -Verb RunAs -ArgumentList '/c "c:\bin\myScript.cmd"'"
add a div to the cells that you would like to add some extra spacing:
<tr class="highlight">
<td><div>Value1</div></td>
<td><div>Value2</div></td>
</tr>
tr.highlight td div {
margin-top: 10px;
}
SLaks answer is correct, but as an addendum note that the x/html specs specify that all ids must be unique within a (single) html document. Although it's not exactly what the op asked, there could be valid instances where the same id is attached to different entities across multiple pages.
Example:
(served to modern browsers) article#main-content {styled one way}
(served to legacy) div#main-content {styled another way}
Probably an antipattern though. Just leaving here as a devil's advocate point.
What about pymysql? It's pure Python, and I've used it on Windows with considerable success, bypassing the difficulties of compiling and installing mysql-python.
I searched for these files in my harddisk
glyphicons-halflings-regular.woff
glyphicons-halflings-regular.woff2
glyphicons-halflings-regular.eot
glyphicons-halflings-regular.svg
glyphicons-halflings-regular.ttf
then copied them in font file in my .net project
What ever attribute is added to the button/anchor/link to disable it, bootstrap is just adding style to it and user will still be able to click it while there is still onclick event. So my simple solution is to check if it is disabled and remove/add onclick event:
if (!('#button').hasAttr('disabled'))
$('#button').attr('onclick', 'someFunction();');
else
$('#button').removeattr('onclick');
//div[@id='..' and @class='...]
should do the trick. That's selecting the div
operators that have both attributes of the required value.
It's worth using one of the online XPath testbeds to try stuff out.
include your Member Class to your jsp :
<%@ page import="pageNumber.*, java.util.*, java.io.*,yourMemberPackage.Member" %>
=RIGHT(A1,LEN(A1)-FIND("`*`",SUBSTITUTE(A1," ","`*`",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))
Just try to without changing anything
npm install [email protected]
X.X.X is your current version
I had similar symptoms, but my problem was that I was nesting BrowserRouter
Do not nest BrowserRouter
, because the history
object will refer to the nearest BrowserRouter
parent. So when you do a history.push(targeturl)
and that targeturl it's not in that particular BrowserRouter
it won't match any of it's route, so it will not load any sub-component.
Nest the Switch
without wrapping it with a BrowserRouter
App.js
file<BrowserRouter>
<Switch>
<Route exact path="/nestedrouter" component={NestedRouter} />
<Route exact path="/target" component={Target} />
</Switch>
</BrowserRouter>
NestedRouter.js
file<BrowserRouter>
<Switch>
<Route exact path="/nestedrouter/" component={NestedRouter} />
<Route exact path="/nestedrouter/subroute" component={SubRoute} />
</Switch>
</BrowserRouter>
BrowserRouter
from NestedRouter.js
file <Switch>
<Route exact path="/nestedrouter/" component={NestedRouter} />
<Route exact path="/nestedrouter/subroute" component={SubRoute} />
</Switch>
To ignore some folder from eslint rules we could create the file .eslintignore
in root directory and add there the path to the folder we want omit (the same way as for .gitignore
).
Here is the example from the ESLint docs on Ignoring Files and Directories:
# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default
# Ignore built files except build/index.js
build/*
!build/index.js
Sure, use the .format method. E.g.,
print('{:10s} {:3d} {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d} {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d} {:7.2f}'.format('zz', 42, 123.34))
will print
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
10s
format a string with 10 spaces, left justified by default
3d
format an integer reserving 3 spaces, right justified by default
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
Update for f-string mode. E.g.,
text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d} {other_number:7.2f}')
For right alignment
print(f'{text:>10} {number:3d} {other_number:7.2f}')
If you use the -i
option you need to provide an extension for your backups.
If you have:
File1.txt
File2.cfg
The command (note the lack of space between -i
and ''
and the -e
to make it work on new versions of Mac and on GNU):
sed -i'.original' -e 's/old_link/new_link/g' *
Create 2 backup files like:
File1.txt.original
File2.cfg.original
There is no portable way to avoid making backup files because it is impossible to find a mix of sed commands that works on all cases:
sed -i -e ...
- does not work on OS X as it creates -e
backupssed -i'' -e ...
- does not work on OS X 10.6 but works on 10.9+sed -i '' -e ...
- not working on GNUNote Given that there isn't a sed command working on all platforms, you can try to use another command to achieve the same result.
E.g., perl -i -pe's/old_link/new_link/g' *
In order to make it work you need to convert key from str to tuple before decryption(ast.literal_eval function). Here is fixed code:
import Crypto
from Crypto.PublicKey import RSA
from Crypto import Random
import ast
random_generator = Random.new().read
key = RSA.generate(1024, random_generator) #generate pub and priv key
publickey = key.publickey() # pub key export for exchange
encrypted = publickey.encrypt('encrypt this message', 32)
#message to encrypt is in the above line 'encrypt this message'
print 'encrypted message:', encrypted #ciphertext
f = open ('encryption.txt', 'w')
f.write(str(encrypted)) #write ciphertext to file
f.close()
#decrypted code below
f = open('encryption.txt', 'r')
message = f.read()
decrypted = key.decrypt(ast.literal_eval(str(encrypted)))
print 'decrypted', decrypted
f = open ('encryption.txt', 'w')
f.write(str(message))
f.write(str(decrypted))
f.close()
I am going to answer my own question.
I added the following lines of code to my Makefile and it fixed the "clock skew" problem:
clean:
find . -type f | xargs touch
rm -rf $(OBJS)
Use Ctrl + / for single line comment and
Ctrl + Alt + / for block or multiline comments.
You can find the list
of duplicate
names using the following aggregate
pipeline:
Group
all the records having similar name
.Match
those groups
having records greater than 1
.group
again to project
all the duplicate names as an array
.The Code:
db.collection.aggregate([
{$group:{"_id":"$name","name":{$first:"$name"},"count":{$sum:1}}},
{$match:{"count":{$gt:1}}},
{$project:{"name":1,"_id":0}},
{$group:{"_id":null,"duplicateNames":{$push:"$name"}}},
{$project:{"_id":0,"duplicateNames":1}}
])
o/p:
{ "duplicateNames" : [ "ksqn291", "ksqn29123213Test" ] }
In Python, creating a new object is often better than modifying an existing one:
item_list = ['item', 5, 'foo', 3.14, True]
item_list = [e for e in item_list if e not in ('item', 5)]
Which is equivalent to:
item_list = ['item', 5, 'foo', 3.14, True]
new_list = []
for e in item_list:
if e not in ('item', 5):
new_list.append(e)
item_list = new_list
In case of a big list of filtered out values (here, ('item', 5)
is a small set of elements), using a set
is faster as the in
operation is O(1) time complexity on average. It's also a good idea to build the iterable you're removing first, so that you're not creating it on every iteration of the list comprehension:
unwanted = {'item', 5}
item_list = [e for e in item_list if e not in unwanted]
A bloom filter is also a good solution if memory is not cheap.
You may also use element.insertAdjacentHTML('beforeend', data);
Please read the "Security considerations" on MDN.
Depending on your definition of shortly, you could use one of the following options:
try: int(your_input); except ValueError: # ...
your_input.isdigit()
parse
which is kind of the opposite of format
You can use document.evaluate
:
Evaluates an XPath expression string and returns a result of the specified type if possible.
It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
function getElementByXpath(path) {_x000D_
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;_x000D_
}_x000D_
_x000D_
console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo</div>
_x000D_
https://gist.github.com/yckart/6351935
There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
Alternative version, using XPathEvaluator
:
function getElementByXPath(xpath) {_x000D_
return new XPathEvaluator()_x000D_
.createExpression(xpath)_x000D_
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)_x000D_
.singleNodeValue_x000D_
}_x000D_
_x000D_
console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo/bar</div>
_x000D_
Bash's set
will parse all output into position parameters.
For instance, with set $(free -h)
command, echo $7
will show "Mem:"
Google Translate Kit, an open source library http://ggltranslate.codeplex.com/
Translator gt = new Translator();
/*using cache*/
DemoWriter dw = new DemoWriter();
gt.KeyGen = new SimpleKeyGen();
gt.CacheManager = new SimleCacheManager();
gt.Writer = dw;
Translator.TranslatedPost post = gt.GetTranslatedPost("Hello world", LanguageConst.ENGLISH, LanguageConst.CHINESE);
Translator.TranslatedPost post2 = gt.GetTranslatedPost("I'm Jeff", LanguageConst.ENGLISH, LanguageConst.CHINESE);
this.result.InnerHtml = "<p>" + post.text +post2.text+ "</p>";
dw.WriteToFile();
For a SOAP 1.2 Webservice, I normally use
curl --header "content-type: application/soap+xml" --data @filetopost.xml http://domain/path
You can order by a selected column or other expressions.
Here an example, how to order by the result of a case-statement:
SELECT col1
, col2
FROM tbl_Bill
WHERE col1 = 0
ORDER BY -- order by case-statement
CASE WHEN tbl_Bill.IsGen = 0 THEN 0
WHEN tbl_Bill.IsGen = 1 THEN 1
ELSE 2 END
The result will be a List starting with "IsGen = 0" rows, followed by "IsGen = 1" rows and all other rows a the end.
You could add more order-parameters at the end:
SELECT col1
, col2
FROM tbl_Bill
WHERE col1 = 0
ORDER BY -- order by case-statement
CASE WHEN tbl_Bill.IsGen = 0 THEN 0
WHEN tbl_Bill.IsGen = 1 THEN 1
ELSE 2 END,
col1,
col2
At some point I too tried to do this, but the Android Studio doesn’t work quite like Eclipse does.
It's simpler: if you create a project at, say /home/USER/Projects/AndroidStudio/MyApplication
from there on all new projects will default to /home/USER/Projects/AndroidStudio
.
You can also edit ~/.AndroidStudioPreview/config/options/ide.general.xml
(in linux) and change the line that reads <option name="lastProjectLocation" value="$USER_HOME$/AndroidStudioProjects" />
to <option name="lastProjectLocation" value="$USER_HOME$/Projects/AndroidStudio" />
, but be aware that as soon as you create a project anywhere else this will change to that place and all new projects will default to it.
Hope this helps, but the truth is there really isn't much more to it other than what I explained here.
Let me know if you need anything else.
The above error can occur for multiple cases during servlet startup / request. Hope you check the full stack trace of the server log, If you have tomcat, you can also see the exact causes in html preview of the 500 Internal Server Error page.
Weird thing is, if you try to hit the request url a second time, you would get 404 Not Found page.
You can also debug this issue, by placing breakpoints on all the classes constructor initialization block, whose objects are created during servlet startup/request.
In my case, I didn't had javaassist jar loaded for the Weld CDI injection to work. And it shown NoClassDefFound Error.
For those looking to use axios-mock-adapter in place of the mockfetch example in the Redux documentation for async testing, I successfully used the following:
describe('SignInUser', () => {
var history = {
push: function(str) {
expect(str).toEqual('/feed');
}
}
it('Dispatches authorization', () => {
let mock = new MockAdapter(axios);
mock.onPost(`${ROOT_URL}/auth/signin`, {
email: '[email protected]',
password: 'test'
}).reply(200, {token: 'testToken' });
const expectedActions = [ { type: types.AUTH_USER } ];
const store = mockStore({ auth: [] });
return store.dispatch(actions.signInUser({
email: '[email protected]',
password: 'test',
}, history)).then(() => {
expect(store.getActions()).toEqual(expectedActions);
});
});
In order to test a successful case for signInUser
in file actions/index.js:
export const signInUser = ({ email, password }, history) => async dispatch => {
const res = await axios.post(`${ROOT_URL}/auth/signin`, { email, password })
.catch(({ response: { data } }) => {
...
});
if (res) {
dispatch({ type: AUTH_USER }); // Test verified this
localStorage.setItem('token', res.data.token); // Test mocked this
history.push('/feed'); // Test mocked this
}
}
Given that this is being done with jest, the localstorage call had to be mocked. This was in file src/setupTests.js:
const localStorageMock = {
removeItem: jest.fn(),
getItem: jest.fn(),
setItem: jest.fn(),
clear: jest.fn()
};
global.localStorage = localStorageMock;
One option is to put the character literally in your script, e.g.:
const omega = 'O';
This requires that you let the browser know the correct source encoding, see Unicode in JavaScript
However, if you can't or don't want to do this (e.g. because the character is too exotic and can't be expected to be available in the code editor font), the safest option may be to use new-style string escape or String.fromCodePoint
:
const omega = '\u{3a9}';
// or:
const omega = String.fromCodePoint(0x3a9);
This is not restricted to UTF-16 but works for all unicode code points. In comparison, the other approaches mentioned here have the following downsides:
const omega = 'Ω';
): only work when rendered unescaped in an HTML elementconst omega = '\u03A9';
): restricted to UTF-16String.fromCharCode
: restricted to UTF-16Try this:
a[id*='Some:Same'][id$='name']
This will get you all a
elements with id containing
Some:Same
and have the id ending in
name
I found that using the tornado
package to be the fastest and simplest way to achieve this:
from tornado import ioloop, httpclient, gen
def main(urls):
"""
Asynchronously download the HTML contents of a list of URLs.
:param urls: A list of URLs to download.
:return: List of response objects, one for each URL.
"""
@gen.coroutine
def fetch_and_handle():
httpclient.AsyncHTTPClient.configure(None, defaults=dict(user_agent='MyUserAgent'))
http_client = httpclient.AsyncHTTPClient()
waiter = gen.WaitIterator(*[http_client.fetch(url, raise_error=False, method='HEAD')
for url in urls])
results = []
# Wait for the jobs to complete
while not waiter.done():
try:
response = yield waiter.next()
except httpclient.HTTPError as e:
print(f'Non-200 HTTP response returned: {e}')
continue
except Exception as e:
print(f'An unexpected error occurred querying: {e}')
continue
else:
print(f'URL \'{response.request.url}\' has status code <{response.code}>')
results.append(response)
return results
loop = ioloop.IOLoop.current()
web_pages = loop.run_sync(fetch_and_handle)
return web_pages
my_urls = ['url1.com', 'url2.com', 'url100000.com']
responses = main(my_urls)
print(responses[0])
Since the .Rows result is marked as consisting of rows, you can "For Each" it to deal with each row individually, like this:
Function Attendance(rng As Range) As Long
Attendance = 0
For Each rRow In rng.Rows
If WorksheetFunction.Sum(rRow) > 0 Then
Attendance = Attendance + 1
End If
Next
End Function
I use this to check attendance in any of a few categories (different columns) for a list of people (different rows).
(And of course you could use .Columns to do a "For Each" over the columns in the range.)
The OnChange
event is a good choice. But if a user select the same image, the event will not be triggered because the current value is the same as the previous.
The image is the same with a width changed, for example, and it should be uploaded to the server.
To prevent this problem you could to use the following code:
$(document).ready(function(){
$("input[type=file]").click(function(){
$(this).val("");
});
$("input[type=file]").change(function(){
alert($(this).val());
});
});
Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.
My setup was as follows:
I put the following formula in cell A1 of Sheet3:
=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)
Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.
Notes:
In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.
A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.
After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)
and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.
Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.
Cells A2, A3, etc. will get these formulas:
=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)
Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.
I tend to follow the pseudo-conventions established by Java Core/Sun, e.g. in the Collections classes:
List
- interface for the "conceptual" objectArrayList
- concrete implementation of interfaceLinkedList
- concrete implementation of interfaceAbstractList
- abstract "partial" implementation to assist custom implementationsI used to do the same thing modeling my event classes after the AWT Event/Listener/Adapter paradigm.
I have an example about this.
<!DOCTYPE html>
<html ng-app="app">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid body-content" ng-controller="formView">
<div class="row">
<div class="col-md-12">
<h4>Register Form</h4>
<form class="form-horizontal" ng-submit="" name="f" novalidate>
<div ng-repeat="item in elements" class="form-group">
<label>{{item.Label}}</label>
<element type="{{item.Type}}" model="item"></element>
</div>
<input ng-show="f.$valid" type="submit" id="submit" value="Submit" class="" />
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.min.js"></script>
<script src="app.js"></script>
</body>
</html>
angular.module('app', [])
.controller('formView', function ($scope) {
$scope.elements = [{
"Id":1,
"Type":"textbox",
"FormId":24,
"Label":"Name",
"PlaceHolder":"Place Holder Text",
"Max":20,
"Required":false,
"Options":null,
"SelectedOption":null
},
{
"Id":2,
"Type":"textarea",
"FormId":24,
"Label":"AD2",
"PlaceHolder":"Place Holder Text",
"Max":20,
"Required":true,
"Options":null,
"SelectedOption":null
}];
})
.directive('element', function () {
return {
restrict: 'E',
link: function (scope, element, attrs) {
scope.contentUrl = attrs.type + '.html';
attrs.$observe("ver", function (v) {
scope.contentUrl = v + '.html';
});
},
template: '<div ng-include="contentUrl"></div>'
}
})
The accepted answer changes shape for 2d arrays.
I present a solution here, using the Pandas dropna() functionality.
It works for 1D and 2D arrays. In the 2D case you can choose weather to drop the row or column containing np.nan
.
import pandas as pd
import numpy as np
def dropna(arr, *args, **kwarg):
assert isinstance(arr, np.ndarray)
dropped=pd.DataFrame(arr).dropna(*args, **kwarg).values
if arr.ndim==1:
dropped=dropped.flatten()
return dropped
x = np.array([1400, 1500, 1600, np.nan, np.nan, np.nan ,1700])
y = np.array([[1400, 1500, 1600], [np.nan, 0, np.nan] ,[1700,1800,np.nan]] )
print('='*20+' 1D Case: ' +'='*20+'\nInput:\n',x,sep='')
print('\ndropna:\n',dropna(x),sep='')
print('\n\n'+'='*20+' 2D Case: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna (rows):\n',dropna(y),sep='')
print('\ndropna (columns):\n',dropna(y,axis=1),sep='')
print('\n\n'+'='*20+' x[np.logical_not(np.isnan(x))] for 2D: ' +'='*20+'\nInput:\n',y,sep='')
print('\ndropna:\n',x[np.logical_not(np.isnan(x))],sep='')
Result:
==================== 1D Case: ====================
Input:
[1400. 1500. 1600. nan nan nan 1700.]
dropna:
[1400. 1500. 1600. 1700.]
==================== 2D Case: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna (rows):
[[1400. 1500. 1600.]]
dropna (columns):
[[1500.]
[ 0.]
[1800.]]
==================== x[np.logical_not(np.isnan(x))] for 2D: ====================
Input:
[[1400. 1500. 1600.]
[ nan 0. nan]
[1700. 1800. nan]]
dropna:
[1400. 1500. 1600. 1700.]
BLOB stores binary data which are more than 2 GB. Max size for BLOB is 4 GB. Binary data means unstructured data i.e images audio files vedio files digital signature
Text is used to store large string.
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
You can create an element with an id and then assign that length value to that element.
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
document.getElementById('message').innerHTML = lengthOfName;
_x000D_
<p id='message'></p>
_x000D_
from my experience;
if it doesn't work from within php
do this in .htaccess
it worked for me
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin http://www.vknyvz.com
Header set Access-Control-Allow-Credentials true
</IfModule>
I have the current latest version of MySQL: 8.0.20
So my table name is visit, my column name is curdate.
alter table visit modify curdate date not null default (current_date);
This writes the default date value with no timestamp.
use array_rand()
see php manual -> http://php.net/manual/en/function.array-rand.php
Here is the jQuery function I use:
function isExists(var elemId){
return jQuery('#'+elemId).length > 0;
}
This will return a boolean value. If element exists, it returns true.
If you want to select element by class name, just replace #
with .
InputMaps and ActionMaps were designed to capture the key events for the component, it and all of its sub-components, or the entire window. This is controlled through the parameter in JComponent.getInputMap(). See How to Use Key Bindings for documentation.
The beauty of this design is that one can pick and choose which key strokes are important to monitor and have different actions fired based on those key strokes.
This code will call dispose() on a JFrame when the escape key is hit anywhere in the window. JFrame doesn't derive from JComponent so you have to use another component in the JFrame to create the key binding. The content pane might be such a component.
InputMap inputMap;
ActionMap actionMap;
AbstractAction action;
JComponent component;
inputMap = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
actionMap = component.getActionMap();
action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
dispose();
}
};
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "dispose");
actionMap.put("dispose", action);
I solved this problem for myself using grunt. I have the grunt script below. What the script does is takes the command line parameter of the specific test to run and creates a copy of test.ts and puts this specific test name in there.
To run this, first install grunt-cli using:
npm install -g grunt-cli
Put the below grunt dependencies in your package.json:
"grunt": "^1.0.1",
"grunt-contrib-clean": "^1.0.0",
"grunt-contrib-copy": "^1.0.0",
"grunt-exec": "^2.0.0",
"grunt-string-replace": "^1.3.1"
To run it save the below grunt file as Gruntfile.js in your root folder. Then from command line run it as:
grunt --target=app.component
This will run app.component.spec.ts.
Grunt file is as below:
/*
This gruntfile is used to run a specific test in watch mode. Example: To run app.component.spec.ts , the Command is:
grunt --target=app.component
Do not specific .spec.ts. If no target is specified it will run all tests.
*/
module.exports = function(grunt) {
var target = grunt.option('target') || '';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
clean: ['temp.conf.js','src/temp-test.ts'],
copy: {
main: {
files: [
{expand: false, cwd: '.', src: ['karma.conf.js'], dest: 'temp.conf.js'},
{expand: false, cwd: '.', src: ['src/test.ts'], dest: 'src/temp-test.ts'}
],
}
},
'string-replace': {
dist: {
files: {
'temp.conf.js': 'temp.conf.js',
'src/temp-test.ts': 'src/temp-test.ts'
},
options: {
replacements: [{
pattern: /test.ts/ig,
replacement: 'temp-test.ts'
},
{
pattern: /const context =.*/ig,
replacement: 'const context = require.context(\'./\', true, /'+target+'\\\.spec\\\.ts$/);'
}]
}
}
},
'exec': {
sleep: {
//The sleep command is needed here, else webpack compile fails since it seems like the files in the previous step were touched too recently
command: 'ping 127.0.0.1 -n 4 > nul',
stdout: true,
stderr: true
},
ng_test: {
command: 'ng test --config=temp.conf.js',
stdout: true,
stderr: true
}
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-string-replace');
grunt.loadNpmTasks('grunt-exec');
// Default task(s).
grunt.registerTask('default', ['clean','copy','string-replace','exec']);
};
Try the following (Which does not print -1 at the end now!)
int index = word.indexOf(guess);
while(index >= 0) {
System.out.println(index);
index = word.indexOf(guess, index+1);
}
You can also wrap your text in label fields, so your form will be more self-explainable semantically.
Just remember to float labels and inputs to the left and to add a specific width to them, and the containing form. Then you can add margins to both of them, to adjust the spacing between the lines (you understand, of course, that this is a pretty minimal markup that expects content to be as big as to some limit).
That way you wont have to add any more elements, just the label-input pairs, all of them wrapped in a form element.
For example:
<form>
<label for="txtName">Name</label>
<input id"txtName" type="text">
<label for="txtEmail">Email</label>
<input id"txtEmail" type="text">
<label for="txtAddress">Address</label>
<input id"txtAddress" type="text">
...
<input type="submit" value="Submit The Form">
</form>
And the css will be:
form{
float:left; /*to clear the floats of inner elements,usefull if you wanna add a border or background image*/
width:300px;
}
label{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
input{
float:left;
width:150px;
margin-bottom:10px; /*or whatever you want the spacing to be*/
}
you can use cssSelector,
driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));
You can also used below code
<html>
<head>
<style>
.labelClass{
float: left;
width: 113px;
}
</style>
</head>
<body>
<form action="yourclassName.jsp">
<span class="labelClass">First name: </span><input type="text" name="fname"><br>
<span class="labelClass">Last name: </span><input type="text" name="lname"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
In addition to romkyns's great answer.. here is some relevant documentation/examples.
DOM Elements have a native .click()
method.
The
HTMLElement.click()
method simulates a mouse click on an element.When click is used, it also fires the element's click event which will bubble up to elements higher up the document tree (or event chain) and fire their click events too. However, bubbling of a click event will not cause an
<a>
element to initiate navigation as if a real mouse-click had been received. (mdn reference)
Relevant W3 documentation.
A few examples..
You can access a specific DOM element from a jQuery object: (example)
$('a')[0].click();
You can use the .get()
method to retrieve a DOM element from a jQuery object: (example)
$('a').get(0).click();
As expected, you can select the DOM element and call the .click()
method. (example)
document.querySelector('a').click();
It's worth pointing out that jQuery is not required to trigger a native .click()
event.
I don't see any answer documenting how to work around this problem with cooperating processes. A common pattern with things like ssh-agent
is to have the child process print an expression which the parent can eval
.
bash$ eval $(shh-agent)
For example, ssh-agent
has options to select Csh or Bourne-compatible output syntax.
bash$ ssh-agent
SSH2_AUTH_SOCK=/tmp/ssh-era/ssh2-10690-agent; export SSH2_AUTH_SOCK;
SSH2_AGENT_PID=10691; export SSH2_AGENT_PID;
echo Agent pid 10691;
(This causes the agent to start running, but doesn't allow you to actually use it, unless you now copy-paste this output to your shell prompt.) Compare:
bash$ ssh-agent -c
setenv SSH2_AUTH_SOCK /tmp/ssh-era/ssh2-10751-agent;
setenv SSH2_AGENT_PID 10752;
echo Agent pid 10752;
(As you can see, csh
and tcsh
uses setenv
to set varibles.)
Your own program can do this, too.
bash$ foo=$(makefoo)
Your makefoo
script would simply calculate and print the value, and let the caller do whatever they want with it -- assigning it to a variable is a common use case, but probably not something you want to hard-code into the tool which produces the value.
I’ve been using ng cli lately, and it was really tough to find a good way to structure my code.
The most efficient one I've seen so far comes from mrholek repository (https://github.com/mrholek/CoreUI-Angular).
This folder structure allows you to keep your root project clean and structure your components, it avoids redundant (sometimes useless) naming convention of the official Style Guide.
Also it’s, this structure is useful to group import when it’s needed and avoid having 30 lines of import for a single file.
src
|
|___ app
|
| |___ components/shared
| | |___ header
| |
| |___ containers/layout
| | |___ layout1
| |
| |___ directives
| | |___ sidebar
| |
| |___ services
| | |___ *user.service.ts*
| |
| |___ guards
| | |___ *auth.guard.ts*
| |
| |___ views
| | |___ about
| |
| |___ *app.component.ts*
| |
| |___ *app.module.ts*
| |
| |___ *app.routing.ts*
|
|___ assets
|
|___ environments
|
|___ img
|
|___ scss
|
|___ *index.html*
|
|___ *main.ts*
I was having this problem on Ubuntu 12.04.3 LTS (well beyond EOL, I know...) and got around it with:
sudo apt-get update && sudo apt-get install ca-certificates
import java.util.ArrayList;
import java.util.List;
public class Node<T> {
private List<Node<T>> children = new ArrayList<Node<T>>();
private Node<T> parent = null;
private T data = null;
public Node(T data) {
this.data = data;
}
public Node(T data, Node<T> parent) {
this.data = data;
this.parent = parent;
}
public List<Node<T>> getChildren() {
return children;
}
public void setParent(Node<T> parent) {
parent.addChild(this);
this.parent = parent;
}
public void addChild(T data) {
Node<T> child = new Node<T>(data);
child.setParent(this);
this.children.add(child);
}
public void addChild(Node<T> child) {
child.setParent(this);
this.children.add(child);
}
public T getData() {
return this.data;
}
public void setData(T data) {
this.data = data;
}
public boolean isRoot() {
return (this.parent == null);
}
public boolean isLeaf() {
return this.children.size == 0;
}
public void removeParent() {
this.parent = null;
}
}
Example:
import java.util.List;
Node<String> parentNode = new Node<String>("Parent");
Node<String> childNode1 = new Node<String>("Child 1", parentNode);
Node<String> childNode2 = new Node<String>("Child 2");
childNode2.setParent(parentNode);
Node<String> grandchildNode = new Node<String>("Grandchild of parentNode. Child of childNode1", childNode1);
List<Node<String>> childrenNodes = parentNode.getChildren();
My answer is very similar to Ricardo's answer, but I feel that my approach is a little more straightforward simply because there is so much going on in his using
function that I'm not even sure how exactly it works on a lower level.
So for those who want a simple and clean solution that creates a database for you where you know exactly what is happening under the hood, this is for you:
public Startup(IHostingEnvironment env)
{
using (var client = new TargetsContext())
{
client.Database.EnsureCreated();
}
}
This pretty much means that within the DbContext
that you created (in this case, mine is called TargetsContext
), you can use an instance of the DbContext
to ensure that the tables defined with in the class are created when Startup.cs is run in your application.
Since Java 11 you may use that:
public FileReader(String fileName, Charset charset) throws IOException;
llist module implements linked list data structures. It supports a doubly linked list, i.e. dllist
and a singly linked data structure sllist
.
This object represents a doubly linked list data structure.
first
First dllistnode
object in the list. None
if list is empty.
last
Last dllistnode
object in the list. None if list is empty.
dllist objects also support the following methods:
append(x)
Add x
to the right side of the list and return inserted dllistnode
.
appendleft(x)
Add x
to the left side of the list and return inserted dllistnode
.
appendright(x)
Add x
to the right side of the list and return inserted dllistnode
.
clear()
Remove all nodes from the list.
extend(iterable)
Append elements from iterable
to the right side of the list.
extendleft(iterable)
Append elements from iterable
to the left side of the list.
extendright(iterable)
Append elements from iterable
to the right side of the list.
insert(x[, before])
Add x
to the right side of the list if before
is not specified, or insert x
to the left side of dllistnode before
. Return inserted dllistnode
.
nodeat(index)
Return node (of type dllistnode
) at index
.
pop()
Remove and return an element’s value from the right side of the list.
popleft()
Remove and return an element’s value from the left side of the list.
popright()
Remove and return an element’s value from the right side of the list
remove(node)
Remove node
from the list and return the element which was stored in it.
dllistnode
objectsllist.dllistnode([value])
Return a new doubly linked list node, initialized (optionally) with value
.
dllistnode
objects provide the following attributes:next
Next node in the list. This attribute is read-only.
prev
Previous node in the list. This attribute is read-only.
value
Value stored in this node. Compiled from this reference
class llist.sllist([iterable])
Return a new singly linked list initialized with elements from iterable
. If iterable is not specified, the new sllist
is empty.
A similar set of attributes and operations are defined for this sllist
object. See this reference for more information.
Super Thanks to user somedrew for their post here: https://bbs.archlinux.org/viewtopic.php?id=55485 on 2008-09-20 02:09:48
Looking in /sys/class/net should be one way
Here's my script to test for a network connection other than the loop back. I use the below in another script that I have for periodically testing if my website is accessible. If it's NOT accessible a popup window alerts me to a problem.
The script below prevents me from receiving popup messages every five minutes whenever my laptop is not connected to the network.
#!/usr/bin/bash
# Test for network conection
for interface in $(ls /sys/class/net/ | grep -v lo);
do
if [[ $(cat /sys/class/net/$interface/carrier) = 1 ]]; then OnLine=1; fi
done
if ! [ $OnLine ]; then echo "Not Online" > /dev/stderr; exit; fi
Note for those new to bash: The final 'if' statement tests if NOT [!] online and exits if this is the case. See man bash and search for "Expressions may be combined" for more details.
P.S. I feel ping is not the best thing to use here because it aims to test a connection to a particular host NOT test if there is a connection to a network of any sort.
P.P.S. The Above works on Ubuntu 12.04 The /sys may not exist on some other distros. See below:
Modern Linux distributions include a /sys directory as a virtual filesystem (sysfs, comparable to /proc, which is a procfs), which stores and allows modification of the devices connected to the system, whereas many traditional UNIX and Unix-like operating systems use /sys as a symbolic link to the kernel source tree.[citation needed]
From Wikipedia https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard
You need to initialize it first:
p = Pump().getPumps()
Use the xattr
command. You can inspect the extended attributes:
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
com.apple.quarantine
and use the -d
option to delete one extended attribute:
$ xattr -d com.apple.quarantine s.7z
$ xattr s.7z
com.apple.metadata:kMDItemWhereFroms
you can also use the -c
option to remove all extended attributes:
$ xattr -c s.7z
$ xattr s.7z
xattr -h
will show you the command line options, and xattr has a man page.
On my Mac:
/System/Library/Frameworks/JavaVM.framework/Home/
btw, did you tried which java
?
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
This can also be done as follows for a list of dataframes df_list
:
df = df_list[0]
for df_ in df_list[1:]:
df = df.merge(df_, on='join_col_name')
or if the dataframes are in a generator object (e.g. to reduce memory consumption):
df = next(df_list)
for df_ in df_list:
df = df.merge(df_, on='join_col_name')
I believe you are looking for:
Just pass it the localhost IP.
There is also a gethostbyname function, that is also usefull.
I had the same problem and I think I have the solution.
If your field Application
in table Library
has a foreign key that references a field in another table (named Application
I would bet), then your field Application
in table Library
has to have a foreign key to table Application
too.
After that you can do your composed foreign key.
Excuse my poor english, and sorry if I'm wrong.
If you invoke addRecipient
multiple times it will add the given recipient to the list of recipients of the given time (TO, CC, BCC)
For example:
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
message.addRecipient(Message.RecipientType.CC, InternetAddress.parse("[email protected]"));
Will add the 3 addresses to CC
If you wish to add all addresses at once you should use setRecipients
or addRecipients
and provide it with an array of addresses
Address[] cc = new Address[] {InternetAddress.parse("[email protected]"),
InternetAddress.parse("[email protected]"),
InternetAddress.parse("[email protected]")};
message.addRecipients(Message.RecipientType.CC, cc);
You can also use InternetAddress.parse
to parse a list of addresses
message.addRecipients(Message.RecipientType.CC,
InternetAddress.parse("[email protected],[email protected],[email protected]"));
In some applications TCP is faster (better throughput) than UDP.
This is the case when doing lots of small writes relative to the MTU size. For example, I read an experiment in which a stream of 300 byte packets was being sent over Ethernet (1500 byte MTU) and TCP was 50% faster than UDP.
The reason is because TCP will try and buffer the data and fill a full network segment thus making more efficient use of the available bandwidth.
UDP on the other hand puts the packet on the wire immediately thus congesting the network with lots of small packets.
You probably shouldn't use UDP unless you have a very specific reason for doing so. Especially since you can give TCP the same sort of latency as UDP by disabling the Nagle algorithm (for example if you're transmitting real-time sensor data and you're not worried about congesting the network with lot's of small packets).
You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.
If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-
First copy the table
CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;
Then drop columns that you want to be after the column you will insert
ALTER TABLE my_tab DROP COLUMN three;
Now add the new column (two in this example) and the ones you removed.
ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));
Lastly add back the data for the re-created columns
UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);
Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?
I had a similar issue , The function name i was using matched one of the inbuilt functions declared in one of the header files that i included in the program.Reading through the compiler error message will tell you the exact header file and function name.Changing the function name solved this issue for me
Check out WaveMaker for building a quick, simple webapp. They have a browser based drag-and-drop designer for Dojo/JavaScript widgets, and the backend is 100% Java.