Stream audio in realtime without waiting for recording to end: https://github.com/noamtcohen/AudioStreamer
This streams PCM data but you could modify the code to stream mp3 or Speex
Thanks to cryo for improved version that I based my tested code below:
#Instead of adding silence at start and end of recording (values=0) I add the original audio . This makes audio sound more natural as volume is >0. See trim()
#I also fixed issue with the previous code - accumulated silence counter needs to be cleared once recording is resumed.
from array import array
from struct import pack
from sys import byteorder
import copy
import pyaudio
import wave
THRESHOLD = 500 # audio levels not normalised.
CHUNK_SIZE = 1024
SILENT_CHUNKS = 3 * 44100 / 1024 # about 3sec
FORMAT = pyaudio.paInt16
FRAME_MAX_VALUE = 2 ** 15 - 1
NORMALIZE_MINUS_ONE_dB = 10 ** (-1.0 / 20)
RATE = 44100
CHANNELS = 1
TRIM_APPEND = RATE / 4
def is_silent(data_chunk):
"""Returns 'True' if below the 'silent' threshold"""
return max(data_chunk) < THRESHOLD
def normalize(data_all):
"""Amplify the volume out to max -1dB"""
# MAXIMUM = 16384
normalize_factor = (float(NORMALIZE_MINUS_ONE_dB * FRAME_MAX_VALUE)
/ max(abs(i) for i in data_all))
r = array('h')
for i in data_all:
r.append(int(i * normalize_factor))
return r
def trim(data_all):
_from = 0
_to = len(data_all) - 1
for i, b in enumerate(data_all):
if abs(b) > THRESHOLD:
_from = max(0, i - TRIM_APPEND)
break
for i, b in enumerate(reversed(data_all)):
if abs(b) > THRESHOLD:
_to = min(len(data_all) - 1, len(data_all) - 1 - i + TRIM_APPEND)
break
return copy.deepcopy(data_all[_from:(_to + 1)])
def record():
"""Record a word or words from the microphone and
return the data as an array of signed shorts."""
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, output=True, frames_per_buffer=CHUNK_SIZE)
silent_chunks = 0
audio_started = False
data_all = array('h')
while True:
# little endian, signed short
data_chunk = array('h', stream.read(CHUNK_SIZE))
if byteorder == 'big':
data_chunk.byteswap()
data_all.extend(data_chunk)
silent = is_silent(data_chunk)
if audio_started:
if silent:
silent_chunks += 1
if silent_chunks > SILENT_CHUNKS:
break
else:
silent_chunks = 0
elif not silent:
audio_started = True
sample_width = p.get_sample_size(FORMAT)
stream.stop_stream()
stream.close()
p.terminate()
data_all = trim(data_all) # we trim before normalize as threshhold applies to un-normalized wave (as well as is_silent() function)
data_all = normalize(data_all)
return sample_width, data_all
def record_to_file(path):
"Records from the microphone and outputs the resulting data to 'path'"
sample_width, data = record()
data = pack('<' + ('h' * len(data)), *data)
wave_file = wave.open(path, 'wb')
wave_file.setnchannels(CHANNELS)
wave_file.setsampwidth(sample_width)
wave_file.setframerate(RATE)
wave_file.writeframes(data)
wave_file.close()
if __name__ == '__main__':
print("Wait in silence to begin recording; wait in silence to terminate")
record_to_file('demo.wav')
print("done - result written to demo.wav")
It's python source parser failure on sum.up=False
named argument as sum.up is not valid argument name (you can't use dots -- only alphanumerics and underscores in argument names).
Editing the web.config
file or updating a DLL in the bin
folder just recycles the worker process for that application, not the whole pool.
Here's the strsplit
solution if s
is a vector:
> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"
You can use
Source.fromFile(fileName).getLines().mkString
however it should be noticed that getLines() removes all new line characters. If you want save formatting you should use
Source.fromFile(fileName).iter.mkString
In spark/scala, it's pretty easy to filter with varargs.
val d = spark.read...//data contains column named matid
val ids = Seq("BNBEL0608AH", "BNBEL00608H")
val filtered = d.filter($"matid".isin(ids:_*))
Simple solution:
min-height: 100%;
min-width: 100%;
width: auto;
height: auto;
margin: 0;
padding: 0;
By the way, if you want to center it in a parent div container, you can add those css properties:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
It should really work as expected :)
Just use:
if file_name.endswith(tuple(extensions)):
In Python 3.6 you can use so called f-strings. In my opinion this method is much clearer to read.
>>> f'{a:02d}'
'05'
In order to perform chmod, you need to be owner of the file you are trying to modify, or the root user.
for /f "delims=" %a in (downing.txt) do echo %a & pause>nul
Prints 1st line, then waits for user to press a key to print next line. After printing required lines, press Ctrl+C to stop.
@Ross Presser: This method prints lines only, not prepend line numbers.
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
On Error Resume Next
DoStep1
If Err.Number <> 0 Then
WScript.Echo "Error in DoStep1: " & Err.Description
Err.Clear
End If
DoStep2
If Err.Number <> 0 Then
WScript.Echo "Error in DoStop2:" & Err.Description
Err.Clear
End If
'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
Within Excel you need to set a reference to the VB script run-time library.
The relevant file is usually located at \Windows\System32\scrrun.dll
Microsoft Scripting Runtime
'scrrun.dll
file will be displayed below the listboxThis can also be done directly in the code if access to the VBA object model has been enabled.
Access can be enabled by ticking the check-box Trust access to the VBA project object model
found at File > Options > Trust Center > Trust Center Settings > Macro Settings
To add a reference:
Sub Add_Reference()
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference
End Sub
To remove a reference:
Sub Remove_Reference()
Dim oReference As Object
Set oReference = Application.VBE.ActiveVBProject.References.Item("Scripting")
Application.VBE.ActiveVBProject.References.Remove oReference
'Remove a reference
End Sub
I know I'm late to the party, but I needed something similar that the above answers didn't help.
I was using Angular's $watch function to detect changes in a variable. Not only did I need to know whether a property had changed on the variable, but I also wanted to make sure that the property that changed was not a temporary, calculated field. In other words, I wanted to ignore certain properties.
Here's the code: https://jsfiddle.net/rv01x6jo/
Here's how to use it:
// To only return the difference
var difference = diff(newValue, oldValue);
// To exclude certain properties
var difference = diff(newValue, oldValue, [newValue.prop1, newValue.prop2, newValue.prop3]);
Hope this helps someone.
I'm running on a Dell XPS 15. Rather than stuffing around with resolutions and magnifications and all that, I just did the following:
Everything seems to work fine and the display looks good (if a bit blurry/pixelly). The only difference i can see is that the title bar is in Windows XP style (oh no!!!).
I'm curious to know if this works for others and if anyone comes across any problems.
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
git log --oneline | grep PATTERN
Given that your date format follows : "YYYY-MM-DD HH:MM:SS", if you need to find the difference between two dates in number of months :
(strftime('%m', date1) + 12*strftime('%Y', date1)) -
(strftime('%m', date2) + 12*strftime('%Y', date2))
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
This should work, I tried it by myself and it worked for me. If you pass True instead of false, the print dialog will appear.
this.print(false);
The abstract methods are implicitly virtual. Abstract methods require an instance, but static methods do not have an instance. So, you can have a static method in an abstract class, it just cannot be static abstract (or abstract static).
You can also use a shorter way:
<?php header('Content-Type: charset=utf-8'); ?>
See RFC 2616. It's valid to specify only character set.
I tried all answers. None of them worked for me.
What worked for me on Sierra + Xcode 8.2 was going to:
/Library/Developer/CoreSimulator/Devices
and deleting all devices.
(Maybe this won't work for you, maybe this is a solution as a standalone, or maybe you have to do this in addition to other answers, but I did all solutions here and so not sure what did the deed). Just be aware that some of the answers here are old and the location of simulator has changed. Snowcrash's answer seems to be most recent.
Here is a little function to recursivlely create directories:
const createDir = (dir) => {
// This will create a dir given a path such as './folder/subfolder'
const splitPath = dir.split('/');
splitPath.reduce((path, subPath) => {
let currentPath;
if(subPath != '.'){
currentPath = path + '/' + subPath;
if (!fs.existsSync(currentPath)){
fs.mkdirSync(currentPath);
}
}
else{
currentPath = subPath;
}
return currentPath
}, '')
}
Thanks to Renato answer, I have created a really basic example:
const exec = require('child_process').exec
exec('git config --global user.name', (err, stdout, stderr) => console.log(stdout))
It will just print your global git username :)
The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.
To put it simply each one of these providers is a specialized version of the other, in this order: provider
> factory
> value
/ constant
/ service
.
So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.
This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.
(source: simplygoodcode.com)
For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/
This is not possible in the requested way because there are numbers with two decimal places which can not be expressed exactly using IEEE floating point numbers (for example 1/10 = 0.1 can not be expressed as a Double
or Float
). The formatting should always happen as the last step before presenting the result to the user.
I guess you are asking because you want to deal with monetary values. There is no way to do this reliably with floating-point numbers, you shoud consider switching to fixed-point arithmetics. This probably means doing all calculations in "cents" instead of "dollars".
If anyone's having trouble with this (as I was), you can get the postback code for a button by adding the UseSubmitBehavior="false" attribute to it. If you examine the rendered source of the button, you'll see the exact javascript you need to execute. In my case it was using the name of the button rather than the id.
You might also need to provide your user with an alert showing that those functions are disabled for the text input fields. This will work
function showError(){_x000D_
alert('you are not allowed to cut,copy or paste here');_x000D_
}_x000D_
_x000D_
$('.form-control').bind("cut copy paste",function(e) {_x000D_
e.preventDefault();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<textarea class="form-control" oncopy="showError()" onpaste="showError()"></textarea>
_x000D_
while (listBox1.Items.Count > 0){
listBox1.Items.Remove(0);
}
string s2 = s1.Replace(",", ",\n") + ",....";
Immediately after the object is instantiatd, you can attach a property, say name
, to the object and assign the string value you expect to it:
var myObj = new someClass();
myObj.name="myObj";
document.write(myObj.name);
Alternatively, the assignment can be made inside the codes of the class, i.e.
var someClass = function(P)
{ this.name=P;
// rest of the class definition...
};
var myObj = new someClass("myObj");
document.write(myObj.name);
An "em" is a typographical unit of width, the width of a wide-ish letter like "m" pronounced "em". Similarly there is an "en". Similarly "en-dash" and "em-dash" for – and —
You should probably use a JavaScript library to do things like this.
For example, MochiKit has a function removeElement, and jQuery has remove.
Code coverage has been explained well in the previous answers. So this is more of an answer to the second part of the question.
We've used three tools to determine code coverage.
We use these tools to
Regex is overkill here.
You could use string.Split
with the overload that takes a string[]
for the delimiters but that would also be overkill.
Look at Substring
and IndexOf
- the former to get parts of a string given and index and a length and the second for finding indexed of inner strings/characters.
This is what worked for me
curl --form file='@filename' URL
It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.
So firstly, the only mistake the OP made was in not using the @
symbol before the file name. Secondly, my answer which uses file=...
only worked for me because the form field I was trying to do the upload for was called file
. If your form field is called something else, use that name instead.
From the curl
manpages; under the description for the option --form
it says:
This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
Chances are that if you are trying to do a form upload, you will most likely want to use the @
prefix to upload the file rather than <
which uploads the contents of the file.
Now I must also add that one must be careful with using the <
symbol because in most unix shells, <
is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <
]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl
command does not behave the way you expect.
On that same note, I will also recommend quoting the @
symbol.
You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?
I say this because curl
offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data
option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.
Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.
In your html file you write:
<div class="banner">
Center content
</div>
your css file you write:
.banner {
display: block;
margin: auto;
width: 100px;
height: 50px;
}
works for me.
If you want to convert a property to an integer from properties file there are 2 solutions which I found:
Given scenario: customer.properties contains customer.id = 100 as a field and you want to access it in spring configuration file as integer.The property customerId is declared as type int in the Bean Customer
Solution 1:
<property name="customerId" value="#{T(java.lang.Integer).parseInt('${customer.id}')}" />
_x000D_
In the above line, the string value from properties file is converted to int type.
solution 2: Use some other extension inplace of propeties.For Ex.- If your properties file name is customer.properties then make it customer.details and in the configuration file use the below code
<property name="customerId" value="${customer.id}" />
_x000D_
I checked with below code and it works fine for me. I found answer from here.
driver = new ChromeDriver();
driver.manage().window().maximize();
String baseUrl = "http://www.google.co.uk/";
driver.get(baseUrl);
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab
driver.get("https://www.facebook.com");
driver.switchTo().window(tabs.get(0)); // switch back to main screen
driver.get("https://www.news.google.com");
Use process.h instead of stdlib and iostream... It will work 100%.
One suggestion is that use a pdf library like PDFJS.
Yo have to append, the following "data:application/pdf;base64"
+ your pdf String, and set the src of your element to that.
Try with this example:
var pdfsrc = "data:application/pdf;base64" + "67987yiujkhkyktgiyuyhjhgkhgyi...n"
<pdf-element id="pdfOpen" elevation="5" downloadable src="pdfsrc" ></pdf-element>
Hope it helps :)
A built-in Map type is now available in JavaScript. It can be used instead of simply using Object. It is supported by current versions of all major browsers.
Maps do not support the [subscript]
notation used by Objects. That syntax implicitly casts the subscript
value to a primitive string or symbol. Maps support any values as keys, so you must use the methods .get(key)
, .set(key, value)
and .has(key)
.
var m = new Map();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
m.set(key1, 'value1');_x000D_
m.set(key2, 'value2');_x000D_
_x000D_
console.assert(m.has(key2), "m should contain key2.");_x000D_
console.assert(!m.has(key3), "m should not contain key3.");
_x000D_
Objects only supports primitive strings and symbols as keys, because the values are stored as properties. If you were using Object, it wouldn't be able to to distinguish key2
and key3
because their string representations would be the same:
var o = new Object();_x000D_
var key1 = 'key1';_x000D_
var key2 = {};_x000D_
var key3 = {};_x000D_
_x000D_
o[key1] = 'value1';_x000D_
o[key2] = 'value2';_x000D_
_x000D_
console.assert(o.hasOwnProperty(key2), "o should contain key2.");_x000D_
console.assert(!o.hasOwnProperty(key3), "o should not contain key3."); // Fails!
_x000D_
1 for month is February. The 30th of February is changed to 1st of March. You should set 0 for month. The best is to use the constant defined in Calendar:
c1.set(2000, Calendar.JANUARY, 30);
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
You can either
fig, ax = plt.subplots() #create figure and axes
candlestick(ax, quotes, ...)
or
candlestick(plt.gca(), quotes) #get the axis when calling the function
The first gives you more flexibility. The second is much easier if candlestick is the only thing you want to plot
The content of the table/tables in PostgreSQL database can be deleted in several ways.
Deleting table content using sql:
Deleting content of one table:
TRUNCATE table_name;
DELETE FROM table_name;
Deleting content of all named tables:
TRUNCATE table_a, table_b, …, table_z;
Deleting content of named tables and tables that reference to them (I will explain it in more details later in this answer):
TRUNCATE table_a, table_b CASCADE;
Deleting table content using pgAdmin:
Deleting content of one table:
Right click on the table -> Truncate
Deleting content of table and tables that reference to it:
Right click on the table -> Truncate Cascaded
Difference between delete and truncate:
From the documentation:
DELETE deletes rows that satisfy the WHERE clause from the specified table. If the WHERE clause is absent, the effect is to delete all rows in the table. http://www.postgresql.org/docs/9.3/static/sql-delete.html
TRUNCATE is a PostgreSQL extension that provides a faster mechanism to remove all rows from a table. TRUNCATE quickly removes all rows from a set of tables. It has the same effect as an unqualified DELETE on each table, but since it does not actually scan the tables it is faster. Furthermore, it reclaims disk space immediately, rather than requiring a subsequent VACUUM operation. This is most useful on large tables. http://www.postgresql.org/docs/9.1/static/sql-truncate.html
Working with table that is referenced from other table:
When you have database that has more than one table the tables have probably relationship. As an example there are three tables:
create table customers (
customer_id int not null,
name varchar(20),
surname varchar(30),
constraint pk_customer primary key (customer_id)
);
create table orders (
order_id int not null,
number int not null,
customer_id int not null,
constraint pk_order primary key (order_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
create table loyalty_cards (
card_id int not null,
card_number varchar(10) not null,
customer_id int not null,
constraint pk_card primary key (card_id),
constraint fk_customer foreign key (customer_id) references customers(customer_id)
);
And some prepared data for these tables:
insert into customers values (1, 'John', 'Smith');
insert into orders values
(10, 1000, 1),
(11, 1009, 1),
(12, 1010, 1);
insert into loyalty_cards values (100, 'A123456789', 1);
Table orders references table customers and table loyalty_cards references table customers. When you try to TRUNCATE / DELETE FROM the table that is referenced by other table/s (the other table/s has foreign key constraint to the named table) you get an error. To delete content from all three tables you have to name all these tables (the order is not important)
TRUNCATE customers, loyalty_cards, orders;
or just the table that is referenced with CASCADE key word (you can name more tables than just one)
TRUNCATE customers CASCADE;
The same applies for pgAdmin. Right click on customers table and choose Truncate Cascaded.
The default Gson implementation of Map serialization uses toString()
on the key:
Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Will give:
{
"java.awt.Point[x\u003d1,y\u003d2]": "a",
"java.awt.Point[x\u003d3,y\u003d4]": "b"
}
enableComplexMapKeySerialization
If you want the Map Key to be serialized according to default Gson rules you can use enableComplexMapKeySerialization. This will return an array of arrays of key-value pairs:
Gson gson = new GsonBuilder().enableComplexMapKeySerialization()
.setPrettyPrinting().create();
Map<Point, String> original = new HashMap<>();
original.put(new Point(1, 2), "a");
original.put(new Point(3, 4), "b");
System.out.println(gson.toJson(original));
Will return:
[
[
{
"x": 1,
"y": 2
},
"a"
],
[
{
"x": 3,
"y": 4
},
"b"
]
]
More details can be found here.
You are applying shapiro.test()
to a data.frame
instead of the column. Try the following:
shapiro.test(heisenberg$HWWIchg)
It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).
One way around this is to bind your event handler in javascript (where it should be):
document.getElementById('optionID').onchange = function () {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:
window.changeMessage() {
document.getElementById("message").innerHTML = "Having a Baby!!";
};
?
Try this using this single code:
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("/serviceX")
public class MyClassRESTService {
@POST
@Path("/doSomething")
public void someMethod(String x) {
System.out.println(x);
// String x contains the body, you can process
// it, parse it using JAXB and so on ...
}
}
The url for try rest services ends .... /serviceX/doSomething
A little late to the party, but here's another solution.
Simply adjusting the class of the modal to something like alert-danger
does work, however it removes the top rounded corners of the modal.
A workaround is to give the element with modal-header
an additional class of panel-heading
, e.g.
<div class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header panel-heading"> <!-- change here -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Then, to change the heading color you can do something like (assuming you're using jQUery)
jQuery('.modal-content').addClass('panel-danger')
If this string is for presentation to the end user, you should use NSNumberFormatter
. This will add thousands separators, and will honor the localization settings for the user:
NSInteger n = 10000;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *string = [formatter stringFromNumber:@(n)];
In the US, for example, that would create a string 10,000
, but in Germany, that would be 10.000
.
Our server calls stored procs from Java like so - works on both SQL Server 2000 & 2008:
String SPsql = "EXEC <sp_name> ?,?"; // for stored proc taking 2 parameters
Connection con = SmartPoolFactory.getConnection(); // java.sql.Connection
PreparedStatement ps = con.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(<timeout value>);
ps.setString(1, <param1>);
ps.setString(2, <param2>);
ResultSet rs = ps.executeQuery();
http://php.net/manual/en/language.types.array.php
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// as of PHP 5.4
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
Standard arrays can be used that way.
Just Do,
CTRL + X
CTRL + C
It will ask you to save file, Press Y, then you are done.
Use socat for this:
For example:
socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11
If you are working with Android's MediaStore database, here is how to store an image and then display it after it is saved.
on button click write this
Intent in = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
in.putExtra("crop", "true");
in.putExtra("outputX", 100);
in.putExtra("outputY", 100);
in.putExtra("scale", true);
in.putExtra("return-data", true);
startActivityForResult(in, 1);
then do this in your activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK && data != null) {
Bitmap bmp = (Bitmap) data.getExtras().get("data");
img.setImageBitmap(bmp);
btnadd.requestFocus();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImageString = Base64.encodeToString(b, Base64.DEFAULT);
byte[] bytarray = Base64.decode(encodedImageString, Base64.DEFAULT);
Bitmap bmimage = BitmapFactory.decodeByteArray(bytarray, 0,
bytarray.length);
}
}
There is a switch
statement but I can never seem to get it to work the way I think it should. Since you have not provided an example I will make one using a factor variable:
dft <-data.frame(x = sample(letters[1:8], 20, replace=TRUE))
levels(dft$x)
[1] "a" "b" "c" "d" "e" "f" "g" "h"
If you specify the categories you want in an order appropriate to the reassignment you can use the factor or numeric variables as an index:
c("abc", "abc", "abc", "def", "def", "def", "g", "h")[dft$x]
[1] "def" "h" "g" "def" "def" "abc" "h" "h" "def" "abc" "abc" "abc" "h" "h" "abc"
[16] "def" "abc" "abc" "def" "def"
dft$y <- c("abc", "abc", "abc", "def", "def", "def", "g", "h")[dft$x] str(dft)
'data.frame': 20 obs. of 2 variables:
$ x: Factor w/ 8 levels "a","b","c","d",..: 4 8 7 4 6 1 8 8 5 2 ...
$ y: chr "def" "h" "g" "def" ...
I later learned that there really are two different switch functions. It's not generic function but you should think about it as either switch.numeric
or switch.character
. If your first argument is an R 'factor', you get switch.numeric
behavior, which is likely to cause problems, since most people see factors displayed as character and make the incorrect assumption that all functions will process them as such.
Based on a general research and understanding, "Almost" Everything that can be accessed via a browser is actually called a "Web application" now these days. Even your internet router at home is a web application that uses the HTTP protocol to access the application (i.e the one that "interacts" with you). Yes, there are lots of websites that do "Nothing" except showing you stuff. But the age we are living in, everything operates on the basis of web application. Natwest PLC bank has got a website where you can go and find out things that natwest offer as a consumer/high-street bank. However:
1) You can create your online banking account - Web application 2) View, amend details on your personal stuff - web application 3) Manage money - Web application 4) Deal shares/stocks - Web application
Another good example is Fidelity.com (as quoted in many other examples on the web).
I'm going to have to argue and say that there are two answers:
1) If your purpose is simply to inform your audience with some contents that will never demand any interaction whatsoever, website is your answer. Then it is not a web application.
2) If you are living in the current/modern world i.e. will have a personal site, allow people to see some/all/none of your special stuff, protect yourself from people/bots/etc., web application and websites are no different.
If a profiler is not applicable in your setup, you may try to identify the thread following steps in this post.
Basically, there are three steps:
top -H
and get PID of the thread with highest CPU.There are three types of variables:
The default values for instance and static variables are the same and depends on the type:
An array is an Object. So an array instance variable that is declared but no explicitly initialized will have null value. If you declare an int[] array as instance variable it will have the null value.
Once the array is created all of its elements are assiged with the default type value. For example:
private boolean[] list; // default value is null
private Boolean[] list; // default value is null
once is initialized:
private boolean[] list = new boolean[10]; // all ten elements are assigned to false
private Boolean[] list = new Boolean[10]; // all ten elements are assigned to null (default Object/Boolean value)
In Chrome Browser go to setting , clear browsing history and then reload the page
If Libraries/React.xcodeproj
are red in xcode then reinstall node_modules
rm -rf node_modules && yarn
My newly created project from react-native 0.46.3 was red :S I have npm 5.3.0 and yarn 0.24.5 when I did react-native init
Hope to give some extra input in solving this question (or part of it).
This will work for opening an Excel
file from another. A line of code from Mr. Peter L., for the change, use the following:
Application.Workbooks.Open Filename:="C:\Book1withLinkToBook2.xlsx", UpdateLinks:=3
This is in MSDS
. The effect is that it just updates everything (yes, everything) with no warning. This can also be checked if you record a macro.
In MSDS
, it refers this to MS EXCEL 2010
and 2013
. I'm thinking that MS EXCEL 2016
has this covered as well.
I have MS EXCEL 2013
, and have a situation pretty much the same as this topic. So I have a file (call it A
) with Workbook_Open
event code that always get's stuck on the update links prompt.
I have another file (call it B
) connected to this one, and Pivot Tables force me to open the file A
so that the data model can be loaded. Since I want to open the A
file silently in the background, I just use the line that I wrote above, with a Windows("A.xlsx").visible = false
, and, apart from a bigger loading time, I open the A
file from the B
file with no problems or warnings, and fully updated.
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
you can try this (I don't have sql server here today so I can't verify syntax, sorry)
select attributeName
from tableName
where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
and DATEPART(day,attributeName) BETWEEN 2 AND 4
Quickest and may be the best solution is to have below content in <TOMCAT_INSTALL_DIR>/conf/Catalina/localhost/ROOT.xml
<Context
docBase="/your_webapp_location_directory"
path=""
reloadable="true"
/>
And your webapp will be available at http://<host>:<port>/
You can use the attribute df.empty
to check whether it's empty or not:
if df.empty:
print('DataFrame is empty!')
Source: Pandas Documentation
[tested in XCode 7.2 and for iOS 9.2]
What suppressed the Storyboard errors and warnings for me was setting the intrinsic size of the scroll view and the content view (in my case, a stackview) to Placeholder. This setting is found in the Size inspector in Storyboard. And it says - Setting a design time intrinsic content size only affects a view while editing in Interface Builder. The view will not have this intrinsic content size at runtime.
So, I guess we aren't going wrong by setting this.
Note: In storyboard, I have pinned all the edges of scrollview to the superview and all the edges of stackview to the scrollview. In my code, I have set the translatesAutoresizingMaskIntoConstraints as false for both the scrollview and the stackview. And I have not mentioned a content size. When the stackview grows dynamically, the constraints set in storyboard ensure that the stack is scrollable.
The storyboard warning was driving me mad and I didn't want to centre things horizontally or vertically just to suppress the warning.
Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();
. However, you have updated your code to use the List.isEmpty()
method to properly check if the list is empty.
The problem now is that you are never actually sending an empty list to giveList()
. In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.
do {
number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
/* Change this line */
if (number != -1) numbers.add(number);
} while (number != -1);
The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:
var black = $('.black');
var white = $('.white');
The selector will find every element classed under black or white. Button functions stay as stated above:
$('#showBlackButton').click(function() {
black.show();
white.hide();
});
$('#showWhiteButton').click(function() {
white.show();
black.hide();
});
As long as your list is initialized with values and that value actually exists in the list, then Contains should return true.
I tried the following:
var list = new List<int> {1,2,3,4,5};
var intVar = 4;
var exists = list.Contains(intVar);
And exists is indeed set to true.
Passing arguments by bundle is restricted to some data types. But you can transfer any data to your fragment this way:
In your fragment create a public method like this
public void passData(Context context, List<LexItem> list, int pos) {
mContext = context;
mLexItemList = list;
mIndex = pos;
}
and in your activity call passData() with all your needed data types after instantiating the fragment
WebViewFragment myFragment = new WebViewFragment();
myFragment.passData(getApplicationContext(), mLexItemList, index);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.my_fragment_container, myFragment);
ft.addToBackStack(null);
ft.commit();
Remark: My fragment extends "android.support.v4.app.Fragment", therefore I have to use "getSupportFragmentManager()". Of course, this principle will work also with a fragment class extending "Fragment", but then you have to use "getFragmentManager()".
You can use // instead of single /. That converts to int
directly.
For now, use an EditText
. Use android:inputType="number"
to force it to be numeric. Convert the resulting string into an integer (e.g., Integer.parseInt(myEditText.getText().toString())
).
In the future, you might consider a NumberPicker
widget, once that becomes available (slated to be in Honeycomb).
You don't need jQuery, just a regular expression.
This will remove the last underscore:
var str = 'a_b_c';_x000D_
console.log( str.replace(/_([^_]*)$/, '$1') ) //a_bc
_x000D_
This will replace it with the contents of the variable replacement
:
var str = 'a_b_c',_x000D_
replacement = '!';_x000D_
_x000D_
console.log( str.replace(/_([^_]*)$/, replacement + '$1') ) //a_b!c
_x000D_
Hmm, I would suggest that you use Flyweight to implement the states. Purpose: Avoid the memory overhead of a large number of small objects. State machines can get very, very big.
http://en.wikipedia.org/wiki/Flyweight_pattern
I'm not sure that I see the need to use design pattern State to implement the nodes. The nodes in a state machine are stateless. They just match the current input symbol to the available transitions from the current state. That is, unless I have entirely forgotten how they work (which is a definite possiblilty).
If I were coding it, I would do something like this:
interface FsmNode {
public boolean canConsume(Symbol sym);
public FsmNode consume(Symbol sym);
// Other methods here to identify the state we are in
}
List<Symbol> input = getSymbols();
FsmNode current = getStartState();
for (final Symbol sym : input) {
if (!current.canConsume(sym)) {
throw new RuntimeException("FSM node " + current + " can't consume symbol " + sym);
}
current = current.consume(sym);
}
System.out.println("FSM consumed all input, end state is " + current);
What would Flyweight do in this case? Well, underneath the FsmNode there would probably be something like this:
Map<Integer, Map<Symbol, Integer>> fsm; // A state is an Integer, the transitions are from symbol to state number
FsmState makeState(int stateNum) {
return new FsmState() {
public FsmState consume(final Symbol sym) {
final Map<Symbol, Integer> transitions = fsm.get(stateNum);
if (transisions == null) {
throw new RuntimeException("Illegal state number " + stateNum);
}
final Integer nextState = transitions.get(sym); // May be null if no transition
return nextState;
}
public boolean canConsume(final Symbol sym) {
return consume(sym) != null;
}
}
}
This creates the State objects on a need-to-use basis, It allows you to use a much more efficient underlying mechanism to store the actual state machine. The one I use here (Map(Integer, Map(Symbol, Integer))) is not particulary efficient.
Note that the Wikipedia page focuses on the cases where many somewhat similar objects share the similar data, as is the case in the String implementation in Java. In my opinion, Flyweight is a tad more general, and covers any on-demand creation of objects with a short life span (use more CPU to save on a more efficient underlying data structure).
You can use momentjs duration object
Example:
const diff = moment.duration(Date.now() - new Date(2010, 1, 1))
console.log(`${diff.years()} years ${diff.months()} months ${diff.days()} days ${diff.hours()} hours ${diff.minutes()} minutes and ${diff.seconds()} seconds`)
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
The path to the nginx.conf
file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf
.
You may access and edit this file by typing this at the terminal
cd /etc/nginx
/etc/nginx$ sudo nano nginx.conf
Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.
I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf
file which is the primary Configuration file for Nginx.
Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d
. Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-
http{
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
Further to this you may comment out from the PRIMARY Config file , the line
http{
#include /etc/nginx/sites-available/some_file.conf; # Comment Out
include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}
and need not keep any Config Files in /etc/nginx/sites-available/
and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/
, kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .
EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/
, this was the older practice and is DEPRECIATED now .
Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf;
.
Quote from Nginx CookBook page - 5 .
"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."
in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:
<item
android:id="@+id/OK_MENU_ITEM"
android:onClick="showMsgDirectMenuXml" />
And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:
private void showMsgDirectMenuXml(MenuItem item) {
Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
toast.show();
}
NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)
For z-index:1000
to have an effect you need a non-static positioning scheme.
Add position:relative;
to a rule selecting the element you want to be on top
Moved from the closed topic
del /s d:\test\archive*.txt
This should get you all of your text files
Alternatively,
I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.
Please test this on your system before using it though.
@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION
REM ---------------------------
REM *** EDIT VARIABLES BELOW ***
REM ---------------------------
set targetFolder=
REM targetFolder is the location you want to delete from
REM ---------------------------
REM *** DO NOT EDIT BELOW ***
REM ---------------------------
IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
set "Subfolders[!Index!]=%%D"
set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!
:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in:
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start
:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end
:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end
:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit
REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)
If you change the
set targetFolder=
to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp
Hope this helps
display: inline-block
adds an extra margin to your element.
I would recommend this:
#element {
display: table; /* IE8+ and all other modern browsers */
}
Bonus: You can also now easily center that fancy new #element
just by adding margin: 0 auto
.
From PHP 5.4 you can take advantage of array dereferencing and do something like this:
<?
function data()
{
$retr_arr["a"] = "abc";
$retr_arr["b"] = "def";
$retr_arr["c"] = "ghi";
return $retr_arr;
}
$a = data()["a"]; //$a = "abc"
$b = data()["b"]; //$b = "def"
$c = data()["c"]; //$c = "ghi"
?>
Microsoft do not support C99 and haven't announced any plans to. I believe they intend to track C++ standards but consider C as effectively obsolete except as a subset of C++.
New projects in Visual Studio 2003 and later have the "Compile as C++ Code (/TP)" option set by default, so any .c files will be compiled as C++.
Does <img src="/path/to/pic.jpg" style="max-width:XXXpx; max-height:YYYpx;" >
help?
Browser will take care of keeping aspect ratio intact.
i.e max-width
kicks in when image width is greater than height and its height will be calculated proportionally. Similarly max-height
will be in effect when height is greater than width.
You don't need any jQuery or javascript for this.
Supported by ie7+ and other browsers (http://caniuse.com/minmaxwh).
check the following code to open new activit.
Intent f = new Intent(MainActivity.this, SecondActivity.class);
startActivity(f);
To solve this you must ensure the following is true on the machine hosting SQL Server...
In GAS global variables are not what they are in other languages. They are not constants nor variables available in all routines.
I thought I could use global variables for consistency amongst functions and efficiency as well. But I was wrong as pointed out by some people here at SO.
Global variable will be evaluated at each execution of a script, so not just once every time you run your application.
Global variables CAN be changed in a script (so they are not constants that cannot be changed by accident), but will be reinitialized when another script will be invoked.
There is also a speed penalty on using global variables. If within a function you use the same global variable two or more times, it will be faster to assign a local variable and use that instead.
If you want to preserve variables between all functions in your application, it might be using a cacheService will be best. I found out that looping through all files and folders on a drive takes a LOT of time. But you can store info about files and folders within cache (or even properties) and speed up at least 100 times.
The only way I use global variables now is for some prefixes and for naming widgets.
You can use sys.exit()
to exit from the middle of the main function.
However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__
- then you can use return as normal.
Java Language Specification defines E1 op= E2
to be equivalent to E1 = (T) ((E1) op (E2))
where T
is a type of E1
and E1
is evaluated once.
That's a technical answer, but you may be wondering why that's a case. Well, let's consider the following program.
public class PlusEquals {
public static void main(String[] args) {
byte a = 1;
byte b = 2;
a = a + b;
System.out.println(a);
}
}
What does this program print?
Did you guess 3? Too bad, this program won't compile. Why? Well, it so happens that addition of bytes in Java is defined to return an int
. This, I believe was because the Java Virtual Machine doesn't define byte operations to save on bytecodes (there is a limited number of those, after all), using integer operations instead is an implementation detail exposed in a language.
But if a = a + b
doesn't work, that would mean a += b
would never work for bytes if it E1 += E2
was defined to be E1 = E1 + E2
. As the previous example shows, that would be indeed the case. As a hack to make +=
operator work for bytes and shorts, there is an implicit cast involved. It's not that great of a hack, but back during the Java 1.0 work, the focus was on getting the language released to begin with. Now, because of backwards compatibility, this hack introduced in Java 1.0 couldn't be removed.
use get_loaded_extensions()
PHP function
Regarding tex?image conversion, the tool LaTeXiT produces much higher quality output. I believe it is standard in most TeX distributions but you can certainly find it online if you don't already have it. All you need to do is put it in the TeX, drag the image to your desktop, then drag from your desktop to an image hosting site (I use imgur).
For the fastest way $ cd "project"
you can also just do it this way
document.getElementById(id).outerHTML
where id is the id of the element that you are looking for
I modified my activate script to source the file .virtualenvrc
, if it exists in the current directory, and to save/restore PYTHONPATH
on activate/deactivate.
You can find the patched activate
script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.
Then I added something like this to my .virtualenvrc
:
export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"
"Error code: ssl_error_no_cypher_overlap" error message after login, when Welcome screen expected--using Firefox browser Solution 1: enter 'about:config' in Browser Address bar 2: find/select "security.ssl3.rsa_rc4_40_md5" 3: set boolean to TRUE
Edge (as opposed to IE11) has a better UI for Local storage / Session storage and cookies:
If you are trying to add arguments to a handler in recompose
, make sure that you're defining your arguments correctly in the handler. It is essentially a curried function, so you want to be sure to require the correct number of arguments. This page has a good example of using arguments with handlers.
Example (from the link):
withHandlers({
handleClick: props => (value1, value2) => event => {
console.log(event)
alert(value1 + ' was clicked!')
props.doSomething(value2)
},
})
for your child HOC and in the parent
class MyComponent extends Component {
static propTypes = {
handleClick: PropTypes.func,
}
render () {
const {handleClick} = this.props
return (
<div onClick={handleClick(value1, value2)} />
)
}
}
this avoids writing an anonymous function out of your handler to patch fix the problem with not supplying enough parameter names on your handler.
Make sure you have added all your changes to the staging area before running
git mv oldFolderName newFoldername
git fails with error
fatal: bad source, source=oldFolderName/somepath/somefile.foo, destination=newFolderName/somepath/somefile.foo
if there are any unadded files, so I just found out.
you can use a Scanner to read from input :
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0); //charAt() method returns the character at the specified index in a string. The index of the first character is 0, the second character is 1, and so on.
I would suggest that the current solution is to use my package urllib2_prior_auth which solves this pretty nicely (I work on inclusion to the standard lib.
I would just mention that you can use the cat
command to concatenate the input files prior to piping them to markdown_py
which has the same effect as what pandoc
does with multiple input files coming in.
cat *.md | markdown_py > youroutputname.html
works pretty much the same as the pandoc example above for the Python version of Markdown on my Mac.
import os#must import this library
if os.path.exists('TwitterDB.csv'):
os.remove('TwitterDB.csv') #this deletes the file
else:
print("The file does not exist")#add this to prevent errors
I had a similar problem, and instead of overwriting my existing file using the different 'modes', I just deleted the file before using it again, so that it would be as if I was appending to a new file on each run of my code.
chmod 600 id_rsa
Run above command from path where key is stored in vm ex: cd /home/opc/.ssh
From Wikipedia:
HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.
But some web applications may have to track the user's progress from page to page, for example when a web server is required to customize the content of a web page for a user. Solutions for these cases include:
- the use of HTTP cookies.
- server side sessions,
- hidden variables (when the current page contains a form), and
- URL-rewriting using URI-encoded parameters, e.g., /index.php?session_id=some_unique_session_code.
What makes the protocol stateless is that the server is not required to track state over multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server, and in many cases (for instance serving up static data over a CDN) minimizes the amount of data that needs to be transferred. If servers were required to maintain the state of clients' visits the structure of issuing and responding to requests would be more complex. As it is, the simplicity of the model is one of its greatest features.
You can use the following script if you don't wish to use Wizard;
RESTORE DATABASE myDB
FROM DISK = N'C:\BackupDB.bak'
WITH REPLACE,RECOVERY,
MOVE N'HRNET' TO N'C:\MSSQL\Data\myDB.mdf',
MOVE N'HRNET_LOG' TO N'C:\MSSQL\Data\myDB.ldf'
Take a look at the LobBasicSample for an example to use CLOB, BLOB, NLOB datatypes.
A version without error-handling:
Function sheetExists(sheetToFind As String) As Boolean
sheetExists = False
For Each sheet In Worksheets
If sheetToFind = sheet.name Then
sheetExists = True
Exit Function
End If
Next sheet
End Function
The 'react-json-view' provides solution rendering json string.
import ReactJson from 'react-json-view';
<ReactJson src={my_important_json} theme="monokai" />
I came up with this solution. It works solid with the latest Symfony 2.4.
I will try to give some explanations.
I think it's a bad idea to use separate validation to validate entities and return constraint violation messages, like suggested by other writers.
You will need to manually validate all the entities, specify validation groups, etc, etc. With complex hierarchical forms it's not practical at all and will get out of hands quickly.
This way you will be validating form twice: once with form and once with separate validator. This is a bad idea from the performance perspective.
I suggest to recursively iterate form type with it's children to collect error messages.
Some answers suggested by another authors contain mutually exclusive IF statements like this: if ($form->count() > 0)
or if ($form->hasChildren())
.
As far as I can see, every form can have errors as well as children. I'm not expert with Symfony Forms component, but in practice you will not get some errors of the form itself, like CSRF protection error or extra fields error. I suggest to remove this separation.
Some authors suggest to put all errors inside of a plain array. So all the error messages of the form itself and of it's children will be added to the same array with different indexing strategies: number-based for type's own errors and name-based for children errors. I suggest to use normalized data structure of the form:
errors:
- "Self error"
- "Another self error"
children
- "some_child":
errors:
- "Children error"
- "Another children error"
children
- "deeper_child":
errors:
- "Children error"
- "Another children error"
- "another_child":
errors:
- "Children error"
- "Another children error"
That way result can be easily iterated later.
So here's my solution to this problem:
use Symfony\Component\Form\Form;
/**
* @param Form $form
* @return array
*/
protected function getFormErrors(Form $form)
{
$result = [];
// No need for further processing if form is valid.
if ($form->isValid()) {
return $result;
}
// Looking for own errors.
$errors = $form->getErrors();
if (count($errors)) {
$result['errors'] = [];
foreach ($errors as $error) {
$result['errors'][] = $error->getMessage();
}
}
// Looking for invalid children and collecting errors recursively.
if ($form->count()) {
$childErrors = [];
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$childErrors[$child->getName()] = $this->getFormErrors($child);
}
}
if (count($childErrors)) {
$result['children'] = $childErrors;
}
}
return $result;
}
I hope it'll help someone.
After having read lots of discussions, I have prepared a simple solution but I don't want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
My option was this:
Create a subroutine that takes in the message and automates the process of sending it to both console and log file.
setlocal
set logfile=logfile.log
call :screenandlog "%DATE% %TIME% This message goes to the screen and to the log"
goto :eof
:screenandlog
set message=%~1
echo %message% & echo %message% >> %logfile%
exit /b
If you add a variable to the message, be sure to remove the quotes in it before sending it to the subroutine or it can screw your batch. Of course this only works for echoing.
Exception code 0xc0000005
is an Access Violation. An AV at fault offset 0x00000000
means that something in your service's code is accessing a nil
pointer. You will just have to debug the service while it is running to find out what it is accessing. If you cannot run it inside a debugger, then at least install a third-party exception logger framework, such as EurekaLog or MadExcept, to find out what your service was doing at the time of the AV.
Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:
GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/
Note first that a double
is a binary fraction and does not really have decimal places.
If you need decimal places, use a BigDecimal
, which has a setScale()
method for truncation, or use DecimalFormat
to get a String
.
Just use myList.remove(myObject)
.
It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)
BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.
You could also expose the directive's controller to the parent scope, like ngForm
with name
attribute does: http://docs.angularjs.org/api/ng.directive:ngForm
Here you could find a very basic example how it could be achieved http://plnkr.co/edit/Ps8OXrfpnePFvvdFgYJf?p=preview
In this example I have myDirective
with dedicated controller with $clear
method (sort of very simple public API for the directive). I can publish this controller to the parent scope and use call this method outside the directive.
That is not problem of IIS but the problem of WCF. WCF by default limits messages to 65KB to avoid denial of service attack with large messages. Also if you don't use MTOM it sends byte[] to base64 encoded string (33% increase in size) => 48KB * 1,33 = 64KB
To solve this issue you must reconfigure your service to accept larger messages. This issue previously fired 400 Bad Request error but in newer version WCF started to use 413 which is correct status code for this type of error.
You need to set maxReceivedMessageSize
in your binding. You can also need to set readerQuotas
.
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding maxReceivedMessageSize="10485760">
<readerQuotas ... />
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
While receiving the stream do these steps.
1st set some reasonable chunk size
Pseudo Code idea:
Continue the first 4 steps while receiving the stream. The final step would be to either fail if you exceeded memory or start outputting the result once all the data is collected by beginning to sort the ranges and spit out the results in order and uncompressing those in order that need to be uncompressed and sort them when you get to them.
This is now no longer needed for Java 9, nor for any recent release of Java 6, 7, or 8. Finally! :)
Per JDK-8170157, the unlimited cryptographic policy is now enabled by default.
Specific versions from the JIRA issue:
Note that if for some odd reason the old behavior is needed in Java 9, it can be set using:
Security.setProperty("crypto.policy", "limited");
Add this line in your styles.xml
file:
<style>
<item name="android:colorAccent">@android:color/holo_green_dark</item>
</style>
source ~/.bash_profile
export ANDROID_HOME=/YOUR_PATH_TO/android-sdk
export PATH=$ANDROID_HOME/platform-tools:$PATH
Use shuf
with the -n
option as shown below, to get N
random lines:
shuf -n N input > output
There is no subquery needed with this statement, which is better written as
select u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
or
select u.*
from Users u inner join CompanyRolesToUsers c
on u.Id = c.UserId --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
That being said, in LINQ it would be
from u in Users
from c in CompanyRolesToUsers
where u.Id == c.UserId &&
u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
or
from u in Users
join c in CompanyRolesToUsers
on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is...
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id = "@+id/Everything"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- other actual layout stuff here EVERYTHING HERE -->
</LinearLayout>
<LinearLayout
android:id="@+id/overlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right" >
</LinearLayout>
Now any view you add under LinearLayout with android:id = "@+id/overlay"
will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything"
I wouldn't advise you to do this but on my personal computer I disabled the firewall so that maven could get the required plugins.
Both approaches behave differently if you use a spied object (annotated with @Spy
) instead of a mock (annotated with @Mock
):
when(...) thenReturn(...)
makes a real method call just before the specified value will be returned. So if the called method throws an Exception you have to deal with it / mock it etc. Of course you still get your result (what you define in thenReturn(...)
)
doReturn(...) when(...)
does not call the method at all.
Example:
public class MyClass {
protected String methodToBeTested() {
return anotherMethodInClass();
}
protected String anotherMethodInClass() {
throw new NullPointerException();
}
}
Test:
@Spy
private MyClass myClass;
// ...
// would work fine
doReturn("test").when(myClass).anotherMethodInClass();
// would throw a NullPointerException
when(myClass.anotherMethodInClass()).thenReturn("test");
1)
$stateProvider
.state('app.example1', {
url: '/example',
views: {
'menuContent': {
templateUrl: 'templates/example.html',
controller: 'ExampleCtrl'
}
}
})
.state('app.example2', {
url: '/example2/:object',
views: {
'menuContent': {
templateUrl: 'templates/example2.html',
controller: 'Example2Ctrl'
}
}
})
2)
.controller('ExampleCtrl', function ($state, $scope, UserService) {
$scope.goExample2 = function (obj) {
$state.go("app.example2", {object: JSON.stringify(obj)});
}
})
.controller('Example2Ctrl', function ($state, $scope, $stateParams) {
console.log(JSON.parse($state.params.object));
})
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
Click on the "show details" link under Date (dd/mm/YYY), then you can copy and paste that plugin code provided there
Update: I think you can just switch the order of the array, like so:
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var usDatea = a.split('/');
var usDateb = b.split('/');
var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var usDatea = a.split('/');
var usDateb = b.split('/');
var x = (usDatea[2] + usDatea[0] + usDatea[1]) * 1;
var y = (usDateb[2] + usDateb[0] + usDateb[1]) * 1;
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
All I did was switch the __date_[1]
(day) and __date_[0]
(month), and replaced uk
with us
so you won't get confused. I think that should take care of it for you.
Update #2: You should be able to just use the date object for comparison. Try this:
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var x = new Date(a),
y = new Date(b);
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var x = new Date(a),
y = new Date(b);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
The solution that worked for me in ASP.NET Core 3.1:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddControllersWithViews();
}
and then change the following:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Then program worked and error was solved.
to Hide All Errors:
error_reporting(0);
ini_set('display_errors', 0);
to Show All Errors:
error_reporting(E_ALL);
ini_set('display_errors', 1);
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
if you're using sql server 2005, start sql server browser service first
the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.
at first use this command to install font-awesome-free
npm install --save-dev @fortawesome/fontawesome-free
after that you can do this
@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";
and I copy the font path like below this is optional
.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');
and finally just run the script
npm run dev
or npm run watch
in laravel
If you are working in a restricted workplaces you probably will encounter this problem
A combination of a few things worked for me Basically change https to http
From https:
repositories {
jcenter()
}
To :
repositories {
maven { url "http://jcenter.bintray.com" }
}
and in gradle-wrapper.properties
..
From :
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
To :
distributionUrl=http\://services.gradle.org/distributions/gradle-3.3-all.zip
And then
- (optional) File -> Invalidate Caches / Restart`
- Give a clean build.
To verify : Check your Gradle console. It should start downloading libs from jcenter via HTTP.
This is a very old question - but still for reference if others are looking at it - requestAnimationFrame()
is the right way to handle animation in modern browsers:
UPDATE: The mozilla link shows how to do this - I didn't feel like repeating the text behind the link ;)
I always use this syntax to create the foreign key constraint between 2 tables
Alter Table ForeignKeyTable
Add constraint `ForeignKeyTable_ForeignKeyColumn_FK`
`Foreign key (ForeignKeyColumn)` references `PrimaryKeyTable (PrimaryKeyColumn)`
i.e.
Alter Table tblEmployee
Add constraint tblEmployee_DepartmentID_FK
foreign key (DepartmentID) references tblDepartment (ID)
Try this (LINQ method syntax):
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
or in LINQ Query syntax:
string[] columnNames = (from dc in dt.Columns.Cast<DataColumn>()
select dc.ColumnName).ToArray();
Cast
is required, because Columns is of type DataColumnCollection which is a IEnumerable
, not IEnumerable<DataColumn>
. The other parts should be obvious.
Actually, in this case it's quite simple: apply the vertical align to the image. Since it's all in one line, it's really the image you want aligned, not the text.
<!-- moved "vertical-align:middle" style from span to img -->_x000D_
<div>_x000D_
<img style="vertical-align:middle" src="https://placehold.it/60x60">_x000D_
<span style="">Works.</span>_x000D_
</div>
_x000D_
Tested in FF3.
Now you can use flexbox for this type of layout.
.box {_x000D_
display: flex;_x000D_
align-items:center;_x000D_
}
_x000D_
<div class="box">_x000D_
<img src="https://placehold.it/60x60">_x000D_
<span style="">Works.</span>_x000D_
</div>
_x000D_
Try this code:--
UIImageView *imv = [[UIImageView alloc]initWithFrame:CGRectMake(3,2, 20, 25)];
imv.image=[UIImage imageNamed:@"arrow2.png"];
[cell addSubview:imv];
[imv release];
In the light of the latest httpoxy vulnerabilities, there is really a need for a full example, how to use HTTP_X_FORWARDED_FOR
properly.
So here is an example written in PHP, how to detect a client IP address, if you know that client may be behind a proxy and you know this proxy can be trusted. If you don't known any trusted proxies, just use REMOTE_ADDR
<?php
function get_client_ip ()
{
// Nothing to do without any reliable information
if (!isset ($_SERVER['REMOTE_ADDR'])) {
return NULL;
}
// Header that is used by the trusted proxy to refer to
// the original IP
$proxy_header = "HTTP_X_FORWARDED_FOR";
// List of all the proxies that are known to handle 'proxy_header'
// in known, safe manner
$trusted_proxies = array ("2001:db8::1", "192.168.50.1");
if (in_array ($_SERVER['REMOTE_ADDR'], $trusted_proxies)) {
// Get the IP address of the client behind trusted proxy
if (array_key_exists ($proxy_header, $_SERVER)) {
// Header can contain multiple IP-s of proxies that are passed through.
// Only the IP added by the last proxy (last IP in the list) can be trusted.
$proxy_list = explode (",", $_SERVER[$proxy_header]);
$client_ip = trim (end ($proxy_list));
// Validate just in case
if (filter_var ($client_ip, FILTER_VALIDATE_IP)) {
return $client_ip;
} else {
// Validation failed - beat the guy who configured the proxy or
// the guy who created the trusted proxy list?
// TODO: some error handling to notify about the need of punishment
}
}
}
// In all other cases, REMOTE_ADDR is the ONLY IP we can trust.
return $_SERVER['REMOTE_ADDR'];
}
print get_client_ip ();
?>
You have multiple Google Chrome browser tabs open for the same URL and developer toolbar.
In some other tab, you have set breakpoints which are showing up when you are debugging in the current tab.
Solution: Close the developer toolbar in the other tab or the tab itself.
2.3.5 did not have input tap
, just input keyevent
and input text
You can use the monkeyrunner for it: (this is a copy of the answer at https://stackoverflow.com/a/18959385/1587329):
You might want to use monkeyrunner like this:
$ monkeyrunner
>>> from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
>>> device = MonkeyRunner.waitForConnection()
>>> device.touch(200, 400, MonkeyDevice.DOWN_AND_UP)
You can also do a drag, start activies etc. Have a look at the api for MonkeyDevice.
works for me on windows:
#include <conio.h>
char c = _getch();
Keep it simple...
var array = [1, 2, 3, 4, 5, 6, 7, 9, 0]
var n = 0
for i in array {
n += i
}
print("My sum of elements is: \(n)")
Output:
My sum of elements is: 37
If this is your own source code and you already have a Netbeans project folder with your source files you should just start with:
File | Open Project...
not
File | New Project ...
because the project is not new.
That's what frameworks do, e.g. if you initialize session in Front Controller or boostrap script, you won't have to care about it's initalization either for page controllers or ajax controllers. PHP frameworks are not a panacea, but they do so many useful things like this!
I think you can get the data you want from INFORMATION_SCHEMA TABLES.
You can find more info here: http://dev.mysql.com/doc/refman/5.0/en/tables-table.html
Here's a modified version of Hors answer, works slightly better for my case, as it strips out the base directory that is passed as it goes, and has a recursive switch that can be set to false which is also handy. Plus to make the output more readable, I've separated the file and subdirectory files, so the files are added first then the subdirectory files (see result for what I mean.)
I tried a few other methods and suggestions around and this is what I ended up with. I had another working method already that was very similar, but seemed to fail where there was a subdirectory with no files but that subdirectory had a subsubdirectory with files, it didn't scan the subsubdirectory for files - so some answers may need to be tested for that case.)... anyways thought I'd post my version here too in case someone is looking...
function get_filelist_as_array($dir, $recursive = true, $basedir = '', $include_dirs = false) {
if ($dir == '') {return array();} else {$results = array(); $subresults = array();}
if (!is_dir($dir)) {$dir = dirname($dir);} // so a files path can be sent
if ($basedir == '') {$basedir = realpath($dir).DIRECTORY_SEPARATOR;}
$files = scandir($dir);
foreach ($files as $key => $value){
if ( ($value != '.') && ($value != '..') ) {
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if (is_dir($path)) {
// optionally include directories in file list
if ($include_dirs) {$subresults[] = str_replace($basedir, '', $path);}
// optionally get file list for all subdirectories
if ($recursive) {
$subdirresults = get_filelist_as_array($path, $recursive, $basedir, $include_dirs);
$results = array_merge($results, $subdirresults);
}
} else {
// strip basedir and add to subarray to separate file list
$subresults[] = str_replace($basedir, '', $path);
}
}
}
// merge the subarray to give the list of files then subdirectory files
if (count($subresults) > 0) {$results = array_merge($subresults, $results);}
return $results;
}
I suppose one thing to be careful of it not to pass a $basedir value to this function when calling it... mostly just pass the $dir (or passing a filepath will work now too) and optionally $recursive as false if and as needed. The result:
[0] => demo-image.png
[1] => filelist.php
[2] => tile.png
[3] => 2015\header.png
[4] => 2015\08\background.jpg
Enjoy! Okay, back to the program I'm actually using this in...
UPDATE Added extra argument for including directories in the file list or not (remembering other arguments will need to be passed to use this.) eg.
$results = get_filelist_as_array($dir, true, '', true);
i've written a function that extract numbers from string:
int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
// get startIndex
int startIndex = src.Find(str) + CString(str).GetLength();
// cut the string
CString toreturn = src.Mid(startIndex, length);
// convert to number
return _wtoi(toreturn); // atoi(toreturn)
}
Usage:
CString str = _T("digit:1, number:102");
int digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);
Starting from Xcode 8, you can use the class property attribute as answered by Berbie.
However, in the implementation, you need to define both class getter and setter for the class property using a static variable in lieu of an iVar.
Sample.h
@interface Sample: NSObject
@property (class, retain) Sample *sharedSample;
@end
Sample.m
@implementation Sample
static Sample *_sharedSample;
+ ( Sample *)sharedSample {
if (_sharedSample==nil) {
[Sample setSharedSample:_sharedSample];
}
return _sharedSample;
}
+ (void)setSharedSample:(Sample *)sample {
_sharedSample = [[Sample alloc]init];
}
@end
There is no super() in C++. You have to call the Base Constructor explicitly by name.
For Node/Express developers you can use middleware and set this via server.
app.use(function(req, res, next) {
res.setHeader('X-UA-Compatible', 'IE=edge');
next();
});
Check if you are returning a @ResponseBody or a @ResponseStatus
I had a similar problem. My Controller looked like that:
@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
When calling with a POST request I always got the following error:
HTTP Status 405 - Request method 'POST' not supported
After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.
To fix this simply add a @ResponseBody
@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
or a @ResponseStatus to your method.
@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
return userService.updateUser(user).getId();
}
If you are using SDK 28 or higher, you need to migrate to AndroidX library.
With Android Studio 3.2 and higher, you can migrate an existing project to AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
Check if Xcode is installed or not:
$ gcc --version
$ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
$ brew doctor
$ brew update
http://techsharehub.blogspot.com/2013/08/brew-command-not-found.html "click here for exact instruction updates"
You should remove .Value
from all option buttons because option buttons don't hold the resultant value, the option group control does. If you omit .Value
then the default interface will report the option button status, as you are expecting. You should write all relevant code under commandbutton_click events because whenever the commandbutton is clicked the option button action will run.
If you want to run action code when the optionbutton is clicked then don't write an if loop for that.
EXAMPLE:
Sub CommandButton1_Click
If OptionButton1 = true then
(action code...)
End if
End sub
Sub OptionButton1_Click
(action code...)
End sub
Just to add yet another solution :P, I went with a combination of @spheenik and @collin-anderson 's solutions.
# Ensure that we have an ssh config with AddKeysToAgent set to true
if [ ! -f ~/.ssh/config ] || ! cat ~/.ssh/config | grep AddKeysToAgent | grep yes > /dev/null; then
echo "AddKeysToAgent yes" >> ~/.ssh/config
fi
# Ensure a ssh-agent is running so you only have to enter keys once
if [ ! -S ~/.ssh/ssh_auth_sock ]; then
eval `ssh-agent`
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
Could be a little more elegant but its simple and readable. This solution:
AddKeysToAgent yes
is in your ssh config so keys will be automatically added upon useComments welcome :)
For Mysql, the jdbc Driver connection string is com.mysql.jdbc.Driver. Use the following code to get connected:-
class DBConnection {
private static Connection con = null;
private static String USERNAME = "your_mysql_username";
private static String PASSWORD = "your_mysql_password";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String URL = "jdbc:mysql://localhost:3306/database_name";
public static Connection getDatabaseConnection(){
Class.forName(DRIVER);
return con = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}
I had the same problem, but it solved when i put this on manifest: android:theme="@style/Theme.AppCompat.
<application
android:allowBackup="true"
android:icon="@drawable/icon"
android:label="@string/app_name_test"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat">
...
</application>
You can actually write to a named pipe using its name, btw.
Open a command shell as Administrator to get around the default "Access is denied" error:
echo Hello > \\.\pipe\PipeName
one way to accomplish this to have a server side application that waits for the data. The data can be sent using HttpRequest
objects in Java or you can write your own TCP/IP
data transfer utility. Data can be sent using JSON
format or any other format that you think is suitable. Also data can be encrypted before sending to server if it contains sensitive information. All Server application have to do is just wait for HttpRequests
to come in and parse the data and store it anywhere you want.
You can use strftime
to convert datetimes to any character format:
> t <- strftime(times, format="%H:%M:%S")
> t
[1] "02:06:49" "03:37:07" "00:22:45" "00:24:35" "03:09:57" "03:10:41"
[7] "05:05:57" "07:39:39" "06:47:56" "07:56:36"
But that doesn't help very much, since you want to plot your data. One workaround is to strip the date element from your times, and then to add an identical date to all of your times:
> xx <- as.POSIXct(t, format="%H:%M:%S")
> xx
[1] "2012-03-23 02:06:49 GMT" "2012-03-23 03:37:07 GMT"
[3] "2012-03-23 00:22:45 GMT" "2012-03-23 00:24:35 GMT"
[5] "2012-03-23 03:09:57 GMT" "2012-03-23 03:10:41 GMT"
[7] "2012-03-23 05:05:57 GMT" "2012-03-23 07:39:39 GMT"
[9] "2012-03-23 06:47:56 GMT" "2012-03-23 07:56:36 GMT"
Now you can use these datetime
objects in your plot:
plot(xx, rnorm(length(xx)), xlab="Time", ylab="Random value")
For more help, see ?DateTimeClasses
Will it work for you ?
class MyClass;
typedef std::pair<int,MyClass> MyPair;
class MyClass
{
private:
void foo() const{};
public:
static void Method(MyPair const& p)
{
//......
p.second.foo();
};
};
// ...
std::map<int, MyClass> Map;
//.....
std::for_each(Map.begin(), Map.end(), (&MyClass::Method));
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
This question has been asked and answered many times:
Read file from serial port using Java
Reading file from serial port in Java
Is there Java library or framework for accessing Serial ports?
Java Serial Communication on Windows
to reference a few.
Personally I recommend SerialPort from http://serialio.com - it's not free, but it's well worth the developer (no royalties) licensing fee for any commercial project. Sadly, it is no longer royalty free to deploy, and SerialIO.com seems to have remade themselves as a hardware seller; I had to search for information on SerialPort.
From personal experience, I strongly recommend against the Sun, IBM and RxTx implementations, all of which were unstable in 24/7 use. Refer to my answers on some of the aforementioned questions for details. To be perfectly fair, RxTx may have come a long way since I tried it, though the Sun and IBM implementations were essentially abandoned, even back then.
A newer free option that looks promising and may be worth trying is jSSC (Java Simple Serial Connector), as suggested by @Jodes comment.
I have created a function for date manipulation. you can add or subtract any number of days, hours, minutes.
function dateManipulation(date, days, hrs, mins, operator) {
date = new Date(date);
if (operator == "-") {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() - durationInMs);
} else {
var durationInMs = (((24 * days) * 60) + (hrs * 60) + mins) * 60000;
var newDate = new Date(date.getTime() + durationInMs);
}
return newDate;
}
Now, call this function by passing parameters. For example, here is a function call for getting date before 3 days from today.
var today = new Date();
var newDate = dateManipulation(today, 3, 0, 0, "-");
Twisted can help you with what you are doing, check out their documentation, there are plenty of examples. Also it is a mature product with a big developer/user community behind it.
Using lodash:
function csvToJson(csv) {
const content = csv.split('\n');
const header = content[0].split(',');
return _.tail(content).map((row) => {
return _.zipObject(header, row.split(','));
});
}
async
is used for binding to Observables and Promises, but it seems like you're binding to a regular object. You can just remove both async
keywords and it should probably work.
It's worked for me:
sudo systemctl unmask docker
sudo systemctl start docker
This can be achieved using command cgo.
In essence
'If the import of "C" is immediately preceded by a comment, that comment, called the preamble, is used as a header when compiling the C parts of the package. For example:'
source:https://golang.org/cmd/cgo/
// #include <stdio.h>
// #include <errno.h>
import "C"
The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:
;WITH sumCTE
AS
(
SELECT Rel.t2ID, SUM(Price) price
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
GROUP
BY Rel.t2ID
)
,maxCTE
AS
(
SELECT Rel.t2ID, Rel.t1ID,
ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM @t2 AS T2
JOIN sumCTE AS sumT1
ON sumT1.t2ID = t2.ID
JOIN maxCTE AS maxT1
ON maxT1.t2ID = t2.ID
JOIN @t1 AS T1
ON T1.ID = maxT1.t1ID
WHERE maxT1.PriceList = 1
SELECT CREATED FROM USER_OBJECTS WHERE OBJECT_NAME='<<YOUR TABLE NAME>>'
Update: Python 3.6 implements PEP 528: Change Windows console encoding to UTF-8: the default console on Windows will now accept all Unicode characters. Internally, it uses the same Unicode API as the win-unicode-console
package mentioned below. print(unicode_string)
should just work now.
I get a
UnicodeEncodeError: 'charmap' codec can't encode character...
error.
The error means that Unicode characters that you are trying to print can't be represented using the current (chcp
) console character encoding. The codepage is often 8-bit encoding such as cp437
that can represent only ~0x100 characters from ~1M Unicode characters:
>>> u"\N{EURO SIGN}".encode('cp437') Traceback (most recent call last): ... UnicodeEncodeError: 'charmap' codec can't encode character '\u20ac' in position 0: character maps to
I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?
Windows console does accept Unicode characters and it can even display them (BMP only) if the corresponding font is configured. WriteConsoleW()
API should be used as suggested in @Daira Hopwood's answer. It can be called transparently i.e., you don't need to and should not modify your scripts if you use win-unicode-console
package:
T:\> py -mpip install win-unicode-console
T:\> py -mrun your_script.py
See What's the deal with Python 3.4, Unicode, different languages and Windows?
Is there any way I can make Python automatically print a
?
instead of failing in this situation?
If it is enough to replace all unencodable characters with ?
in your case then you could set PYTHONIOENCODING
envvar:
T:\> set PYTHONIOENCODING=:replace
T:\> python3 -c "print(u'[\N{EURO SIGN}]')"
[?]
In Python 3.6+, the encoding specified by PYTHONIOENCODING
envvar is ignored for interactive console buffers unless PYTHONLEGACYWINDOWSIOENCODING
envvar is set to a non-empty string.
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
Try this one. It will sort numbers from other variables.
const obj = {
a: 1,
b: 2,
c: 3
};
const result = Object.keys(obj)
.reduce((acc, rec) => typeof obj[rec] === "number" ? acc.concat([obj[rec]]) : acc, [])
.reduce((acc, rec) => acc + rec)
You have some errors in your appcontext.xml:
Use *-2.5.xsd
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
Typos in tx:annotation-driven
and context:component-scan
(. instead of -)
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.mmycompany" />
I've had success forcing the view to be ordered using
SELECT TOP 9999999 ... ORDER BY something
Unfortunately using SELECT TOP 100 PERCENT
does not work due the issue here.
If you just want to check the type, you can use jQuery's .is() function,
Like in my case I used below,
if($("#id").is("select")) {
alert('Select');
else if($("#id").is("input")) {
alert("input");
}
Came across a similar problem, but if you do not necessarily want to return a view with view file, you can do this:
return $view->with(compact('myVar1', 'myVar2', ..... , 'myLastVar'));
There is various way to define a function. It is totally based upon your requirement. Below are the few styles :-
var person = new Object();
person.name = "Anand",
person.getName = function(){
return this.name ;
};
var person = {
name : "Anand",
getName : function (){
return this.name
}
}
function Person(name){
this.name = name
this.getName = function(){
return this.name
}
}
function Person(){};
Person.prototype.name = "Anand";
function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}
var person = new function(){
this.name = "Anand"
}
You can try it on console, if you have any confusion.
If you look at the chain of exceptions, the problem is
Caused by: org.hibernate.PropertyNotFoundException: Could not find a setter for property salt in class backend.Account
The problem is that the method Account.setSalt() works fine when you create an instance but not when you retrieve an instance from the database. This is because you don't want to create a new salt each time you load an Account.
To fix this, create a method setSalt(long) with visibility private and Hibernate will be able to set the value (just a note, I think it works with Private, but you might need to make it package or protected).
This is the solution for Node.js which is asynchronous.
using the async npm package.
(JavaScript) Synchronizing forEach Loop with callbacks inside
I know this thread has been dead some time, but here is another answer to the old ie8 png background issue.
You can do it in CSS by using IE's proprietary filtering system like this as well:
filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src='pathToYourPNG');
you will need to use a blank.gif for the 'first' image in your background declaration. This is simply to confuse ie8 and prevent it from using both the filter and the background you have set, and only use the filter. Other browsers support multiple background images and will understand the background declaration and not understand the filter, hence using the background only.
You may also need to play with the sizingMethod in the filter to get it to work the way you want.
In the W3 wiki page about structuring HTML5, it says:
<section>
: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.
And then displays an image that I cleaned up:
It's also important to know how to use the <article>
tag (from the same W3 link above):
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up.In our example,
<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:
<section id="main">
<article>
<!-- first blog post -->
</article>
<article>
<!-- second blog post -->
</article>
<article>
<!-- third blog post -->
</article>
</section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article>
<section id="introduction">
</section>
<section id="content">
</section>
<section id="summary">
</section>
</article>
I have head around lots of solutions and none of them works perfectly. I've used variation of solutions available in my project which is here as below. Please use this code inside class where you are initialising toolbar and drawer layout.
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);// show back button
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
//show hamburger
drawerFragment.mDrawerToggle.setDrawerIndicatorEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
drawerFragment.mDrawerToggle.syncState();
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
drawerFragment.mDrawerLayout.openDrawer(GravityCompat.START);
}
});
}
}
});
Okay guys another sleek option is
Application.Context.ApplicationInfo.NonLocalizedLabel
verified for hard coded android label on application element.
<application android:label="Big App"></application>
Reference: http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#nonLocalizedLabel
may be little late but useful for future. if you don't require to set custom properties of cell and only concern with header text and cell value then this code will help you
public class FileName
{
[DisplayName("File Name")]
public string FileName {get;set;}
[DisplayName("Value")]
public string Value {get;set;}
}
and then you can bind List as datasource as
private void BindGrid()
{
var filelist = GetFileListOnWebServer().ToList();
gvFilesOnServer.DataSource = filelist.ToArray();
}
for further information you can visit this page Bind List of Class objects as Datasource to DataGridView
hope this will help you.
If you have specified your own customer managed KMS key for S3 encryption you also need to provide the flag --server-side-encryption aws:kms
, for example:
aws s3api put-object --bucket bucket --key objectKey --body /path/to/file --server-side-encryption aws:kms
If you do not add the flag --server-side-encryption aws:kms
the cli displays an AccessDenied
error
If you already have your public key added to the GITHUB server there are other solutions that you can try.
In my case the GIT PUSH was failing from inside RUBYMINE but doing it from the Terminal window solved the problem.
For more solutions visit this page https://github.com/gitlabhq/gitlabhq/issues/4730
There is a combination of issues as pointed out in a few of the other answers.
I've provided both the example of .format as well as passing tuples to the argument specifier of %s. In both cases the indentation has been fixed so greater/less than checks are outside of when length matches. Also changed subsequent if statements to elif's so they only run if the prior same level statement was False.
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
if name1 == name2:
print ("The names are the same")
else:
print ("The names are different, but are the same length")
elif len(name1) > len(name2):
print ("{0} is longer than {1}".format(name1, name2))
elif len(name1) < len(name2):
print ("{0} is longer than {1}".format(name2, name1))
name1 = input("Enter name 1: ")
name2 = input("Enter name 2: ")
len(name1)
len(name2)
if len(name1) == len(name2):
if name1 == name2:
print ("The names are the same")
else:
print ("The names are different, but are the same length")
elif len(name1) > len(name2):
print ("%s is longer than %s" % (name1, name2))
elif len(name1) < len(name2):
print ("%s is longer than %s" % (name2, name1))
this version works for primitive types and for classes (short test-method included)
' TODO: change this to the name of your module
Private Const sMODULE As String = "MVbaUtils"
Public Function ExistsInCollection(oCollection As Collection, sKey As String) As Boolean
Const scSOURCE As String = "ExistsInCollection"
Dim lErrNumber As Long
Dim sErrDescription As String
lErrNumber = 0
sErrDescription = "unknown error occurred"
Err.Clear
On Error Resume Next
' note: just access the item - no need to assign it to a dummy value
' and this would not be so easy, because we would need different
' code depending on the type of object
' e.g.
' Dim vItem as Variant
' If VarType(oCollection.Item(sKey)) = vbObject Then
' Set vItem = oCollection.Item(sKey)
' Else
' vItem = oCollection.Item(sKey)
' End If
oCollection.Item sKey
lErrNumber = CLng(Err.Number)
sErrDescription = Err.Description
On Error GoTo 0
If lErrNumber = 5 Then ' 5 = not in collection
ExistsInCollection = False
ElseIf (lErrNumber = 0) Then
ExistsInCollection = True
Else
' Re-raise error
Err.Raise lErrNumber, mscMODULE & ":" & scSOURCE, sErrDescription
End If
End Function
Private Sub Test_ExistsInCollection()
Dim asTest As New Collection
Debug.Assert Not ExistsInCollection(asTest, "")
Debug.Assert Not ExistsInCollection(asTest, "xx")
asTest.Add "item1", "key1"
asTest.Add "item2", "key2"
asTest.Add New Collection, "key3"
asTest.Add Nothing, "key4"
Debug.Assert ExistsInCollection(asTest, "key1")
Debug.Assert ExistsInCollection(asTest, "key2")
Debug.Assert ExistsInCollection(asTest, "key3")
Debug.Assert ExistsInCollection(asTest, "key4")
Debug.Assert Not ExistsInCollection(asTest, "abcx")
Debug.Print "ExistsInCollection is okay"
End Sub
Pitching in with a websocket solution...
function ping(ip, isUp, isDown) {
var ws = new WebSocket("ws://" + ip);
ws.onerror = function(e){
isUp();
ws = null;
};
setTimeout(function() {
if(ws != null) {
ws.close();
ws = null;
isDown();
}
},2000);
}