Copy Always to output directory is set then try the following:
Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
String Root = Directory.GetCurrentDirectory();
These lines Worked for me.
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
//My Stuff
});
var logFile = File.ReadAllLines(LOG_PATH);
var logList = new List<string>(logFile);
Since logFile
is an array, you can pass it to the List<T>
constructor. This eliminates unnecessary overhead when iterating over the array, or using other IO classes.
Actual constructor implementation:
public List(IEnumerable<T> collection)
{
...
ICollection<T> c = collection as ICollection<T>;
if( c != null) {
int count = c.Count;
if (count == 0)
{
_items = _emptyArray;
}
else {
_items = new T[count];
c.CopyTo(_items, 0);
_size = count;
}
}
...
}
Based in the answer by WhoIsNinja:
This code will output both into the Console and into a Log string that can be saved into a file, either by appending lines to it or by overwriting it.
The default name for the log file is 'Log.txt' and is saved under the Application path.
public static class Logger
{
public static StringBuilder LogString = new StringBuilder();
public static void WriteLine(string str)
{
Console.WriteLine(str);
LogString.Append(str).Append(Environment.NewLine);
}
public static void Write(string str)
{
Console.Write(str);
LogString.Append(str);
}
public static void SaveLog(bool Append = false, string Path = "./Log.txt")
{
if (LogString != null && LogString.Length > 0)
{
if (Append)
{
using (StreamWriter file = System.IO.File.AppendText(Path))
{
file.Write(LogString.ToString());
file.Close();
file.Dispose();
}
}
else
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(Path))
{
file.Write(LogString.ToString());
file.Close();
file.Dispose();
}
}
}
}
}
Then you can use it like this:
Logger.WriteLine("==========================================================");
Logger.Write("Loading 'AttendPunch'".PadRight(35, '.'));
Logger.WriteLine("OK.");
Logger.SaveLog(true); //<- default 'false', 'true' Append the log to an existing file.
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
All of these are good answers but I think there's more to explain why None
is useful.
Imagine you collecting RSVPs to a wedding. You want to record whether each person will attend. If they are attending, you set person.attending = True
. If they are not attending you set person.attending = False
. If you have not received any RSVP, then person.attending = None
. That way you can distinguish between no information - None
- and a negative answer.
Here's my thread control function:
#!/bin/bash
# This function just checks jobs in background, don't do more things.
# if jobs number is lower than MAX, then return to get more jobs;
# if jobs number is greater or equal to MAX, then wait, until someone finished.
# Usage:
# thread_max 8
# thread_max 0 # wait, until all jobs completed
thread_max() {
local CHECK_INTERVAL="3s"
local CUR_THREADS=
local MAX=
[[ $1 ]] && MAX=$1 || return 127
# reset MAX value, 0 is easy to remember
[ $MAX -eq 0 ] && {
MAX=1
DEBUG "waiting for all tasks finish"
}
while true; do
CUR_THREADS=`jobs -p | wc -w`
# workaround about jobs bug. If don't execute it explicitily,
# CUR_THREADS will stick at 1, even no jobs running anymore.
jobs &>/dev/null
DEBUG "current thread amount: $CUR_THREADS"
if [ $CUR_THREADS -ge $MAX ]; then
sleep $CHECK_INTERVAL
else
return 0
fi
done
}
The key is the sql query, which you will set up as a string:
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
Note that there are a lot of ways to specify NOT. Another one that works just as well is:
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";
Here is a full example of how to use it:
$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);
while ($row = mysql_fetch_assoc($result) {
//do stuff
}
You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array
which means that $row['field1']
will give you the value for field1
on the current row, and $row['field2']
will give you the value for field2
.
Note that if the column(s) could have NULL
values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL
values:
$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";
var iframes = document.getElementsByTagName("iframe");
for(var i = 0, len = iframes.length; i<len; i++){
window.frames[i].onload = function(_i){
return function(){
iframes[_i].style.height = window.frames[_i].document.body.scrollHeight + "px";
}
}(i);
}
If you're on python and using a Conda Virtual Environment where your python script contains the shebang #!/usr/bin/env python the following works:
* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py 2>&1
Additionally, if you want to capture any outputs in your script (e.g. print, errors, etc) you can use the following:
* * * * * cd /home/user/project && /home/user/anaconda3/envs/envname/bin/python script.py >> /home/user/folder/script_name.log 2>&1
To add a Visual Studio GUI reference, you can find the DropDownStyle
options under the Properties of the selected ComboBox:
Which will automatically add the line mentioned in the first answer to the Form.Designer.cs InitializeComponent()
, like so:
this.comboBoxBatch.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
Assembly code is a human readable representation of machine code:
mov eax, 77
jmp anywhere
Machine code is pure hexadecimal code:
5F 3A E3 F1
I assume you mean object code as in an object file. This is a variant of machine code, with a difference that the jumps are sort of parameterized such that a linker can fill them in.
An assembler is used to convert assembly code into machine code (object code) A linker links several object (and library) files to generate an executable.
I have once written an assembler program in pure hex (no assembler available) luckily this was way back on the good old (ancient) 6502. But I'm glad there are assemblers for the pentium opcodes.
They appear to be populated by the tz database time zones found here.
Just finished up a js library for formatting numbers Numeral.js. It handles decimals, dollars, percentages and even time formatting.
cv::Mat m;
m.create(10, 10, CV_32FC3);
float *array = (float *)malloc( 3*sizeof(float)*10*10 );
cv::MatConstIterator_<cv::Vec3f> it = m.begin<cv::Vec3f>();
for (unsigned i = 0; it != m.end<cv::Vec3f>(); it++ ) {
for ( unsigned j = 0; j < 3; j++ ) {
*(array + i ) = (*it)[j];
i++;
}
}
Now you have a float array. In case of 8 bit, simply change float
to uchar
, Vec3f
to Vec3b
and CV_32FC3
to CV_8UC3
.
You can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
std::string str("a string");
std::cout << str.size() << std::endl;
Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.
I reccomend you to use the following tools for online base64 encoding/decoding:
Check the "Format as Data URL" option to format as a Data URL.
function getDetails(){
var data = [];
dBase.executeSql("PRAGMA table_info('table_name') ", [], function(rsp){
if(rsp.rows.length > 0){
for(var i=0; i<rsp.rows.length; i++){
var o = {
name: rsp.rows.item(i).name,
type: rsp.rows.item(i).type
}
data.push(o);
}
}
alert(rsp.rows.item(0).name);
},function(error){
alert(JSON.stringify(error));
});
}
Add the Picasso library in Dependency
dependencies {
...
implementation 'com.squareup.picasso:picasso:2.71828'
...
}
Sync The Project Create one imageview in Layout
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
</ImageView>
Add the Internet permission in Manifest file
<uses-permission android:name="android.permission.INTERNET" />
//Initialize ImageView
ImageView imageView = (ImageView) findViewById(R.id.imageView);
//Loading image from below url into imageView
Picasso.get()
.load("YOUR IMAGE URL HERE")
.into(imageView);
Without For loop:
Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))
newColumn.DefaultValue = "Your DropDownList value"
table.Columns.Add(newColumn)
C#:
System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);
Since Python 3.5, you can use os.scandir
.
The difference is that it returns file entries not names. On some OSes like windows, it means that you don't have to os.path.isdir/file
to know if it's a file or not, and that saves CPU time because stat
is already done when scanning dir in Windows:
example to list a directory and print files bigger than max_value
bytes:
for dentry in os.scandir("/path/to/dir"):
if dentry.stat().st_size > max_value:
print("{} is biiiig".format(dentry.name))
(read an extensive performance-based answer of mine here)
In Mac:
Kill process
Terminal: kill <pid>
Find pid:
Terminal: lsof -i:<port>
From Diego Pino answer
if we have single or we want first div
element we can use
$('div')[0].className
otherwise we need an id
of that element
Synchronize the data/object that you have saved into NSUserDefaults
-(void)saveCustomObject:(Player *)object
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[prefs setObject:myEncodedObject forKey:@"testing"];
[prefs synchronize];
}
Hope this will help you. Thanks
There are already so many good answers, but you can also use a simple CSS transform:
text-transform: capitalize;
div.c {
text-transform: capitalize;
}
_x000D_
<h2>text-transform: capitalize:</h2>
<div class="c">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
_x000D_
/usr/local/ssl/openssl.cnf
A path like this means the program has been compiled with either Cygwin or MSYS. If you must use this openssl
then you will need an interpreter that understands those paths, like Bash, which is provided by Cygwin or MSYS.
Another option would be to download or compile a Windows Native version of openssl
. Using that the program would instead require a path like
C:\Users\Steven\ssl\openssl.cnf
which would be better suited for the Command Prompt.
The two approaches offered thus far fail with large data sets as (amongst other memory issues) they create is.na(df)
, which will be an object the same size as df
.
Here are two approaches that are more memory and time efficient
An approach using Filter
Filter(function(x)!all(is.na(x)), df)
and an approach using data.table (for general time and memory efficiency)
library(data.table)
DT <- as.data.table(df)
DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]
big_data <- replicate(10, data.frame(rep(NA, 1e6), sample(c(1:8,NA),1e6,T), sample(250,1e6,T)),simplify=F)
bd <- do.call(data.frame,big_data)
names(bd) <- paste0('X',seq_len(30))
DT <- as.data.table(bd)
system.time({df1 <- bd[,colSums(is.na(bd) < nrow(bd))]})
# error -- can't allocate vector of size ...
system.time({df2 <- bd[, !apply(is.na(bd), 2, all)]})
# error -- can't allocate vector of size ...
system.time({df3 <- Filter(function(x)!all(is.na(x)), bd)})
## user system elapsed
## 0.26 0.03 0.29
system.time({DT1 <- DT[,which(unlist(lapply(DT, function(x)!all(is.na(x))))),with=F]})
## user system elapsed
## 0.14 0.03 0.18
axios.get(
'/app/export'
).then(response => {
const url = window.URL.createObjectURL(new Blob([response]));
const link = document.createElement('a');
link.href = url;
const fileName = `${+ new Date()}.csv`// whatever your file name .
link.setAttribute('download', fileName);
document.body.appendChild(link);
link.click();
link.remove();// you need to remove that elelment which is created before.
})
7 in a
Clearest and fastest way to do it.
You can also consider using a set
, but constructing that set from your list may take more time than faster membership testing will save. The only way to be certain is to benchmark well. (this also depends on what operations you require)
After Stop xampp, go to configure and change the port 3306 to 3308 of mysql and save. Now start the sql......Enjoy
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
I am wondering why you cannot put this in a batch file. Example:
cd D:\VBS\
WSCript Converter.vbs
Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.
Inspired by @skiwi, I solved it the following way:
public static <T> T toSingleton(Stream<T> stream) {
List<T> list = stream.limit(1).collect(Collectors.toList());
if (list.isEmpty()) {
return null;
} else {
return list.get(0);
}
}
And then:
User user = toSingleton(users.stream().filter(...).map(...));
In my case the problem was with the content of mail. When I changed content to simpler content without HTML, it worked. But after updating the phpmailer everything solved.
If you map to an array of Promises, you can then resolve them all to an array of numbers. See Promise.all.
You override __hash__
if you want special hash-semantics, and __cmp__
or __eq__
in order to make your class usable as a key. Objects who compare equal need to have the same hash value.
Python expects __hash__
to return an integer, returning Banana()
is not recommended :)
User defined classes have __hash__
by default that calls id(self)
, as you noted.
There is some extra tips from the documentation.:
Classes which inherit a
__hash__()
method from a parent class but change the meaning of__cmp__()
or__eq__()
such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting__hash__ = None
in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checkingisinstance(obj, collections.Hashable)
(unlike classes which define their own__hash__()
to explicitly raise TypeError).
As an even easier solution, you could just use:
$results = $objects.Name
Which should fill $results
with an array of all the 'Name' property values of the elements in $objects
.
This is a big gray area in cookie SOP (Same Origin Policy).
Theoretically, you can specify port number in the domain and the cookie will not be shared. In practice, this doesn't work with several browsers and you will run into other issues. So this is only feasible if your sites are not for general public and you can control what browsers to use.
The better approach is to get 2 domain names for the same IP and not relying on port numbers for cookies.
The Code Runner extension has a setting "Clear previous output", which is what I need 95% of the time.
File > Preferences > Settings > (search for "output") > Code-runner: Clear previous output
The remaining few times I will disable the setting and use the "Clear output" button (top right of the output pane) to selectively clear accumulated output.
This is in Visual Studio Code 1.33.1 with Code Runner 0.9.8.
(Setting the keybinding for Ctrl+k
did not work for me, presumably because some extension has defined "chords" beginning with Ctrl-k
. But "Clear previous output" was actually a better option for me.)
The problem that you are facing is : TypeError : str returned non-string (type NoneType)
Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error
You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return self.summary
but if the value you are returning in not of string type then you can do like this to return string value from your str function
*typeconverting the value to string that your str function returns
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return str(self.summary)
`
Checking the Options Over Write Database worked for me :)
I struggled to get this working. That's why I'll add a complete solution here:
My objective is to add this header to the SOAP envelope:
<soapenv:Header>
<urn:OTAuthentication>
<urn:AuthenticationToken>TOKEN</urn:AuthenticationToken>
</urn:OTAuthentication>
</soapenv:Header>
First create a SOAPHeaderHandler
class.
import java.util.Set;
import java.util.TreeSet;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFactory;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
public class SOAPHeaderHandler implements SOAPHandler<SOAPMessageContext> {
private final String authenticatedToken;
public SOAPHeaderHandler(String authenticatedToken) {
this.authenticatedToken = authenticatedToken;
}
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty =
(Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
try {
SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
SOAPFactory factory = SOAPFactory.newInstance();
String prefix = "urn";
String uri = "urn:api.ecm.opentext.com";
SOAPElement securityElem =
factory.createElement("OTAuthentication", prefix, uri);
SOAPElement tokenElem =
factory.createElement("AuthenticationToken", prefix, uri);
tokenElem.addTextNode(authenticatedToken);
securityElem.addChildElement(tokenElem);
SOAPHeader header = envelope.addHeader();
header.addChildElement(securityElem);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// inbound
}
return true;
}
public Set<QName> getHeaders() {
return new TreeSet();
}
public boolean handleFault(SOAPMessageContext context) {
return false;
}
public void close(MessageContext context) {
//
}
}
setHandlerChain
is required to configure the binding instance with the new chain."Authentication_Service authentication_Service = new Authentication_Service();
Authentication basicHttpBindingAuthentication = authentication_Service.getBasicHttpBindingAuthentication();
String authenticatedToken = "TOKEN";
List<Handler> handlerChain = ((BindingProvider)basicHttpBindingAuthentication).getBinding().getHandlerChain();
handlerChain.add(new SOAPHeaderHandler(authenticatedToken));
((BindingProvider)basicHttpBindingAuthentication).getBinding().setHandlerChain(handlerChain);
For Dot Net Core 3, Microsoft.Data.SqlClient should be used.
Instead of using -c, just pipe it to wc -l.
grep string * | wc -l
This will list each occurrence on a single line and then count the number of lines.
This will miss instances where the string occurs 2+ times on one line, though.
Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js
).
Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS
Thanks to AddRange
:
Example:
public class Person
{
private string Name;
private string FirstName;
public Person(string name, string firstname) => (Name, FirstName) = (name, firstname);
}
To add multiple Person
to a List<>
:
List<Person> listofPersons = new List<Person>();
listofPersons.AddRange(new List<Person>
{
new Person("John1", "Doe" ),
new Person("John2", "Doe" ),
new Person("John3", "Doe" ),
});
CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.
Adding and removing source files is just a matter of modifying the CMakeLists.txt
which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).
The following link explains CMake and Visual Studio specific behavior very well.
Maybe you're not doing it as root?
Try sudo nginx -s reload
, if it still doesn't work, you might want to try sudo pkill -HUP nginx
.
Response.Redirect()
will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
Server.Transfer()
does not change the address bar. You cannot hit back.
I use Server.Transfer()
when I don't want the user to see where I am going. Sometimes on a "loading" type page.
Otherwise I'll always use Response.Redirect()
.
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
The point for diamond operator is simply to reduce typing of code when declaring generic types. It doesn't have any effect on runtime whatsoever.
The only difference if you specify in Java 5 and 6,
List<String> list = new ArrayList();
is that you have to specify @SuppressWarnings("unchecked")
to the list
(otherwise you will get an unchecked cast warning). My understanding is that diamond operator is trying to make development easier. It's got nothing to do on runtime execution of generics at all.
Try this:
$(document).ready(function(){
var yourArray = [];
$("span.HOEnZb").find("div").each(function(){
if(($.trim($(this).text()).length>0)){
yourArray.push($(this).text());
}
});
});
If you want to exit a program because of a fatal error, use:
sys.exit("Your program caused a fatal error. ... description ...")
and import sys
in the header.
An iframe is still the best way to download cross-domain visual content. With AJAX you can certainly download the HTML from a web page and stick it in a div (as others have mentioned) however the bigger problem is security. With iframes you'll be able to load the cross domain content but won't be able to manipulate it since the content doesn't actually belong to you. On the other hand with AJAX you can certainly manipulate any content you are able to download but the other domain's server needs to be setup in such a way that will allow you to download it to begin with. A lot of times you won't have access to the other domain's configuration and even if you do, unless you do that kind of configuration all the time, it can be a headache. In which case the iframe can be the MUCH easier alternative.
As others have mentioned you can also use the embed tag and the object tag but that's not necessarily more advanced or newer than the iframe.
HTML5 has gone more in the direction of adopting web APIs to get information from cross domains. Usually web APIs just return data though and not HTML.
I find such a function named is_sequence in tensorflow.
def is_sequence(seq):
"""Returns a true if its input is a collections.Sequence (except strings).
Args:
seq: an input sequence.
Returns:
True if the sequence is a not a string and is a collections.Sequence.
"""
return (isinstance(seq, collections.Sequence)
and not isinstance(seq, six.string_types))
And I have verified that it meets your needs.
I found good answers here, but also found a simpler way.
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)
You can style the link as a button using bootstrap
, which is still pure javascript, except for styling.
Combining the button and the download link also reduces code, as fewer of those ugly getElementById
calls are needed.
This example needs only one button click to create the text-blob and download it:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
If you are trying to maintain the same aspect ratio, then wouldn't you resize by some percentage of the original size?
For example, half the original size
half = 0.5
out = im.resize( [int(half * s) for s in im.size] )
Use this,
DECLARE @start_date DATETIME = '2015-02-12 00:00:00.000';
DECLARE @end_date DATETIME = '2015-02-13 00:00:00.000';
WITH AllDays
AS ( SELECT @start_date AS [Date], 1 AS [level]
UNION ALL
SELECT DATEADD(DAY, 1, [Date]), [level] + 1
FROM AllDays
WHERE [Date] < @end_date )
SELECT [Date], [level]
FROM AllDays OPTION (MAXRECURSION 0)
pass the @start_date and @end_date as SP parameters.
Result:
Date level
----------------------- -----------
2015-02-12 00:00:00.000 1
2015-02-13 00:00:00.000 2
(2 row(s) affected)
Use the %r
for debugging, since it displays the "raw" data of the variable,
but the others are used for displaying to users.
That's how %r
formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n
used to display to users doesn't work. %r
shows the representation if the raw data of the variable.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months
Output:
Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
Check this example from Learn Python the Hard Way.
I ran into this issue too. It confused me until I realized what was wrong:
You have this:
include /etc/nginx/mime.types;
default_type application/octet-stream;
You want this:
default_type application/octet-stream;
include /etc/nginx/mime.types;
there appears to either be a bug in nginx or a deficiency in the docs (this could be the intended behavior, but it is odd)
as per 2018, the targetSdkVersion can be set up in your app/build.gradle
the following way:
android {
compileSdkVersion 26
buildToolsVersion '27.0.3'
defaultConfig {
...
targetSdkVersion 26
}
...
}
if you choose 26 as SDK target, be sure to follow https://developer.android.com/about/versions/oreo/android-8.0-migration
You can't launch arbitrary commands, but if your users are willing to go through some extra setup, you can use custom protocols.
E.g. you have the users set things up so that some-app://
links start "SomeApp", and then in my-awesome-extension
you open a tab pointing to some-app://some-data-the-app-wants
, and you're good to go!
I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).
One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).
EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
if (isset($_POST['submit'])) {
for($i = 0; $i<= 3; $i++){
if(isset($_POST['books'][$i]))
$book .= ' '.$_POST['books'][$i];
}
1 - disable fork
option in /etc/mongodb.conf
if enabled
2 - Repair your database
mongod --repair --dbpath DBPATH
3 - kill current mongod process
Find mongo processes
ps -ef | grep mongo
you'll get mongod PID
mongodb PID 1 0 06:26 ? 00:00:00 /usr/bin/mongod --config /etc/mongodb.conf
Stop current mongod process
kill -9 PID
4 - start mongoDB service
service mongodb start
I wouldnt use this attribute as most browsers ignore it as CMS points out.
By all means use client side validation but only in conjunction with server side. Any client side validation can be got round.
Slightly off topic but some people check the content type to validate the uploaded file. You need to be careful about this as an attacker can easily change it and upload a php file for example. See the example at: http://www.scanit.be/uploads/php-file-upload.pdf
Try this Code
<select name="forma" onchange="location = this.options[this.selectedIndex].value;">
<option value="Home.php">Home</option>
<option value="Contact.php">Contact</option>
<option value="Sitemap.php">Sitemap</option>
</select>
I don't think it is possible to share a database link between more than one user but not all. They are either private (for one user only) or public (for all users).
A good way around this is to create a view in SCHEMA_B that exposes the table you want to access through the database link. This will also give you good control over who is allowed to select from the database link, as you can control the access to the view.
Do like this:
create database link db_link... as before;
create view mytable_view as select * from mytable@db_link;
grant select on mytable_view to myuser;
To kill from the application, you can do:
android.os.Process.killProcess(android.os.Process.myPid());
This works with express for me:
app.get("*",(req,res,next) => {
if (req.headers["x-forwarded-proto"]) {
res.redirect("https://" + req.headers.host + req.url)
}
if (!res.headersSent) {
next()
}
})
Put this before all HTTP handlers.
for i in xorg-x11-fonts*; do
if [ -f "$i" ]; then printf "BLAH"; fi
done
This will work with multiple files and with white space in file names.
Did you try this:
#define stringify( name ) # name
enum enMyErrorValue
{
ERROR_INVALIDINPUT = 0,
ERROR_NULLINPUT,
ERROR_INPUTTOOMUCH,
ERROR_IAMBUSY
};
const char* enMyErrorValueNames[] =
{
stringify( ERROR_INVALIDINPUT ),
stringify( ERROR_NULLINPUT ),
stringify( ERROR_INPUTTOOMUCH ),
stringify( ERROR_IAMBUSY )
};
void vPrintError( enMyErrorValue enError )
{
cout << enMyErrorValueNames[ enError ] << endl;
}
int main()
{
vPrintError((enMyErrorValue)1);
}
The stringify()
macro can be used to turn any text in your code into a string, but only the exact text between the parentheses. There are no variable dereferencing or macro substitutions or any other sort of thing done.
If you have the web view figured out but your images are still out of scale, the best solution I found (here) was simply prepending the document with:
<style>img{display: inline; height: auto; max-width: 100%;}</style>
As a result all images are scaled to match the web view width.
You should already have all needed variables in /etc/profile.d/oracle.sh
. Make sure you source it:
$ source /etc/profile.d/oracle.sh
The file's content looks like:
ORACLE_HOME=/usr/lib/oracle/11.2/client64
PATH=$ORACLE_HOME/bin:$PATH
LD_LIBRARY_PATH=$ORACLE_HOME/lib
export ORACLE_HOME
export LD_LIBRARY_PATH
export PATH
If you don't have it, create it and source it.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
int n,k=0;
char *ch1;
ch1=(char*)malloc((j-i+1)*1);
n=j-i+1;
while(k<n)
{
ch1[k]=ch[i];
i++;k++;
}
return (char *)ch1;
}
int main()
{
int i=0,j=2;
char s[]="String";
char *test;
test=substring(i,j,s);
printf("%s",test);
free(test); //free the test
return 0;
}
This will compile fine without any warning
#include stdlib.h
test=substring(i,j,s)
; m
as it is unused char substring(int i,int j,char *ch)
or define it before main awk '{$1=$2=$3="";$0=$0;$1=$1}1'
Input
1 2 3 4 5 6 7
Output
4 5 6 7
If you want use margin, remove the class on every button and use :last-child CSS selector.
Html :
<div class="btn-toolbar text-center well">
<button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span> ADD PACKET
</button>
<button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2">
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span> EDIT CUSTOMER
</button>
<button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2">
<span class="glyphicon glyphicon-time" aria-hidden="true"></span> HISTORY
</button>
<button type="button" class="btn btn-primary btn-color btn-bg-color btn-sm col-xs-2">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> DELETE CUSTOMER
</button>
</div>
Css :
.btn-toolbar .btn{
margin-right: 5px;
}
.btn-toolbar .btn:last-child{
margin-right: 0;
}
If all the cases have the same length you can use
switch (mystring.SubString(0,Math.Min(len, mystring.Length)))
.
Another option is to have a function that will return categoryId based on the string and switch on the id.
If Your issue is when you touch/tap on android and whole div covered by blue transparent color! Then you need to just change the
CURSOR : POINTER; to CURSOR : DEFAULT;
use mediaQuery to hide in mobile phone/Tablet.
This works for me.
In Swift 4, as String
is a collection of Character
, you need to use map
let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>
Since the question is being tagged for mysql
, I have the following implementation that works for me and I hope similar alternatives would be there for other RDBMS's. Here's the sql:
select YEAR(now()) - YEAR(dob) - ( DAYOFYEAR(now()) < DAYOFYEAR(dob) ) as age
from table
where ...
Some advantages to the second option:
You can use this
inside onclick
to reference the anchor itself (doing the same in option 1 will give you window
instead).
You can set the href
to a non-JS compatible URL to support older browsers (or those that have JS disabled); browsers that support JavaScript will execute the function instead (to stay on the page you have to use onclick="return someFunction();"
and return false
from inside the function or onclick="return someFunction(); return false;"
to prevent default action).
I've seen weird stuff happen when using href="javascript:someFunction()"
and the function returns a value; the whole page would get replaced by just that value.
Pitfalls
Inline code:
Runs in document
scope as opposed to code defined inside <script>
tags which runs in window
scope; therefore, symbols may be resolved based on an element's name
or id
attribute, causing the unintended effect of attempting to treat an element as a function.
Is harder to reuse; delicate copy-paste is required to move it from one project to another.
Adds weight to your pages, whereas external code files can be cached by the browser.
If you want to implement the same for Android in Xamarin, here is a translation to C#
I chose to name the attribute "ScrollEnabled". Because iOS just uses the excat same naming. So, you have equal naming across both platforms, makes it easier for developers.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Support.V4.View;
using Android.Util;
namespace YourNameSpace.ViewPackage {
// Need to disable swiping for ViewPager, if user performs Pre DSA and the dsa is not completed yet
// http://stackoverflow.com/questions/9650265/how-do-disable-paging-by-swiping-with-finger-in-viewpager-but-still-be-able-to-s
public class CustomViewPager: ViewPager {
public bool ScrollEnabled;
public CustomViewPager(Context context, IAttributeSet attrs) : base(context, attrs) {
this.ScrollEnabled = true;
}
public override bool OnTouchEvent(MotionEvent e) {
if (this.ScrollEnabled) {
return base.OnTouchEvent(e);
}
return false;
}
public override bool OnInterceptTouchEvent(MotionEvent e) {
if (this.ScrollEnabled) {
return base.OnInterceptTouchEvent(e);
}
return false;
}
// For ViewPager inside another ViewPager
public override bool CanScrollHorizontally(int direction) {
return this.ScrollEnabled && base.CanScrollHorizontally(direction);
}
// Some devices like the Galaxy Tab 4 10' show swipe buttons where most devices never show them
// So, you could still swipe through the ViewPager with your keyboard keys
public override bool ExecuteKeyEvent(KeyEvent evt) {
return this.ScrollEnabled ? base.ExecuteKeyEvent(evt) : false;
}
}
}
In .axml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<YourNameSpace.ViewPackage.CustomViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:layout_alignParentTop="true" />
</LinearLayout>
If you want to cut being careful to don't split words you can do the following
function ellipse($str,$n_chars,$crop_str=' [...]')
{
$buff=strip_tags($str);
if(strlen($buff) > $n_chars)
{
$cut_index=strpos($buff,' ',$n_chars);
$buff=substr($buff,0,($cut_index===false? $n_chars: $cut_index+1)).$crop_str;
}
return $buff;
}
if $str is shorter than $n_chars returns it untouched.
If $str is equal to $n_chars returns it as is as well.
if $str is longer than $n_chars then it looks for the next space to cut or (if no more spaces till the end) $str gets cut rudely instead at $n_chars.
NOTE: be aware that this method will remove all tags in case of HTML.
action attribute in <form method="post" action="action=""">
should be just action=""
To set the credentials for the entire day that is 24 hours.
git config --global credential.helper 'cache --timeout 86400'
Else for 1 hour replace the 86400 secs to 3600.
OR
all configuration options for the 'cache' authentication helper:
git help credential-cache
ASCX files are server-side Web application framework designed for Web development to produce dynamic Web pages.They like DLL codes but you can use there's TAGS You can write them once and use them in any places in your ASP pages.If you have a file named "Controll.ascx" then its code will named "Controll.ascx.cs". You can embed it in a ASP page to use it:
To calculate gradients, the machine learning community uses Autograd:
To install:
pip install autograd
Here is an example:
import autograd.numpy as np
from autograd import grad
def fct(x):
y = x**2+1
return y
grad_fct = grad(fct)
print(grad_fct(1.0))
It can also compute gradients of complex functions, e.g. multivariate functions.
You can write directive:
@Directive({
selector: '[clickOut]'
})
export class ClickOutDirective implements AfterViewInit {
@Input() clickOut: boolean;
@Output() clickOutEvent: EventEmitter<any> = new EventEmitter<any>();
@HostListener('document:mousedown', ['$event']) onMouseDown(event: MouseEvent) {
if (this.clickOut &&
!event.path.includes(this._element.nativeElement))
{
this.clickOutEvent.emit();
}
}
}
In your component:
@Component({
selector: 'app-root',
template: `
<h1 *ngIf="isVisible"
[clickOut]="true"
(clickOutEvent)="onToggle()"
>{{title}}</h1>
`,
styleUrls: ['./app.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
title = 'app works!';
isVisible = false;
onToggle() {
this.isVisible = !this.isVisible;
}
}
This directive emit event when html element is containing in DOM and when [clickOut] input property is 'true'. It listen mousedown event to handle event before element will be removed from DOM.
And one note: firefox doesn't contain property 'path' on event you can use function to create path:
const getEventPath = (event: Event): HTMLElement[] => {
if (event['path']) {
return event['path'];
}
if (event['composedPath']) {
return event['composedPath']();
}
const path = [];
let node = <HTMLElement>event.target;
do {
path.push(node);
} while (node = node.parentElement);
return path;
};
So you should change event handler on the directive: event.path should be replaced getEventPath(event)
This module can help. https://www.npmjs.com/package/ngx-clickout It contains the same logic but also handle esc event on source html element.
if you are adding multiple items to the list use this:
mAdapter.notifyItemRangeInserted(startPosition, itemcount);
This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount
existing item in the dataset still considered up to date.
Accepted answer is correct, but I like to define this little utility in most projects I build.
var types = {
'get': function(prop) {
return Object.prototype.toString.call(prop);
},
'null': '[object Null]',
'object': '[object Object]',
'array': '[object Array]',
'string': '[object String]',
'boolean': '[object Boolean]',
'number': '[object Number]',
'date': '[object Date]',
}
Used like this:
if(types.get(prop) == types.number) {
}
If you're using angular you can even have it cleanly injected:
angular.constant('types', types);
The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:
try:
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
print 'Houston, we have a problem.'
raise
Which gives the following output that includes the offending statement and line number:
Houston, we have a problem.
Traceback (most recent call last):
File "/tmp/poop.py", line 2, in <module>
assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie
Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):
import logging
try:
assert False == True
except AssertionError:
logging.error("Nothing is real but I can't quit...", exc_info=True)
You can do that without an I/O redirection:
sed -i 's/$/\n/' filename
You can also use this command to append a newline to a list of files:
find dir -name filepattern | xargs sed -i 's/$/\n/' filename
For echo
, some shells implement it as a shell builtin command. It might not accept the -e
option. If you still want to use echo
, try to find where the echo
binary file is, using which echo
. In most cases, it is located in /bin/echo
, so you can use /bin/echo -e "\n"
to echo a new line.
How about:
git branch -D email
git checkout staging
git checkout -b email
git push origin email --force-with-lease
I think the following will achieve what you are after
function func( orig, target ) {
var i = orig.length, j = 0, total = 0, change, newVals = [], next, factor1, factor2, len = orig.length, marginOfErrors = [];
// map original values to new array
while( i-- ) {
total += newVals[i] = Math.round( orig[i] );
}
change = total < target ? 1 : -1;
while( total !== target ) {
// Iterate through values and select the one that once changed will introduce
// the least margin of error in terms of itself. e.g. Incrementing 10 by 1
// would mean an error of 10% in relation to the value itself.
for( i = 0; i < len; i++ ) {
next = i === len - 1 ? 0 : i + 1;
factor2 = errorFactor( orig[next], newVals[next] + change );
factor1 = errorFactor( orig[i], newVals[i] + change );
if( factor1 > factor2 ) {
j = next;
}
}
newVals[j] += change;
total += change;
}
for( i = 0; i < len; i++ ) { marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i]; }
// Math.round() causes some problems as it is difficult to know at the beginning
// whether numbers should have been rounded up or down to reduce total margin of error.
// This section of code increments and decrements values by 1 to find the number
// combination with least margin of error.
for( i = 0; i < len; i++ ) {
for( j = 0; j < len; j++ ) {
if( j === i ) continue;
var roundUpFactor = errorFactor( orig[i], newVals[i] + 1) + errorFactor( orig[j], newVals[j] - 1 );
var roundDownFactor = errorFactor( orig[i], newVals[i] - 1) + errorFactor( orig[j], newVals[j] + 1 );
var sumMargin = marginOfErrors[i] + marginOfErrors[j];
if( roundUpFactor < sumMargin) {
newVals[i] = newVals[i] + 1;
newVals[j] = newVals[j] - 1;
marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i];
marginOfErrors[j] = newVals[j] && Math.abs( orig[j] - newVals[j] ) / orig[j];
}
if( roundDownFactor < sumMargin ) {
newVals[i] = newVals[i] - 1;
newVals[j] = newVals[j] + 1;
marginOfErrors[i] = newVals[i] && Math.abs( orig[i] - newVals[i] ) / orig[i];
marginOfErrors[j] = newVals[j] && Math.abs( orig[j] - newVals[j] ) / orig[j];
}
}
}
function errorFactor( oldNum, newNum ) {
return Math.abs( oldNum - newNum ) / oldNum;
}
return newVals;
}
func([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100); // => [16, 16, 17, 17, 17, 17]
func([33.333, 33.333, 33.333], 100); // => [34, 33, 33]
func([33.3, 33.3, 33.3, 0.1], 100); // => [34, 33, 33, 0]
func([13.25, 47.25, 11.25, 28.25], 100 ); // => [13, 48, 11, 28]
func( [25.5, 25.5, 25.5, 23.5], 100 ); // => [25, 25, 26, 24]
One last thing, I ran the function using the numbers originally given in the question to compare to the desired output
func([13.626332, 47.989636, 9.596008, 28.788024], 100); // => [48, 29, 13, 10]
This was different to what the question wanted => [ 48, 29, 14, 9]. I couldn't understand this until I looked at the total margin of error
-------------------------------------------------
| original | question | % diff | mine | % diff |
-------------------------------------------------
| 13.626332 | 14 | 2.74% | 13 | 4.5% |
| 47.989636 | 48 | 0.02% | 48 | 0.02% |
| 9.596008 | 9 | 6.2% | 10 | 4.2% |
| 28.788024 | 29 | 0.7% | 29 | 0.7% |
-------------------------------------------------
| Totals | 100 | 9.66% | 100 | 9.43% |
-------------------------------------------------
Essentially, the result from my function actually introduces the least amount of error.
Fiddle here
This in an example that can be used for example to feed a database key, I sometimes use instead of using AUTOINCREMENT options.
import datetime
dt = datetime.datetime.now()
seq = int(dt.strftime("%Y%m%d%H%M%S"))
You might also, like me, have installed php-cgi prior to installing Apache and when doing so it doesn't set up Apache properly to run PHP, removing PHP entirely and reinstalling seemed to fix my problem.
there should has a concurrent implemention of List interface supporting such operation.
try java.util.concurrent.CopyOnWriteArrayList.class
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
If you are using WAMP...
you should add or uncomment the property always_populate_raw_post_data
in php.ini
and set its value to -1
. In my case php.ini
is located in:
C:\wamp64\bin\php\php5.6.25\php.ini
..but if you are still getting the warning (as I was)
You should also set
always_populate_raw_post_data = -1
inphpForApache.ini
:
C:\wamp64\bin\php\php5.6.25\phpForApache.ini
If you can't find this file, open a browser window and go to:
http://localhost/?phpinfo=1
and look for the value of Loaded Configuration File key. In my case the
php.ini
used by WAMP is located in:
C:\wamp64\bin\apache\apache2.4.23\bin\php.ini
(symlink to C:\wamp64\bin\php\php5.6.25\phpForApache.ini)
Finally restart WAMP (or click restart all services)
var newList = list.OrderBy(x => x.Product.Name).Reverse()
This should do the job.
How about
sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub
Try this
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Range("A" & i & ":" & "Z" & i)
Else
Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
IF you want to delete the entire row then use this code
Option Explicit
Sub Sample()
Dim i As Long
Dim DelRange As Range
On Error GoTo Whoa
Application.ScreenUpdating = False
For i = 1 To 50
If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
If DelRange Is Nothing Then
Set DelRange = Rows(i)
Else
Set DelRange = Union(DelRange, Rows(i))
End If
End If
Next i
If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub
If you want to solve this without using Ajax, use the FileReader()
Web API.
Example implementation:
.csv
filefunction readSingleFile(e) {_x000D_
var file = e.target.files[0];_x000D_
if (!file) {_x000D_
return;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
reader.onload = function(e) {_x000D_
var contents = e.target.result;_x000D_
displayContents(contents);_x000D_
displayParsed(contents);_x000D_
};_x000D_
reader.readAsText(file);_x000D_
}_x000D_
_x000D_
function displayContents(contents) {_x000D_
var element = document.getElementById('file-content');_x000D_
element.textContent = contents;_x000D_
}_x000D_
_x000D_
function displayParsed(contents) {_x000D_
const element = document.getElementById('file-parsed');_x000D_
const json = contents.split(',');_x000D_
element.textContent = JSON.stringify(json);_x000D_
}_x000D_
_x000D_
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
_x000D_
<input type="file" id="file-input" />_x000D_
_x000D_
<h3>Raw contents of the file:</h3>_x000D_
<pre id="file-content">No data yet.</pre>_x000D_
_x000D_
<h3>Parsed file contents:</h3>_x000D_
<pre id="file-parsed">No data yet.</pre>
_x000D_
As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer
(or DirectByteBuffer
) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer
before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer
, you can delete the file. However, make sure you never use the ByteBuffer
again after cleaning it, or the JVM will crash.
Awesome work by @BjarkeCK. I made some modifications to his work, to use it as method in jquery:
$.fn.dropZone = function() {
var buttonId = "clickHere";
var mouseOverClass = "mouse-over";
var dropZone = this[0];
var $dropZone = $(dropZone);
var ooleft = $dropZone.offset().left;
var ooright = $dropZone.outerWidth() + ooleft;
var ootop = $dropZone.offset().top;
var oobottom = $dropZone.outerHeight() + ootop;
var inputFile = $dropZone.find("input[type='file']");
dropZone.addEventListener("dragleave", function() {
this.classList.remove(mouseOverClass);
});
dropZone.addEventListener("dragover", function(e) {
console.dir(e);
e.preventDefault();
e.stopPropagation();
this.classList.add(mouseOverClass);
var x = e.pageX;
var y = e.pageY;
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {
inputFile.offset({
top: y - 15,
left: x - 100
});
} else {
inputFile.offset({
top: -400,
left: -400
});
}
}, true);
dropZone.addEventListener("drop", function(e) {
this.classList.remove(mouseOverClass);
}, true);
}
$('#drop-zone').dropZone();
As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.
As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.
using System.Linq;
list.Where(x=> x.Name == nameToExtract);
Edit: misread question (now all matches)
This has already been answered in detail on SO. Check out this thread, It should answer all your questions: Executing a subprocess fails
I've tried it myself with this code:
batchtest.py
from subprocess import Popen
p = Popen("batch.bat", cwd=r"C:\Path\to\batchfolder")
stdout, stderr = p.communicate()
batch.bat
echo Hello World!
pause
I've got the batchtest.py example from the aforementioned thread.
Using the java.time
framework built into Java 8 and later.
import java.time.LocalDate;
import java.time.ZoneId;
int year = 2011;
int month = 10;
int day = 1;
int date = LocalDate.of(year, month, day);
date.atStartOfDay(ZoneId.of("UTC")).toEpochSecond; # Long = 1317427200
For the SQL Server Owner, you should be able to use:
select suser_sname(owner_sid) as 'Owner', state_desc, *
from sys.databases
For a list of SQL Users:
select * from master.sys.server_principals
Ref. SQL Server Tip: How to find the owner of a database through T-SQL
If you are having this problem in 2019, go to your 000-default.conf
file, by typing this subl /etc/apache2/sites-enabled/000-default.conf
(in your terminal to open the file in sublime editor)
When the file loads, locate "The ServerName directive sets the request scheme" and place this "Include /etc/phpmyadmin/apache.conf" on top .
Then restart your apache with the command...service apache2 restart
That will certainly fix the issue. Hope it helps!
The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.
Construct a POJO.java class and create "constructor, getter & setter methods"
class POJO{
public POJO(Drawable proImagePath) {
setProductImagePath(proImagePath);
}
public Drawable getProductImagePath() {
return productImagePath;
}
public void setProductImagePath(Drawable productImagePath) {
this.productImagePath = productImagePath;
}
}
Then setup the adapters through image drawable resources to CustomAdapter.java
class CustomAdapter extends ArrayAdapter<POJO>{
private ArrayList<POJO> cartList = new ArrayList<POJO>();
public MyCartAdapter(Context context, int resource) {
super(context, resource);
}
public MyCartAdapter(Context context, ArrayList<POJO> cartList) {
super(context, 0, cartList);
this.context = context;
this.cartList = cartList;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
*Here you can setup your layout and references.
**/
ImageView productImage = (ImageView) rootView.findViewById(R.id.cart_pro_image);
productImage.setImageDrawable(POJO.getProductImagePath());
}
}
Then pass the references through ActivityClass.java
public class MyCartActivity extends AppCompatActivity{
POJO pojo;
CustomAdapter customAdapter;
ArrayList<POJO> cartList = new ArrayList<POJO>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
customAdapter = new CustomAdapter(this, cartList);
pojo = new POJO(getResources().getDrawable(R.drawable.help_green));
}
}
I think you want a pipelined table function.
Something like this:
CREATE OR REPLACE PACKAGE test AS
TYPE measure_record IS RECORD(
l4_id VARCHAR2(50),
l6_id VARCHAR2(50),
l8_id VARCHAR2(50),
year NUMBER,
period NUMBER,
VALUE NUMBER);
TYPE measure_table IS TABLE OF measure_record;
FUNCTION get_ups(foo NUMBER)
RETURN measure_table
PIPELINED;
END;
CREATE OR REPLACE PACKAGE BODY test AS
FUNCTION get_ups(foo number)
RETURN measure_table
PIPELINED IS
rec measure_record;
BEGIN
SELECT 'foo', 'bar', 'baz', 2010, 5, 13
INTO rec
FROM DUAL;
-- you would usually have a cursor and a loop here
PIPE ROW (rec);
RETURN;
END get_ups;
END;
For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.
Usage:
SELECT *
FROM table(test.get_ups(0));
L4_ID L6_ID L8_ID YEAR PERIOD VALUE
----- ----- ----- ---------- ---------- ----------
foo bar baz 2010 5 13
1 row selected.
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
Do you mean like this?
var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);
To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll()
to accomplish this:
HTML
<div class="abc"></div>
<div class="abc"></div>
JS
var abcElements = document.querySelectorAll('.abc');
// Set their ids
for (var i = 0; i < abcElements.length; i++)
abcElements[i].id = 'abc-' + i;
This will assign the ID 'abc-<index number>'
to each element. So it would come out like this:
<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>
To create an element and assign an id
we can use document.createElement()
and then appendChild()
.
var div = document.createElement('div');
div.id = 'hello1';
var body = document.querySelector('body');
body.appendChild(div);
Update
You can set the id
on your element like this if your script is in your HTML file.
<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">
<script type="text/javascript">
var s = document.getElementsByClassName('assign-me')[0];
s.id = btoa({{str(produit["avt"]["fto"])}});
</script>
Your requirements still aren't 100% clear though.
Use get(0)
instead of html()
. In other words, replace
doc.fromHTML($('#htmlTableId').html(), 15, 15, {
'width': 170,'elementHandlers': specialElementHandlers
});
with
doc.fromHTML($('#htmlTableId').get(0), 15, 15, {
'width': 170,'elementHandlers': specialElementHandlers
});
You can use a background image to accomplish this;
From MDN - Background Size: Contain:
This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.
CSS:
#im {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-image: url("path/to/img");
background-repeat: no-repeat;
background-size: contain;
}
HTML:
<div id="wrapper">
<div id="im">
</div>
</div>
To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:
You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".
If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old
git branch
to see what branch origin is currently on. To change it to another branch, you have to usegit symbolic-ref HEAD refs/heads/another-branch
.
If java command is working and getting problem with javac. then first check in jdk's bin directory javac.exe file is there or not.
If javac.exe file is exist then set JAVA_HOME
as System variable.
What's the problem with using for
loop inside, just like outside?
for (int j = i + 1; j < list.size(); ++j) {
...
}
In general, since Java 5, I used iterators only once or twice.
Do it using JS. Grab the class of the error message, and change it's content for whereever it appears.
var myClasses = document.getElementsByClassName("wpcf7-not-valid-tip");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "Bitte füllen Sie das Pflichtfeld aus.";
}
npm install --save bootstrap
and add this import statement into your index.js file
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
or You could simply add CDN in your index.html file.
I wouldn't use HttpListener or something like that, in that way you'll come across so many issues.
Most importantly it'll be a huge pain to support:
What you need to do is:
I wrote 2 different HTTP proxies in .NET with different requirements and I can tell you that this is the best way to do it.
Mentalis doing this, but their code is "delegate spaghetti", worse than GoTo :)
Python's eager in its evaluation, so eval(input(...))
(Python 3) will evaluate the user's input as soon as it hits the eval
, regardless of what you do with the data afterwards. Therefore, this is not safe, especially when you eval
user input.
Use ast.literal_eval
.
As an example, entering this at the prompt could be very bad for you:
__import__('os').system('rm -rf /a-path-you-really-care-about')
Don't use device-width/height anymore.
device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features
Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.
for issue the remote server returned an unexpected response: (413) Request Entity Too Large on WCF with Resful
please see my explain configuration
</client>
<serviceHostingEnvironment multipleSiteBindingsEnabled="false" aspNetCompatibilityEnabled="true"/>
<bindings>
<!-- this for restfull service -->
<webHttpBinding>
<binding name="RestfullwebHttpBinding"
maxBufferPoolSize="2147483647"
maxReceivedMessageSize="2147483647"
maxBufferSize="2147483647" transferMode="Streamed">
<readerQuotas
maxDepth="2147483647"
maxStringContentLength="2147483647"
maxArrayLength="2147483647"
maxBytesPerRead="2147483647" />
</binding>
</webHttpBinding>
<!-- end -->
<!-- this for Soap v.2 -->
<wsHttpBinding>
<binding name="wsBinding1" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
<!--UsernameToken over Transport Security-->
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" establishSecurityContext="true"/>
</security>
</binding>
</wsHttpBinding>
<!-- this for restfull service -->
<!-- this for Soap v.1 -->
<basicHttpBinding>
<binding name="basicBinding1" maxReceivedMessageSize="2147483647" closeTimeout="00:10:00" openTimeout="00:10:00" receiveTimeout="00:10:00" sendTimeout="00:10:00" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="2147483647" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false" transferMode="Streamed">
<readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxNameTableCharCount="2147483647"/>
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
<!-- end -->
<services>
<clear/>
<service name="ING.IWCFService.CitisecHashTransfer" >
<endpoint address="http://localhost:8099/CitisecHashTransfer.svc"
behaviorConfiguration="RestfullEndpointBehavior"
binding="webHttpBinding"
bindingConfiguration="RestfullwebHttpBinding"
name="ICitisecHashTransferBasicHttpBinding"
contract="ING.IWCFService.ICitisecHashTransfer" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="ING.IWCFService.IWCFServiceValidator, ING.IWCFService"/>
</serviceCredentials>
<serviceSecurityAudit auditLogLocation="Application" serviceAuthorizationAuditLevel="SuccessOrFailure" messageAuthenticationAuditLevel="SuccessOrFailure"/>
<serviceThrottling maxConcurrentCalls="1000" maxConcurrentSessions="100" maxConcurrentInstances="1000"/>
</behavior>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</behavior>
<behavior name="RestfullEndpointBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
This has been asked for various languages. Here's one question about passwords which should be applicable here as well.
If you want to use the strings for URL shortening, you'll also need a Dictionary<> or database check to see whether a generated ID has already been used.
An Example with python3
and the requests
library as mentioned by @leoluk:
pip install requests
Script req.py:
import requests
url='http://localhost'
# in case you need a session
cd = { 'sessionid': '123..'}
r = requests.get(url, cookies=cd)
# or without a session: r = requests.get(url)
r.content
Now,execute it and you will get the html source of localhost!
python3 req.py
for this issue you can create UIView inside "label with UIImage view" and set UIView class as a UIControl and create IBAction as tuch up in side
Here's an example for rotating about an arbitrary point (x,y) using only openCV
def rotate_about_point(x, y, degree, image):
rot_mtx = cv.getRotationMatrix2D((x, y), angle, 1)
abs_cos = abs(rot_mtx[0, 0])
abs_sin = abs(rot_mtx[0, 1])
rot_wdt = int(frm_hgt * abs_sin + frm_wdt * abs_cos)
rot_hgt = int(frm_hgt * abs_cos + frm_wdt * abs_sin)
rot_mtx += np.asarray([[0, 0, -lftmost_x],
[0, 0, -topmost_y]])
rot_img = cv.warpAffine(image, rot_mtx, (rot_wdt, rot_hgt),
borderMode=cv.BORDER_CONSTANT)
return rot_img
Are all the modifications to file.py
in branch2
in their own commits, separate from modifications to other files? If so, you can simply cherry-pick
the changes over:
git checkout branch1
git cherry-pick <commit-with-changes-to-file.py>
Otherwise, merge
does not operate over individual paths...you might as well just create a git diff
patch of file.py
changes from branch2
and git apply
them to branch1
:
git checkout branch2
git diff <base-commit-before-changes-to-file.py> -- file.py > my.patch
git checkout branch1
git apply my.patch
from pathlib import Path
data_folder = Path("source_data/text_files/")
file_to_open = data_folder / "raw_data.txt"
f = open(file_to_open)
print(f.read())
You can use perl to replace various characters, for example:
$ echo "Hello\ world" | perl -pe 's/\\/\\\\/g'
Hello\\ world
Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.
Web Container + HTTP request handling = WebServer
Web Server + EJB + (Messaging + Transactions+ etc) = ApplicaitonServer
A small word of caution, if "do some stuff" means updating the value of the actual property that you visit AND if there is a struct type property along the path from root object to the visited property, the change you made on the property will not be reflected on the root object.
In short, no, you can't.
Long answer, extension methods are just syntactic sugar. IE:
If you have an extension method on string let's say:
public static string SomeStringExtension(this string s)
{
//whatever..
}
When you then call it:
myString.SomeStringExtension();
The compiler just turns it into:
ExtensionClass.SomeStringExtension(myString);
So as you can see, there's no way to do that for static methods.
And another thing just dawned on me: what would really be the point of being able to add static methods on existing classes? You can just have your own helper class that does the same thing, so what's really the benefit in being able to do:
Bool.Parse(..)
vs.
Helper.ParseBool(..);
Doesn't really bring much to the table...
Not least important is why these symbols occur in url. See https://www.php.net/manual/en/function.parse-str.php#76792, specifically:
parse_str('foo[]=1&foo[]=2&foo[]=3', $bar);
the above produces:
$bar = ['foo' => ['1', '2', '3'] ];
and what is THE method to separate query vars in arrays (in php, at least).
2019 answer:
Using CSS grid:
.parent {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr;
}
With most Awk implementations:
awk 'BEGIN {srand(); print srand()}'
If is a package then you can get the source for that with:
select text from all_source where name = 'PADCAMPAIGN'
and type = 'PACKAGE BODY'
order by line;
Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.
Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use
select text from all_source where name = 'pAdCampaign'
and type = 'PACKAGE BODY'
order by line;
Another approach, if you don't care about whitespace being ignored:
for char in $(sed -E s/'(.)'/'\1 '/g <<<"$your_string"); do
# Handle $char here
done
A tty is a terminal (it stands for teletype - the original terminals used a line printer for output and a keyboard for input!). A terminal is a basically just a user interface device that uses text for input and output.
A pty is a pseudo-terminal - it's a software implementation that appears to the attached program like a terminal, but instead of communicating directly with a "real" terminal, it transfers the input and output to another program.
For example, when you ssh in to a machine and run ls
, the ls
command is sending its output to a pseudo-terminal, the other side of which is attached to the SSH daemon.
Update: Nowadays installing is done with pip, but libyaml is still required to build the C extension (on mac):
brew install libyaml
python -m pip install pyyaml
Outdated method:
For MacOSX (mavericks), the following seems to work:
brew install libyaml
sudo python -m easy_install pyyaml
I would suggest not to use list-style-image
, as it behaves quite differently in different browsers, especially the image position
instead, you can use something like this
ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }
it works in all browsers and would give you the identical result in different browsers.
Press Ctrl+C
When you start the server it mentions this in the startup text.
In case anyone else is interested to know how to import files/packages from gdrive inside a google colab. The following procedure worked for me:
1) Mount your google drive in google colab:
from google.colab import drive
drive.mount('/content/gdrive/')
2) Append the directory to your python path using sys:
import sys
sys.path.append('/content/gdrive/mypythondirectory')
Now you should be able to import stuff from that directory!
This is a very old answer. I definitely won't recommend Apache's client anymore. Instead use either:
First of all, request a permission to access network, add following to your manifest:
<uses-permission android:name="android.permission.INTERNET" />
Then the easiest way is to use Apache http client bundled with Android:
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet(URL));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
String responseString = out.toString();
out.close();
//..more logic
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
If you want it to run on separate thread I'd recommend extending AsyncTask:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
responseString = out.toString();
out.close();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
You then can make a request by:
new RequestTask().execute("http://stackoverflow.com");
great work on this class. Simple and easy to use. I modified the class to include a title in the first row of the export; figured I would share:
use:
CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));
class:
public class CsvExport
{
List<string> fields = new List<string>();
public string addTitle { get; set; } // string for the first row of the export
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> currentRow
{
get
{
return rows[rows.Count - 1];
}
}
public object this[string field]
{
set
{
if (!fields.Contains(field)) fields.Add(field);
currentRow[field] = value;
}
}
public void AddRow()
{
rows.Add(new Dictionary<string, object>());
}
string MakeValueCsvFriendly(object value)
{
if (value == null) return "";
if (value is Nullable && ((INullable)value).IsNull) return "";
if (value is DateTime)
{
if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
return ((DateTime)value).ToString("yyyy-MM-dd");
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
string output = value.ToString();
if (output.Contains(",") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
return output;
}
public string Export()
{
StringBuilder sb = new StringBuilder();
// if there is a title
if (!string.IsNullOrEmpty(addTitle))
{
// escape chars that would otherwise break the row / export
char[] csvTokens = new[] { '\"', ',', '\n', '\r' };
if (addTitle.IndexOfAny(csvTokens) >= 0)
{
addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
}
sb.Append(addTitle).Append(",");
sb.AppendLine();
}
// The header
foreach (string field in fields)
sb.Append(field).Append(",");
sb.AppendLine();
// The rows
foreach (Dictionary<string, object> row in rows)
{
foreach (string field in fields)
sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
sb.AppendLine();
}
return sb.ToString();
}
public void ExportToFile(string path)
{
File.WriteAllText(path, Export());
}
public byte[] ExportToBytes()
{
return Encoding.UTF8.GetBytes(Export());
}
}
You should \usepackage{longtable}
.
I decided to post a written Objective-C version from the accepted answer just to provide more options in this question..
- (UIView *)applyBlurToView:(UIView *)view withEffectStyle:(UIBlurEffectStyle)style andConstraints:(BOOL)addConstraints
{
//only apply the blur if the user hasn't disabled transparency effects
if(!UIAccessibilityIsReduceTransparencyEnabled())
{
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:style];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
blurEffectView.frame = view.bounds;
[view addSubview:blurEffectView];
if(addConstraints)
{
//add auto layout constraints so that the blur fills the screen upon rotating device
[blurEffectView setTranslatesAutoresizingMaskIntoConstraints:NO];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeTop
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeBottom
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeLeading
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeLeading
multiplier:1
constant:0]];
[view addConstraint:[NSLayoutConstraint constraintWithItem:blurEffectView
attribute:NSLayoutAttributeTrailing
relatedBy:NSLayoutRelationEqual
toItem:view
attribute:NSLayoutAttributeTrailing
multiplier:1
constant:0]];
}
}
else
{
view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.7];
}
return view;
}
The constraints could be removed if you want incase if you only support portrait mode or I just add a flag to this function to use them or not..
Javier covered Notifications and current limitations.
My suggestion: window.postMessage
while we wait for the handicapped browser to catch up, else Worker.postMessage()
to still be operating with Web Workers.
These can be the fallback option with dialog box message display handler, for when a Notification feature test fails or permission is denied.
Notification has-feature and denied-permission check:
if (!("Notification" in window) || (Notification.permission === "denied") ) {
// use (window||Worker).postMessage() fallback ...
}
Use the property table-layout:fixed;
on the table to get equally spaced cells. If a column has a width set, then no matter what the content is, it will be the specified width. Columns without a width set will divide whatever room is left over among themselves.
<table style='table-layout:fixed;'>
<tbody>
<tr>
<td>gobble de gook</td>
<td>mibs</td>
</tr>
</tbody>
</table>
Just to throw it out there, you could also use <colgroup><col span='#' style='width:#%;'/></colgroup>
, which doesn't require repetition of style per table data or giving the table an id to use in a style sheet. I think setting the widths on the first row is enough though.
With argparse you could do:
parser.argparse.ArgumentParser()
#parser.add_args here
#sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
You just can put your query as a subquery:
SELECT avg(count)
FROM
(
SELECT COUNT (*) AS Count
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time )
FROM Table B
WHERE (B.Id = T.Id))
GROUP BY T.Grouping
) as counts
Edit: I think this should be the same:
SELECT count(*) / count(distinct T.Grouping)
FROM Table T
WHERE T.Update_time =
(SELECT MAX (B.Update_time)
FROM Table B
WHERE (B.Id = T.Id))
The modulo operator %
in C and C++ is defined for two integers, however, there is an fmod()
function available for usage with doubles.
One way would be with sed
. For example:
echo $name | sed -e 's?http://www\.??'
Normally the sed
regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:
echo ${name#http://www.}
(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)
Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.
public static String decimalToBinaryString(int value) {
String str = "";
while(value > 0) {
if(value % 2 == 1) {
str = "1"+str;
} else {
str = "0"+str;
}
value /= 2;
}
return str;
}
You can leverage Apache Commons StringUtils.isEmpty(str)
, which checks for empty strings and handles null
gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str)
.
Example:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",
or even tends to report missing implementation, in spite it is there.
The only solution then is to verify consistency of declaration of implementation manually, method by method.
With the below code you have to set PermissionLevel=External on your project properties before you deploy, and change the database to trust external code (be sure to read elsewhere about security risks and alternatives [like certificates]) by running "ALTER DATABASE database_name SET TRUSTWORTHY ON".
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.SqlServer.Server;
[Serializable]
[SqlUserDefinedAggregate(Format.UserDefined,
MaxByteSize=8000,
IsInvariantToDuplicates=true,
IsInvariantToNulls=true,
IsInvariantToOrder=true,
IsNullIfEmpty=true)]
public struct CommaDelimit : IBinarySerialize
{
[Serializable]
private class StringList : List<string>
{ }
private StringList List;
public void Init()
{
this.List = new StringList();
}
public void Accumulate(SqlString value)
{
if (!value.IsNull)
this.Add(value.Value);
}
private void Add(string value)
{
if (!this.List.Contains(value))
this.List.Add(value);
}
public void Merge(CommaDelimit group)
{
foreach (string s in group.List)
{
this.Add(s);
}
}
void IBinarySerialize.Read(BinaryReader reader)
{
IFormatter formatter = new BinaryFormatter();
this.List = (StringList)formatter.Deserialize(reader.BaseStream);
}
public SqlString Terminate()
{
if (this.List.Count == 0)
return SqlString.Null;
const string Separator = ", ";
this.List.Sort();
return new SqlString(String.Join(Separator, this.List.ToArray()));
}
void IBinarySerialize.Write(BinaryWriter writer)
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(writer.BaseStream, this.List);
}
}
I've tested this using a query that looks like:
SELECT
dbo.CommaDelimit(X.value) [delimited]
FROM
(
SELECT 'D' [value]
UNION ALL SELECT 'B' [value]
UNION ALL SELECT 'B' [value] -- intentional duplicate
UNION ALL SELECT 'A' [value]
UNION ALL SELECT 'C' [value]
) X
And yields: A, B, C, D
myWebView.loadData(myHtmlString, "text/html; charset=UTF-8", null);
This works flawlessly, especially on Android 4.0, which apparently ignores character encoding inside HTML.
Tested on 2.3 and 4.0.3.
In fact, I have no idea about what other values besides "base64" does the last parameter take. Some Google examples put null in there.
I know this is very old question, however there is a very lightweight (~.5Kb) JavaScript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.
The library is Keydrown.
Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:
kd.P.down(function () {
console.log('The "P" key is being held down!');
});
kd.P.up(function () {
console.clear();
});
// This update loop is the heartbeat of Keydrown
kd.run(function () {
kd.tick();
});
I've incorporated Keydrown into my client-side JavaScript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)
I hope this helps.
I have shamelessly pulled some pretty big datasets in memory, and altough it did get sluggish it took maybe 15 Mo of data upwards with pretty intense calculations on the dataset. I doubt you will run into problems with memory unless you have intense calculations on the data and many many rows. Profiling and benchmarking with different mock resultsets will be your best bet to evaluate performance.
I have follow Wellington Lorindo posting. And My problem was solved.
Steps 1. run in terminal
ps ax | grep mysql
Result was
11200 ? Ssl 0:01 /usr/sbin/mysqld
11514 pts/0 S+ 0:00 grep mysql
Steps 2. Again type this
sudo service mysql start
And problem solved.
Thanks Wellington Lorindo
I solved that problem.
I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>
) and its states (state pattern, forward declaration).
The solution is as follows:
In the *.cpp
file, you must include the Header file that you forward, i.e.
ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"
template <class T>
class LinkFrame;
using namespace std;
template <class T>
class State {
protected:
LinkFrame<int> *myFrame;
}
Its cpp:
#include "State.h"
#include "Frame.h"
#include "LinkFrame.h"
template <class T>
bool State<T>::replace(Frame<T> *f){
And... another class.
Essentially you need to do an argsort
, what implementation you need depends if you want to use external libraries (e.g. NumPy) or if you want to stay pure-Python without dependencies.
The question you need to ask yourself is: Do you want the
Unfortunately the example in the question doesn't make it clear what is desired because both will give the same result:
>>> arr = np.array([1, 2, 3, 100, 5])
>>> np.argsort(np.argsort(arr))
array([0, 1, 2, 4, 3], dtype=int64)
>>> np.argsort(arr)
array([0, 1, 2, 4, 3], dtype=int64)
argsort
implementationIf you have NumPy at your disposal you can simply use the function numpy.argsort
or method numpy.ndarray.argsort
.
An implementation without NumPy was mentioned in some other answers already, so I'll just recap the fastest solution according to the benchmark answer here
def argsort(l):
return sorted(range(len(l)), key=l.__getitem__)
To get the indices that would sort the array/list you can simply call argsort
on the array or list. I'm using the NumPy versions here but the Python implementation should give the same results
>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(arr)
array([1, 2, 0, 3], dtype=int64)
The result contains the indices that are needed to get the sorted array.
Since the sorted array would be [1, 2, 3, 4]
the argsorted array contains the indices of these elements in the original.
1
and it is at index 1
in the original so the first element of the result is 1
. 2
is at index 2
in the original so the second element of the result is 2
. 3
is at index 0
in the original so the third element of the result is 0
. 4
and it is at index 3
in the original so the last element of the result is 3
.In this case you would need to apply argsort
twice:
>>> arr = np.array([3, 1, 2, 4])
>>> np.argsort(np.argsort(arr))
array([2, 0, 1, 3], dtype=int64)
In this case :
3
, which is the third largest value so it would have index 2
in the sorted array/list so the first element is 2
.1
, which is the smallest value so it would have index 0
in the sorted array/list so the second element is 0
.2
, which is the second-smallest value so it would have index 1
in the sorted array/list so the third element is 1
.4
which is the largest value so it would have index 3
in the sorted array/list so the last element is 3
.Change the order in which you are doing things just a bit. You seem to be dividing by 2 for no particular reason at all.
While your application does not guarantee an input string of semi colon delimited variables you could easily make it do so:
package com;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// Good practice to initialize before use
Scanner keyboard = new Scanner(System.in);
String input = "";
// it's also a good idea to prompt the user as to what is going on
keyboardScanner : for (;;) {
input = keyboard.next();
if (input.indexOf(",") >= 0) { // Realistically we would want to use a regex to ensure [0-9],...etc groupings
break keyboardScanner; // break out of the loop
} else {
keyboard = new Scanner(System.in);
continue keyboardScanner; // recreate the scanner in the event we have to start over, just some cleanup
}
}
String strarray[] = input.split(","); // move this up here
int intarray[] = new int[strarray.length];
int count = 0; // Declare variables when they are needed not at the top of methods as there is no reason to allocate memory before it is ready to be used
for (count = 0; count < intarray.length; count++) {
intarray[count] = Integer.parseInt(strarray[count]);
}
for (int s : intarray) {
System.out.println(s);
}
}
}
From the @Tgr's comment, there is an online tool : https://codetabs.com/count-loc/count-loc-online.html
You should use bootstrap column nesting.
See Bootstrap 3 or Bootstrap 4:
<div class="row">
<div class="col-md-5">Span 5</div>
<div class="col-md-3">Span 3<br />second line</div>
<div class="col-md-2">
<div class="row">
<div class="col-md-12">Span 2</div>
</div>
<div class="row">
<div class="col-md-12">Span 2</div>
</div>
</div>
<div class="col-md-2">Span 2</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="row">
<div class="col-md-12">Span 6</div>
<div class="col-md-12">Span 6</div>
</div>
</div>
<div class="col-md-6">Span 6</div>
</div>
http://jsfiddle.net/DRanJ/125/
(In Fiddle screen, enlarge your test screen to see the result, because I'm using col-md-*, then responsive stacks columns)
Note: I am not sure that BS2 allows columns nesting, but in the answer of Paul Keister, the columns nesting is not used. You should use it and avoid to reinvente css while bootstrap do well.
The columns height are auto, if you add a second line (like I do in my example), column height adapt itself.
Another option is to use querySelector('.foo')
or querySelectorAll('.foo')
which have broader browser support than getElementsByClassName
.
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
an easiest way which i used and worked well
date('Y-m-d', strtotime('-1 year'));
this worked perfect.. hope this will help someone else too.. :)
You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.
Start with a tab delimited file:
% cat /tmp/input.txt
a b
a2 b2
create a sequence file
hive> create table test_sq(k string, v string) stored as sequencefile;
try to load; as expected, this will fail:
hive> load data local inpath '/tmp/input.txt' into table test_sq;
But with this table:
hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;
The load works just fine:
hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a b
a2 b2
Now load into the sequence table from the text table:
insert into table test_sq select * from test_t;
Can also do load/insert with overwrite to replace all.
Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:
$('#myButton').on('click', function(event) {
event.preventDefault(); // To prevent following the link (optional)
...
});
You can also use inline javascript in the onclick attribute:
<a ... onclick="myFunc();">..</a>
Update: Corrected map rendering algorithm, added more illustrations, changed formating.
Perhaps the advantage for the "zig-zag" technique for mapping the tiles to the screen can be said that the tile's x
and y
coordinates are on the vertical and horizontal axes.
"Drawing in a diamond" approach:
By drawing an isometric map using "drawing in a diamond", which I believe refers to just rendering the map by using a nested for
-loop over the two-dimensional array, such as this example:
tile_map[][] = [[...],...]
for (cellY = 0; cellY < tile_map.size; cellY++):
for (cellX = 0; cellX < tile_map[cellY].size cellX++):
draw(
tile_map[cellX][cellY],
screenX = (cellX * tile_width / 2) + (cellY * tile_width / 2)
screenY = (cellY * tile_height / 2) - (cellX * tile_height / 2)
)
Advantage:
The advantage to the approach is that it is a simple nested for
-loop with fairly straight forward logic that works consistently throughout all tiles.
Disadvantage:
One downside to that approach is that the x
and y
coordinates of the tiles on the map will increase in diagonal lines, which might make it more difficult to visually map the location on the screen to the map represented as an array:
However, there is going to be a pitfall to implementing the above example code -- the rendering order will cause tiles that are supposed to be behind certain tiles to be drawn on top of the tiles in front:
In order to amend this problem, the inner for
-loop's order must be reversed -- starting from the highest value, and rendering toward the lower value:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
for (j = tile_map[i].size; j >= 0; j--): // Changed loop condition here.
draw(
tile_map[i][j],
x = (j * tile_width / 2) + (i * tile_width / 2)
y = (i * tile_height / 2) - (j * tile_height / 2)
)
With the above fix, the rendering of the map should be corrected:
"Zig-zag" approach:
Advantage:
Perhaps the advantage of the "zig-zag" approach is that the rendered map may appear to be a little more vertically compact than the "diamond" approach:
Disadvantage:
From trying to implement the zig-zag technique, the disadvantage may be that it is a little bit harder to write the rendering code because it cannot be written as simple as a nested for
-loop over each element in an array:
tile_map[][] = [[...],...]
for (i = 0; i < tile_map.size; i++):
if i is odd:
offset_x = tile_width / 2
else:
offset_x = 0
for (j = 0; j < tile_map[i].size; j++):
draw(
tile_map[i][j],
x = (j * tile_width) + offset_x,
y = i * tile_height / 2
)
Also, it may be a little bit difficult to try to figure out the coordinate of a tile due to the staggered nature of the rendering order:
Note: The illustrations included in this answer were created with a Java implementation of the tile rendering code presented, with the following int
array as the map:
tileMap = new int[][] {
{0, 1, 2, 3},
{3, 2, 1, 0},
{0, 0, 1, 1},
{2, 2, 3, 3}
};
The tile images are:
tileImage[0] ->
A box with a box inside.tileImage[1] ->
A black box.tileImage[2] ->
A white box.tileImage[3] ->
A box with a tall gray object in it.A Note on Tile Widths and Heights
The variables tile_width
and tile_height
which are used in the above code examples refer to the width and height of the ground tile in the image representing the tile:
Using the dimensions of the image will work, as long as the image dimensions and the tile dimensions match. Otherwise, the tile map could be rendered with gaps between the tiles.
Caution: This answer provides a solution that was relevant at that time, before the new features of MongoDB 2.2 and up were introduced. See the other answers if you are using a more recent version of MongoDB.
The field selector parameter is limited to complete properties. It cannot be used to select part of an array, only the entire array. I tried using the $ positional operator, but that didn't work.
The easiest way is to just filter the shapes in the client.
If you really need the correct output directly from MongoDB, you can use a map-reduce to filter the shapes.
function map() {
filteredShapes = [];
this.shapes.forEach(function (s) {
if (s.color === "red") {
filteredShapes.push(s);
}
});
emit(this._id, { shapes: filteredShapes });
}
function reduce(key, values) {
return values[0];
}
res = db.test.mapReduce(map, reduce, { query: { "shapes.color": "red" } })
db[res.result].find()
As John Galt mentions in his answer , you should probably instead use df.to_dict('records')
. It's faster than transposing manually.
In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop
In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop
Use df.T.to_dict().values()
, like below:
In [1]: df
Out[1]:
customer item1 item2 item3
0 1 apple milk tomato
1 2 water orange potato
2 3 juice mango chips
In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
{'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
{'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]
I believe VS2010 to be right this time, and I'd check if I had the standard handy, but currently I don't.
Now, it's exactly like the error message says: You can't capture stuff outside of the enclosing scope of the lambda.† grid
is not in the enclosing scope, but this
is (every access to grid
actually happens as this->grid
in member functions). For your usecase, capturing this
works, since you'll use it right away and you don't want to copy the grid
auto lambda = [this](){ std::cout << grid[0][0] << "\n"; }
If however, you want to store the grid and copy it for later access, where your puzzle
object might already be destroyed, you'll need to make an intermediate, local copy:
vector<vector<int> > tmp(grid);
auto lambda = [tmp](){}; // capture the local copy per copy
† I'm simplifying - Google for "reaching scope" or see §5.1.2 for all the gory details.
I would like to suggest a solution if you need to sort more than 2 lists in sync:
def SortAndSyncList_Multi(ListToSort, *ListsToSync):
y = sorted(zip(ListToSort, zip(*ListsToSync)))
w = [n for n in zip(*y)]
return list(w[0]), tuple(list(a) for a in zip(*w[1]))
Set the image to be the background of a div, then set the background size to be half the width of the image.
<div class="myimage"></div>
Then in your css, if your image is 300px x 200px:
.myimage {
background: url('images/myimage.png') no-repeat;
background-size:150px;
width:150px;
height:100px;
}
The below query takes the first date for each work order (in a table of showing all status changes):
SELECT
WORKORDERNUM,
MIN(DATE)
FROM
WORKORDERS
WHERE
DATE >= to_date('2015-01-01','YYYY-MM-DD')
GROUP BY
WORKORDERNUM
All credits to @Martijn Pieters in the comments:
You can use the function last_insert_rowid()
:
The
last_insert_rowid()
function returns theROWID
of the last row insert from the database connection which invoked the function. Thelast_insert_rowid()
SQL function is a wrapper around thesqlite3_last_insert_rowid()
C/C++ interface function.
If there is a package.json
, and in it there is lodash
configuration in it. then you should:
npm install
if in the package.json
there is no lodash
:
npm install --save-dev
app.get('/', function (req, res) {
res.sendfile(__dirname + '/public/index.html');
});
There are two kinds of input value: field's property and field's html attribute.
If you use keyup event and field.value you shuld get current value of the field. It's not the case when you use field.getAttribute('value') which would return what's in the html attribute (value=""). The property represents what's been typed into the field and changes as you type, while attribute doesn't change automatically (you can change it using field.setAttribute method).
There are 3 ways I can think of:
The way that is easiest to explain is
:%s/phrase to delete//gc
but you can also (personally I use this second one more often) do a regular search for the phrase to delete
/phrase to delete
Vim will take you to the beginning of the next occurrence of the phrase.
Go into insert mode (hit i) and use the Delete key to remove the phrase.
Hit escape when you have deleted all of the phrase.
Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed
Continue hitting n and dot until you are done.
Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you
Count the number of characters you want to delete
Type that number in (with number keys)
Hit the x key - characters should get deleted
Continue through with n and dot like in the second method.
PS - And if you didn't know already you can do a capital n to move backwards through the search matches.
For Chrome on Ubuntu (16.04), F11 is the way to go.
since you followed the tutorial, I presume you have a screen that says Hello World.
that means you have some code in your layout xml that looks like this
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/cool_pic"
/>
Updated for c# 6:
try
{
// some code
}
catch (SqlException ex) when (ex.Number == -2) // -2 is a sql timeout
{
// handle timeout
}
Very simple and nice to look at!!
for php 7.0 on ubuntu use
sudo apt-get install php7.0-curl
And finally,
sudo service apache2 restart
or
sudo service nginx restart
If the control you are waiting for is an "Ajax" web element, the following code will wait for it, or any other Ajax web element to finish loading or performing whatever it needs to do so that you can more-safely continue with your steps.
public static void waitForAjaxToFinish() {
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver wdriver) {
return ((JavascriptExecutor) driver).executeScript(
"return jQuery.active == 0").equals(true);
}
});
}
Possible Permission Issue
I know this post is fairly old, but I ran into a similar issue and my file was spelled correctly.
I originally created the app_offline.htm file in another location and then moved it to the root of my application. Because of my setup I then had a permissions issue.
The website acted as if it was not there. Creating the file within the root directory instead of moving it, fixed my problem. (Or you could just fix the permission in properties->security)
Hope it helps someone.
For example, if you want an array of int
pointers it will be int* a[10]
. It means that variable a
is a collection of 10 int*
s.
EDIT
I guess this is what you want to do:
class Bar
{
};
class Foo
{
public:
//Takes number of bar elements in the pointer array
Foo(int size_in);
~Foo();
void add(Bar& bar);
private:
//Pointer to bar array
Bar** m_pBarArr;
//Current fee bar index
int m_index;
};
Foo::Foo(int size_in) : m_index(0)
{
//Allocate memory for the array of bar pointers
m_pBarArr = new Bar*[size_in];
}
Foo::~Foo()
{
//Notice delete[] and not delete
delete[] m_pBarArr;
m_pBarArr = NULL;
}
void Foo::add(Bar &bar)
{
//Store the pointer into the array.
//This is dangerous, you are assuming that bar object
//is valid even when you try to use it
m_pBarArr[m_index++] = &bar;
}
I guess I'm a little late (a lot late;-)) to this post, but I'd like to add Perst, an open source, object-oriented embedded database for Java &.NET. for your consideration. Perst is an open source / dual license embedded database for Java. The distribution is compatible with Google's Android platform, and also includes Perst Lite for Java ME. We've even built an Android benchmark and produced a whitepaper on the subject...you can take a look here: http://www.mcobject.com/index.cfm?fuseaction=download&pageid=581§ionid=133
All the best, Chris
I'd recommend using the Buffer
class:
var someEncodedString = Buffer.from('someString', 'utf-8');
This avoids any unnecessary dependencies that other answers require, since Buffer
is included with node.js
, and is already defined in the global scope.
UPDATE: The original answer from 2013 is now outdated because some of the classes have been replaced. The new way of doing this is using the new java.time
classes.
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
LocalDateTime date1 = LocalDate.parse(inputString1, dtf);
LocalDateTime date2 = LocalDate.parse(inputString2, dtf);
long daysBetween = Duration.between(date1, date2).toDays();
System.out.println ("Days: " + daysBetween);
} catch (ParseException e) {
e.printStackTrace();
}
Note that this solution will give the number of actual 24 hour-days, not the number of calendar days. For the latter, use
long daysBetween = ChronoUnit.DAYS.between(date1, date2)
Original answer (outdated as of Java 8)
You are making some conversions with your Strings that are not necessary. There is a SimpleDateFormat
class for it - try this:
SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";
try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diff = date2.getTime() - date1.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
e.printStackTrace();
}
EDIT: Since there have been some discussions regarding the correctness of this code: it does indeed take care of leap years. However, the TimeUnit.DAYS.convert
function loses precision since milliseconds are converted to days (see the linked doc for more info). If this is a problem, diff
can also be converted by hand:
float days = (diff / (1000*60*60*24));
Note that this is a float
value, not necessarily an int
.
In my case the following was necessary:
sudo chgrp vboxsf /media/sf_sharedFolder
If you are using React try this custom Image component:
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import defaultErrorImage from 'assets/images/default-placeholder-image.png';
const Image = ({ src, alt, className, onErrorImage }) => {
const imageEl = useRef(null);
return (
<img
src={src}
alt={alt}
className={className}
onError={() => {
imageEl.current.src = onErrorImage;
}}
ref={imageEl}
/>
);
};
Image.defaultProps = {
onErrorImage: defaultErrorImage,
};
Image.propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
onErrorImage: PropTypes.string,
};
export default Image;