<a href="/fruits/index.html">Back to Fruits List</a>
You can do this quite easily with lxml. First install it:
[sudo] pip install lxml
Here is a recursive function I wrote that does the heavy lifting for you:
from lxml import objectify as xml_objectify
def xml_to_dict(xml_str):
""" Convert xml to dict, using lxml v3.4.2 xml processing library """
def xml_to_dict_recursion(xml_object):
dict_object = xml_object.__dict__
if not dict_object:
return xml_object
for key, value in dict_object.items():
dict_object[key] = xml_to_dict_recursion(value)
return dict_object
return xml_to_dict_recursion(xml_objectify.fromstring(xml_str))
xml_string = """<?xml version="1.0" encoding="UTF-8"?><Response><NewOrderResp>
<IndustryType>Test</IndustryType><SomeData><SomeNestedData1>1234</SomeNestedData1>
<SomeNestedData2>3455</SomeNestedData2></SomeData></NewOrderResp></Response>"""
print xml_to_dict(xml_string)
The below variant preserves the parent key / element:
def xml_to_dict(xml_str):
""" Convert xml to dict, using lxml v3.4.2 xml processing library, see http://lxml.de/ """
def xml_to_dict_recursion(xml_object):
dict_object = xml_object.__dict__
if not dict_object: # if empty dict returned
return xml_object
for key, value in dict_object.items():
dict_object[key] = xml_to_dict_recursion(value)
return dict_object
xml_obj = objectify.fromstring(xml_str)
return {xml_obj.tag: xml_to_dict_recursion(xml_obj)}
If you want to only return a subtree and convert it to dict, you can use Element.find() to get the subtree and then convert it:
xml_obj.find('.//') # lxml.objectify.ObjectifiedElement instance
See the lxml docs here. I hope this helps!
include
folder where you have installed
Codeblocks. int left=0, int top=0, int right=INT_MAX, int bottom=INT_MAX,
in that line.You can use map lambda
a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)
This will also work if there lengths of original lists do not match
In addition (or in replacement) to the HTML5's <a download
attribute already mentioned,
the browser's download to disk behavior can also be triggered by the following http response header:
Content-Disposition: attachment; filename=ProposedFileName.txt;
This was the way to do before HTML5 (and still works with browsers supporting HTML5).
In IntelliJ 14, the path to the settings for Auto Import has changed. The path is
IntelliJ IDEA->Preferences->Editor->General->Auto Import
then follow the instructions above, clicking Add unambiguous imports on the fly
I can't imagine why this wouldn't be set by default.
I just had the same problem and all I did was delete the user log in credentials in sql server using another user id and adding them back.
If you want to define your ItemReader
instance and your Step
instance in a single JavaConfig class. You can use the @StepScope
and the @Value
annotations such as:
@Configuration
public class ContributionCardBatchConfiguration {
private static final String WILL_BE_INJECTED = null;
@Bean
@StepScope
public FlatFileItemReader<ContributionCard> contributionCardReader(@Value("#{jobParameters['fileName']}")String contributionCardCsvFileName){
....
}
@Bean
Step ingestContributionCardStep(ItemReader<ContributionCard> reader){
return stepBuilderFactory.get("ingestContributionCardStep")
.<ContributionCard, ContributionCard>chunk(1)
.reader(contributionCardReader(WILL_BE_INJECTED))
.writer(contributionCardWriter())
.build();
}
}
The trick is to pass a null value to the itemReader since it will be injected through the @Value("#{jobParameters['fileName']}")
annotation.
Thanks to Tobias Flohre for his article : Spring Batch 2.2 – JavaConfig Part 2: JobParameters, ExecutionContext and StepScope
Open a terminal window
$sudo cp -R /Applications/Xcode4/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1.sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/
You will be prompt to enter a password since you're inside a system folder
You cannot change the Width and Height properties of the Form as they are readonly. You can change the form's size like this:
button1_Click(object sender, EventArgs e)
{
// This will change the Form's Width and Height, respectively.
this.Size = new Size(420, 200);
}
You can also just right click on the page in the browser and select "Inspect Element" to bring up the developer tools.
solve(c)
does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c
to invoke matrix multiplication in R.
R performs element by element multiplication when you invoke solve(c) * c
.
The answer from @laughing_man is quite accurate. But still, I wanted to give a recommendation which I learned from Kafka expert Stephane Maarek.
Kafka isn’t meant to handle large messages.
Your API should use cloud storage (Ex AWS S3), and just push to Kafka or any message broker a reference of S3. You must find somewhere to persist your data, maybe it’s a network drive, maybe it’s whatever, but it shouldn't be message broker.
Now, if you don’t want to go with the above solution
The message max size is 1MB (the setting in your brokers is called message.max.bytes
) Apache Kafka. If you really needed it badly, you could increase that size and make sure to increase the network buffers for your producers and consumers.
And if you really care about splitting your message, make sure each message split has the exact same key so that it gets pushed to the same partition, and your message content should report a “part id” so that your consumer can fully reconstruct the message.
You can also explore compression, if your message is text-based (gzip, snappy, lz4 compression) which may reduce the data size, but not magically.
Again, you have to use an external system to store that data and just push an external reference to Kafka. That is a very common architecture and one you should go with and widely accepted.
Keep that in mind Kafka works best only if the messages are huge in amount but not in size.
Source: https://www.quora.com/How-do-I-send-Large-messages-80-MB-in-Kafka
Use media queries. Your CSS code would be:
@media screen and (max-width: 1024px) {
.yourClass {
display: none !important;
}
}
Simple solution for cast pointer to object
class myClass
{
public:
void sayHello () {
cout << "Hello";
}
};
int main ()
{
myClass* myPointer;
myClass myObject = myClass(* myPointer); // Cast pointer to object
myObject.sayHello();
return 0;
}
Easiest solution:
app.disable('etag');
Alternate solution here if you want more control:
I had similar issue with c#, first I found that each project may have a few different types. i.e. in .csproject file locate ProjectTypeGuids, it should be a few guids, i.e.
<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
they will point on component you are missing. In my case it was ASP.NET MVC 2. Some guys get it worked by installing MVC 2 destribution.
My case was worse, because installation didn't work, but it turned out that it was because I had Express 2008 and 2010. I fixed it by uninstalling both 2008 & 2010 and installing only 2010 versions. For c# you need both Visual C# Express and Visual Web Developer express
after doing all the installation of graphviz, adding to the PATH of environment variables, you need to add these two lines:
import os
os.environ["PATH"] += os.pathsep + 'C:/Program Files (x86)/Graphviz2.38/bin/'
Provided that the remote repository is origin, and that you're interested in master:
git fetch origin
git reset --hard origin/master
This tells it to fetch the commits from the remote repository, and position your working copy to the tip of its master branch.
All your local commits not common to the remote will be gone.
check this one:
import java.io.*;
public class UserInputInteger
{
public static void main(String args[])throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int number;
System.out.println("Enter the number");
number = Integer.parseInt(in.readLine());
}
}
Try using
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
and not
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
You are not actually changing the function.
onClick
is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.
Another problem is your variable color
seems out of nowhere.
Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)
Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.
For i = 0 To d.Count - 1
s = d.Items()(i)
Debug.Print s
Next i()
KEYS works the same way
For i = 0 To d.Count - 1
Debug.Print d.Keys()(i), d.Items()(i)
Next i
This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".
Debug.Print Split("A,B,C,D", ",")(2)
SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.
Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.
There are lots of answers on this topic already so I wouldn't add a redundant one.
But to someone who just started learning Observable / Angular and wonders which one to use compare with Promise, I would recommend you keep everything Observable and convert all existing Promises in your project to Observable.
Simply because Angular framework itself and it's community are all using Observable. So it would be beneficial when you integrate framework services or 3rd party modules and chaining everything together.
While I appreciate all the downvotes but I still insist my opinion above unless someone put a proper comment to list a few scenarios that might still be useful in your Angular project to use Promises over Observables.
Of course, no opinion is 100% correct in all cases but at least I think 98% of the time for regular commercial projects implemented in Angular framework, Observable is the right way to go.
Even if you don't like it at the starting point of your simple hobby project, you'll soon realise almost all components you interact with in Angular, and most of the Angular friendly 3rd party framework are using Observables, and then you'll ended up constantly converting your Promise to Observable in order to communicate with them.
Those components includes but not limited to: HttpClient, Form builder, Angular material modules/dialogs, Ngrx store/effects and ngx-bootstrap.
In fact, the only Promise from Angular eco-system I dealt with in the past 2 years is APP_INITIALIZER
.
I don't know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint
Server:
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
Client
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
it also have all the needed information for simple client/server applications.
Just convert the server and use some simple protocol to call a function from python.
P.S: i'm sure there are a lot of better options, it's just a simple one if you want...
Fixed it. I needed to run libtoolize
in the directory, then re-run:
aclocal
autoheader
Project with Multiple Targets
In my case I am working on Project with multiple Targets and the issue was "inherit from Target" was unchecked. Selecting "inherit from target" solved my problem
You'll find the junit launch commands in .metadata/.plugins/org.eclipse.debug.core/.launches, assuming your Eclipse works like mine does. The files are named {TestClass}.launch.
You will probably also need the .classpath file in the project directory that contains the test class.
Like the run configurations, they're XML files (even if they don't have an xml extension).
It's weird that SelectedItem holds the fresh data, whereas SelectedValue doesn't. Sounds like a bug to me. If your items in the Combobox are objects other than ComboBoxItems, you will need something like this: (my ComboBox
contains KeyValuePair
s)
var selectedItem = (KeyValuePair<string, string>?)(sender as ComboBox).SelectedItem;
if (!selectedItem.HasValue)
return;
string selectedValue = selectedItem.Value.Value; // first .Value gets ref to KVPair
ComboBox.SelectedItem
can be null, whereas Visual Studio keeps telling me that a KeyValuePair
can't be null. That's why I cast the SelectedItem
to a nullable KeyValuePair<string, string>?
. Then I check if selectedItem
has a value other than null
. This approach should be applicable to whatever type your selected item actually is.
You can insert into a table from a SELECT.
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
(SELECT id FROM state WHERE name = 'New York'),
(SELECT id FROM positions WHERE name = 'Sales Executive'),
(SELECT id FROM manager WHERE name = 'Barry Green')
FROM
dual
Or, similarly...
INSERT INTO
Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
001,
'John Doe',
'1 River Walk, Green Street',
state.id,
positions.id,
manager.id
FROM
state
CROSS JOIN
positions
CROSS JOIN
manager
WHERE
state.name = 'New York'
AND positions.name = 'Sales Executive'
AND manager.name = 'Barry Green'
Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.
Only 1 emulator or device may be open at a time. Make sure you don't have multiple emulators running.
Require Screen sizes for splash :
LDPI: Portrait: 200 X 320px
MDPI: Portrait: 320 X 480px
HDPI: Portrait: 480 X 800px
XHDPI: Portrait: 720 X 1280px
XXHDPI: Portrait: 960 X 1600px
XXXHDPI: Portrait: 1440 x 2560px
Require icon Sizes for App :
$(function() { ... });
is just jQuery short-hand for
$(document).ready(function() { ... });
What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.
However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?
Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!
if you use jquery on you website, you can use something like this your console
$.post(_x000D_
'dom/data-home.php',_x000D_
{_x000D_
type : "home", id : "0"_x000D_
},function(data){_x000D_
console.log(data)_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
import re
s = '''
text1
text2
http://url.com/bla1/blah1/
text3
text4
http://url.com/bla2/blah2/
text5
text6
http://url.com/bla3/blah3/'''
g = re.findall(r'(text\d+)',s)
print ('list',g)
for i in g:
print (i)
Out
list ['text1', 'text2', 'text3', 'text4', 'text5', 'text6']
text1
text2
text3
text4
text5
text6 ?
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven't found any bugs in the functions; After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
Same codes from Nickolay above, but tested on IE9 and chrome (and removed the extra rendering):
window.onload = window.onresize = function() {
var canvas = document.getElementById('canvas');
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * 0.8;
var canvasHeight = canvasWidth / 2;
canvas.style.position = "absolute";
canvas.setAttribute("width", canvasWidth);
canvas.setAttribute("height", canvasHeight);
canvas.style.top = (viewportHeight - canvasHeight) / 2 + "px";
canvas.style.left = (viewportWidth - canvasWidth) / 2 + "px";
}
HTML:
<body>
<canvas id="canvas" style="background: #ffffff">
Canvas is not supported.
</canvas>
</body>
The top and left offset only works when I add px
.
This is what I did:
Very simply put:
=IF(C7>100,"Profit",IF(C7=100,"Quota Met","Loss"))
The first IF
Statement, if true will input Profit, and if false will lead on to the next IF
statement and so forth :)
I only have basic formula knowledge but it's working so I will accept I am right!
This is an exeprt from Technet (so not sure why the marked answer says named pipes are faster??):
Named Pipes vs. TCP/IP Sockets
In a fast local area network (LAN) environment, Transmission Control Protocol/Internet Protocol (TCP/IP) Sockets and Named Pipes clients are comparable with regard to performance. However, the performance difference between the TCP/IP Sockets and Named Pipes clients becomes apparent with slower networks, such as across wide area networks (WANs) or dial-up networks. This is because of the different ways the interprocess communication (IPC) mechanisms communicate between peers.
For named pipes, network communications are typically more interactive. A peer does not send data until another peer asks for it using a read command. A network read typically involves a series of peek named pipes messages before it starts to read the data. These can be very costly in a slow network and cause excessive network traffic, which in turn affects other network clients.
It is also important to clarify if you are talking about local pipes or network pipes. If the server application is running locally on the computer that is running an instance of SQL Server, the local Named Pipes protocol is an option. Local named pipes runs in kernel mode and is very fast.
For TCP/IP Sockets, data transmissions are more streamlined and have less overhead. Data transmissions can also take advantage of TCP/IP Sockets performance enhancement mechanisms such as windowing, delayed acknowledgements, and so on. This can be very helpful in a slow network. Depending on the type of applications, such performance differences can be significant.
TCP/IP Sockets also support a backlog queue. This can provide a limited smoothing effect compared to named pipes that could lead to pipe-busy errors when you are trying to connect to SQL Server.
Generally, TCP/IP is preferred in a slow LAN, WAN, or dial-up network, whereas named pipes can be a better choice when network speed is not the issue, as it offers more functionality, ease of use, and configuration options.
The method jQuery (v1.10) uses to find this is:
var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
That is:
window.pageXOffset
first and uses that if it exists.document.documentElement.scrollLeft
.document.documentElement.clientLeft
if it exists.The subtraction of document.documentElement.clientLeft
/ Top
only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.
I don't know how they are getting away with it, or what negative side effects their may be, but I'm using Hover.com to host some of my domains, and recently setup the apex of my domain as a CNAME there. Their DNS editing tool did not complain at all, and my domain happily resolves via the CNAME assigned.
Here is what Dig shows me for this domain (actual domain obfuscated as mydomain.com):
; <<>> DiG 9.8.3-P1 <<>> mydomain.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 2056
;; flags: qr rd ra; QUERY: 1, ANSWER: 3, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;mydomain.com. IN A
;; ANSWER SECTION:
mydomain.com. 394 IN CNAME myapp.parseapp.com.
myapp.parseapp.com. 300 IN CNAME parseapp.com.
parseapp.com. 60 IN A 54.243.93.102
There is no built in thread based pool. However, it can be very quick to implement a producer/consumer queue with the Queue
class.
From: https://docs.python.org/2/library/queue.html
from threading import Thread
from Queue import Queue
def worker():
while True:
item = q.get()
do_work(item)
q.task_done()
q = Queue()
for i in range(num_worker_threads):
t = Thread(target=worker)
t.daemon = True
t.start()
for item in source():
q.put(item)
q.join() # block until all tasks are done
This is how you do it in 2020:
var s = "ABCDEFGH";
var first5 = s.AsSpan(0, 5);
A Span<T> points directly to the memory of the string, avoiding allocating a temporary string. Of course, any subsequent method asking for a string
requires a conversion:
Console.WriteLine(first5.ToString());
Though, these days many .NET
APIs allow for spans. Stick to them if possible!
Note: If targeting .NET Framework
add a reference to the System.Memory package, but don't expect the same superb performance.
In addition to the answer of BalusC, use the following Java RegExp to replace &&
with and
:
Search: (#\{[^\}]*)(&&)([^\}]*\})
Replace: $1and$3
You have run this regular expression replacement multiple times to find all occurences in case you are using >2 literals in your EL expressions. Mind to replace the leading # by $ if your EL expression syntax differs.
Popup blockers will typically only allow window.open
if used during the processing of a user event (like a click). In your case, you're calling window.open
later, not during the event, because $.getJSON
is asynchronous.
You have two options:
Do something else, rather than window.open
.
Make the ajax call synchronous, which is something you should normally avoid like the plague as it locks up the UI of the browser. $.getJSON
is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
...and so you can make your $.getJSON
call synchronous by mapping your params to the above and adding async: false
:
$.ajax({
url: "redirect/" + pageId,
async: false,
dataType: "json",
data: {},
success: function(status) {
if (status == null) {
alert("Error in verifying the status.");
} else if(!status) {
$("#agreement").dialog("open");
} else {
window.open(redirectionURL);
}
}
});
Again, I don't advocate synchronous ajax calls if you can find any other way to achieve your goal. But if you can't, there you go.
Here's an example of code that fails the test because of the asynchronous call:
Live example | Live source (The live links no longer work because of changes to JSBin)
jQuery(function($) {
// This version doesn't work, because the window.open is
// not during the event processing
$("#theButton").click(function(e) {
e.preventDefault();
$.getJSON("http://jsbin.com/uriyip", function() {
window.open("http://jsbin.com/ubiqev");
});
});
});
And here's an example that does work, using a synchronous call:
Live example | Live source (The live links no longer work because of changes to JSBin)
jQuery(function($) {
// This version does work, because the window.open is
// during the event processing. But it uses a synchronous
// ajax call, locking up the browser UI while the call is
// in progress.
$("#theButton").click(function(e) {
e.preventDefault();
$.ajax({
url: "http://jsbin.com/uriyip",
async: false,
dataType: "json",
success: function() {
window.open("http://jsbin.com/ubiqev");
}
});
});
});
Try this
chdir /d D:\Work\Root
Enjoy rooting ;)
Here i tried with this approach :
import numpy as np
#converting to one_hot
def one_hot_encoder(value, datal):
datal[value] = 1
return datal
def _one_hot_values(labels_data):
encoded = [0] * len(labels_data)
for j, i in enumerate(labels_data):
max_value = [0] * (np.max(labels_data) + 1)
encoded[j] = one_hot_encoder(i, max_value)
return np.array(encoded)
If you want to update branch that is not currently checked out you can do:
git fetch -f origin rbranch:lbranch
Assuming your byteData
array is biger than 32 + byteSalt.length()
...you're going to it's length, not byteSalt.length
. You're trying to copy from beyond the array end.
You can do this because regular expressions define extractors but you need to define the regex pattern first. I don't have access to a Scala REPL to test this but something like this should work.
val Pattern = "([a-cA-C])".r
word.firstLetter match {
case Pattern(c) => c bound to capture group here
case _ =>
}
If the class implements comparable, you could also do
int compRes = a.compareTo(b);
if(compRes < 0 || compRes > 0)
System.out.println("not equal");
else
System.out.println("equal);
doesn't use a !
, though not particularly useful, or readable....
A small update for the new Skype options window. Please follow this:
Go to Tools ? Options ? Advanced ? Connection
and uncheck the box use port 80 and 443 as alternatives for incoming connections
.
The answer to that question depends somewhat on the particular Python implementation.
To understand what this is all about, pay particular attention to the actual file
object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after the read()
call returns.
This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".
in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.
A better solution, to make sure that the file is closed, is this pattern:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
which will always close the file immediately after the block ends; even if an exception occurs.
Edit: To put a finer point on it:
Other than file.__exit__()
, which is "automatically" called in a with
context manager setting, the only other way that file.close()
is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__()
. This leads us to the question of when does __del__()
get called?
A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.
-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203
In particular:
Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.
[...]
CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.
-- https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types
(Emphasis mine)
but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!
I advocate use of the "rel" attribute. The XHTML validates, the attribute itself is rarely used, and the data is efficiently retrieved.
For those of you landing here but searching how to break out of a loop that contains an include statement use return instead of break or continue.
<?php
for ($i=0; $i < 100; $i++) {
if (i%2 == 0) {
include(do_this_for_even.php);
}
else {
include(do_this_for_odd.php);
}
}
?>
If you want to break when being inside do_this_for_even.php you need to use return. Using break or continue will return this error: Cannot break/continue 1 level. I found more details here
There are a few good answers posted here, but I think you can simplify your code and skip the check for inputElement.selectionStart
support: it is not supported only on IE8 and earlier (see documentation) which represents less than 1% of the current browser usage.
var input = document.getElementById('myinput'); // or $('#myinput')[0]
var caretPos = input.selectionStart;
// and if you want to know if there is a selection or not inside your input:
if (input.selectionStart != input.selectionEnd)
{
var selectionValue =
input.value.substring(input.selectionStart, input.selectionEnd);
}
This is what worked for me
$scope.form_name.field_name.$setDirty()
That is because Low
is a string.
.toFixed()
only works with a number.
Try doing:
Low = parseFloat(Low).toFixed(..);
I didn't particularly like any of the answers.
Here is how I did it.
# Convert the file into an array of strings
lines=(`cat "foo.txt"`)
# Print out the lines via array index
echo "${lines[0]}"
echo "${lines[1]}"
echo "${lines[5]}"
If using dotnet run
dotnet run --urls="http://localhost:5001"
Answering my own question.
curl -X GET --basic --user username:password \
https://www.example.com/mobile/resource
curl -X DELETE --basic --user username:password \
https://www.example.com/mobile/resource
curl -X PUT --basic --user username:password -d 'param1_name=param1_value' \
-d 'param2_name=param2_value' https://www.example.com/mobile/resource
POSTing a file and additional parameter
curl -X POST -F 'param_name=@/filepath/filename' \
-F 'extra_param_name=extra_param_value' --basic --user username:password \
https://www.example.com/mobile/resource
You can use the terms aggregation.
{
"size": 0,
"aggs" : {
"langs" : {
"terms" : { "field" : "language", "size" : 500 }
}
}}
The size
parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.
A search will return something like:
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"langs" : {
"buckets" : [ {
"key" : "10",
"doc_count" : 244812
}, {
"key" : "11",
"doc_count" : 136794
}, {
"key" : "12",
"doc_count" : 32312
} ]
}
}
}
I'm using a custom view that I layout on top of the other ones and that just draws the 4 small corners in the same color as the background. This works whatever the view contents are and does not allocate much memory.
public class RoundedCornersView extends View {
private float mRadius;
private int mColor = Color.WHITE;
private Paint mPaint;
private Path mPath;
public RoundedCornersView(Context context) {
super(context);
init();
}
public RoundedCornersView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.RoundedCornersView,
0, 0);
try {
setRadius(a.getDimension(R.styleable.RoundedCornersView_radius, 0));
setColor(a.getColor(R.styleable.RoundedCornersView_cornersColor, Color.WHITE));
} finally {
a.recycle();
}
}
private void init() {
setColor(mColor);
setRadius(mRadius);
}
private void setColor(int color) {
mColor = color;
mPaint = new Paint();
mPaint.setColor(mColor);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
invalidate();
}
private void setRadius(float radius) {
mRadius = radius;
RectF r = new RectF(0, 0, 2 * mRadius, 2 * mRadius);
mPath = new Path();
mPath.moveTo(0,0);
mPath.lineTo(0, mRadius);
mPath.arcTo(r, 180, 90);
mPath.lineTo(0,0);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
/*Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(0, 0, mRadius, mRadius, paint);*/
int w = getWidth();
int h = getHeight();
canvas.drawPath(mPath, mPaint);
canvas.save();
canvas.translate(w, 0);
canvas.rotate(90);
canvas.drawPath(mPath, mPaint);
canvas.restore();
canvas.save();
canvas.translate(w, h);
canvas.rotate(180);
canvas.drawPath(mPath, mPaint);
canvas.restore();
canvas.translate(0, h);
canvas.rotate(270);
canvas.drawPath(mPath, mPaint);
}
}
If you're file isn't too big you can always sort by the column that has the - and once they're all together just highlight and delete. Then re-sort back to what you want.
Adding new items to String array.
String[] myArray = new String[] {"x", "y"};
// Convert array to list
List<String> listFromArray = Arrays.asList(myArray);
// Create new list, because, List to Array always returns a fixed-size list backed by the specified array.
List<String> tempList = new ArrayList<String>(listFromArray);
tempList.add("z");
//Convert list back to array
String[] tempArray = new String[tempList.size()];
myArray = tempList.toArray(tempArray);
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
I had the very same problem and then I realized that programming in NodeJS is actually different than Python or Java as its based on JavaScript. I'll try to use simple concepts as there may be a few new folks that would be interested or may come to this question.
Let's look at the following code :
var http = require('http'); // (1)
exports.handler = function(event, context) {
console.log('start request to ' + event.url)
http.get(event.url, // (2)
function(res) { //(3)
console.log("Got response: " + res.statusCode);
context.succeed();
}).on('error', function(e) {
console.log("Got error: " + e.message);
context.done(null, 'FAILURE');
});
console.log('end request to ' + event.url); //(4)
}
Whenever you make a call to a method in http package (1) , it is created as event and this event gets it separate event. The 'get' function (2) is actually the starting point of this separate event.
Now, the function at (3) will be executing in a separate event, and your code will continue it executing path and will straight jump to (4) and finish it off, because there is nothing more to do.
But the event fired at (2) is still executing somewhere and it will take its own sweet time to finish. Pretty bizarre, right ?. Well, No it is not. This is how NodeJS works and its pretty important you wrap your head around this concept. This is the place where JavaScript Promises come to help.
You can read more about JavaScript Promises here. In a nutshell, you would need a JavaScript Promise to keep the execution of code inline and will not spawn new / extra threads.
Most of the common NodeJS packages have a Promised version of their API available, but there are other approaches like BlueBirdJS that address the similar problem.
The code that you had written above can be loosely re-written as follows.
'use strict';
console.log('Loading function');
var rp = require('request-promise');
exports.handler = (event, context, callback) => {
var options = {
uri: 'https://httpbin.org/ip',
method: 'POST',
body: {
},
json: true
};
rp(options).then(function (parsedBody) {
console.log(parsedBody);
})
.catch(function (err) {
// POST failed...
console.log(err);
});
context.done(null);
};
Please note that the above code will not work directly if you will import it in AWS Lambda. For Lambda, you will need to package the modules with the code base too.
tryCatch
has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:
expr: [Required] R code(s) to be evaluated
error : [Optional] What should run if an error occured while evaluating the codes in expr
warning : [Optional] What should run if a warning occured while evaluating the codes in expr
finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning
tryCatch(
expr = {
# Your code...
# goes here...
# ...
},
error = function(e){
# (Optional)
# Do this if an error is caught...
},
warning = function(w){
# (Optional)
# Do this if an warning is caught...
},
finally = {
# (Optional)
# Do this at the end before quitting the tryCatch structure...
}
)
Thus, a toy example, to calculate the log of a value might look like:
log_calculator <- function(x){
tryCatch(
expr = {
message(log(x))
message("Successfully executed the log(x) call.")
},
error = function(e){
message('Caught an error!')
print(e)
},
warning = function(w){
message('Caught an warning!')
print(w)
},
finally = {
message('All done, quitting.')
}
)
}
Now, running three cases:
A valid case
log_calculator(10)
# 2.30258509299405
# Successfully executed the log(x) call.
# All done, quitting.
A "warning" case
log_calculator(-10)
# Caught an warning!
# <simpleWarning in log(x): NaNs produced>
# All done, quitting.
An "error" case
log_calculator("log_me")
# Caught an error!
# <simpleError in log(x): non-numeric argument to mathematical function>
# All done, quitting.
I've written about some useful use-cases which I use regularly. Find more details here: https://rsangole.netlify.com/post/try-catch/
Hope this is helpful.
We actually had these merged together originally, i.e. there was a "filter"-like method that accepted *args
and **kwargs
, where you could pass a SQL expression or keyword arguments (or both). I actually find that a lot more convenient, but people were always confused by it, since they're usually still getting over the difference between column == expression
and keyword = expression
. So we split them up.
to make it work add soft reference to /usr/bin:
As of Bootstrap 3.x, there's an example of this in the docs here: http://getbootstrap.com/components/#input-groups-buttons-dropdowns
<div class="input-group">
<input type="text" class="form-control" aria-label="...">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Action <span class="caret"></span></button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div><!-- /btn-group -->
</div><!-- /input-group -->
Use dotPeek
Select the .dll
to decompile
That's it
This didnt worked for me. (Im with Angular 2.1.2). I had NOT to import MainPipeModule in app.module.ts and importe it instead in the module where the component Im using the pipe is imported too.
Looks like if your component is declared and imported in a different module, you need to include your PipeModule in that module too.
A trap is called by code like programs and used e. g. to call OS routines (i. e. normally synchronous). An interrupt is called by events (many times hardware, like the network card having received data, or the CPU timer), and - as the name suggests - interrupts the normal control flow, as the CPU has to switch to the driver routine to handle the event.
I had the same issue while adding Flask. So used one of the above command.
pip install --ignore-installed --upgrade --user flask
Got only a small warning and it worked!!
Installing collected packages: click, MarkupSafe, Jinja2, itsdangerous, Werkzeug, flask WARNING: The script flask.exe is installed in 'C:\Users\Admin\AppData\Roaming\Python\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. Successfully installed Jinja2-2.11.2 MarkupSafe-1.1.1 Werkzeug-1.0.1 click-7.1.2 flask-1.1.2 itsdangerous-1.1.0 WARNING: You are using pip version 20.1.1; however, version 20.2 is available. You should consider upgrading via the 'c:\python38\python.exe -m pip install --upgrade pip' command.
For all those facing a similar issue, I came across this same issue when i was trying to run a particular code snippet, shown below.
<html>
<head>
<script>
var div, container = document.getElementById("container")
for(var i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
https://codepen.io/pcwanderer/pen/MMEREr
Looking at the error in the console for the above code.
Since the document.getElementById is returning a null and as null does not have a attribute named appendChild, therefore a error is thrown. To solve the issue see the code below.
<html>
<head>
<style>
#container{
height: 200px;
width: 700px;
background-color: red;
margin: 10px;
}
div{
height: 100px;
width: 100px;
background-color: purple;
margin: 20px;
display: inline-block;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var div, container = document.getElementById("container")
for(let i=0;i<5;i++){
div = document.createElement("div");
div.onclick = function() {
alert("This is a box #"+i);
};
container.appendChild(div);
}
</script>
</body>
</html>
https://codepen.io/pcwanderer/pen/pXWBQL
I hope this helps. :)
You can simply call filter
multiple times:
query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \
filter(User.lastname.like(searchVar2))
To achieve your current need, you need to fire below query
> insert overwrite table student
> select *from student
> where id <> 1;
This will delete current table and create new table with same name with all rows except the rows that you want to exclude/delete
I tried this on Hive 1.2.1
Using the -clean
option is the way to go, as mentioned by the other answers.
Make sure that you remove it from your .ini
or shortcut after you've fixed the problem. It causes Eclipse to reevaluate all of the plugins everytime it starts and can dramatically increase startup time, depending on how many Eclipse plugins you have installed.
You can get all tables that has column "Product" from information_Schema.columns
SELECT DISTINCT table_name FROM information_schema.columns WHERE column_name ="Product";
Nor create a procedure
delimiter //
CREATE PROCEDURE curdemo()
BEGIN
DECLARE a varchar(100);
DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE column_name ="Product";
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO a;
SELECT * FROM a;
END LOOP;
CLOSE cur1;
END;
delimiter ;
call curdemo();
I am using JavaScript but some of the principles are common I am sure.
The code I am using is as follows:
var s = new webdriver.ActionSequence(d);
d.findElement(By.className('fc-time')).then(function(result){
s.mouseMove(result,l).click().perform();
});
the driver = d
.
The location = l
is simply {x:300,y:500)
- it is just an offset.
What I found during my testing was that I could not make it work without using the method to find an existing element first, using that at a basis from where to locate my click.
I suspect the figures in the locate are a bit more difficult to predict than I thought.
It is an old post but this response may help other newcomers like me.
OpenId - Used only for Authentication.
OAuth - Used for both Authentication and Authorization. Authorization depends on the access_token which comes as part of JWT token. It can have details of user permissions or any useful information.
Both can rely on 3rd party auth provider which maintains their accounts. For example OKTA identity provider, User provides the credentials on OKTA login page and on successful login the user is redirected on the consumer application with the JWT token in the header.
Use the tee
command:
echo "hello" | tee logfile.txt
You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.
See example bellow
([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
_x000D_
<div id="test">_x000D_
<span>1</span>_x000D_
<span>2</span>_x000D_
<span>3</span>_x000D_
<span>4</span>_x000D_
<div>
_x000D_
You can use docker-compose run
instead of docker-compose up
and tack the arguments on the end. For example:
docker-compose run dperson/samba arg1 arg2 arg3
If you need to connect to other docker containers, use can use --service-ports
option:
docker-compose run --service-ports dperson/samba arg1 arg2 arg3
Perhaps this is what you are looking for:
import os
os.chdir(default_path)
You can implement a class that holds the fields you have in your JSON
class MyData
{
public string t;
public bool a;
public object[] data;
public string[][] type;
}
and then use the generic version of DeserializeObject:
MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
// Do something with typeStr
}
Documentation: Serializing and Deserializing JSON
use this command to check the possible output
mysql> select user,host,password from mysql.user;
output
mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user | host | password |
+-------+-----------------------+-------------------------------------------+
| root | localhost | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root | 127.0.0.1 | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | % | |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
Grant the user admin with password using GRANT command once again
mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
then check the GRANT LIST the out put will be like his
mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user | host | password |
+-------+-----------------------+-------------------------------------------+
| root | localhost | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root | 127.0.0.1 | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | % | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.
Now the user should be allowed to login.
In Jsp:
action="profile/proffiesional"
In Controller
@RequestMapping(value = "proffessional", method = RequestMethod.POST)
Spelling MisMatch !
Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)
I just removed the head portion in index.html file and it worked fine.This is the head tag in html file
Try std::find
vector<int>::iterator it = std::find(v.begin(), v.end(), 123);
if(it==v.end()){
std::cout<<"Element not found";
}
This is not necessarily a VBA task - This specific task is easiest sollowed with Auto filter.
1.Insert Auto filter (In Excel 2010 click on home-> (Editing) Sort & Filter -> Filter)
2. Filter on the 'Websites' column
3. Mark the 'none' and delete them
4. Clear filter
Combining a couple of the previous answers, you could try start /b cmd /c foo.exe
.
For a trivial example, if you wanted to print out the versions of java/groovy/grails/gradle, you could do this in a batch file:
@start /b cmd /c java -version
@start /b cmd /c gradle -version
@start /b cmd /c groovy -version
@start /b cmd /c grails -version
If you have something like Process Explorer (Sysinternals), you will see a few child cmd.exe processes each with a java process (as per the above commands). The output will print to the screen in whatever order they finish.
start /b : Start application without creating a new window. The
application has ^C handling ignored. Unless the application
enables ^C processing, ^Break is the only way to interrupt
the application
cmd /c : Carries out the command specified by string and then terminates
To declare a type variable property, mark the declaration with the
static
declaration modifier. Classes may mark type computed properties with theclass
declaration modifier instead to allow subclasses to override the superclass’s implementation. Type properties are discussed in Type Properties.NOTE
In a class declaration, the keywordstatic
has the same effect as marking the declaration with both theclass
andfinal
declaration modifiers.
Source: The Swift Programming Language - Type Variable Properties
select * from Header where userID like '%''%'
Hope this helps.
try it like this:
function popupwindow(url, title, w, h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
}
As the error message says in the last line: the module models
in the file c:\projects\mysite..\mysite\polls\models.py
contains no class model
. This error occurs in the definition of the Poll
class:
class Poll(models.model):
Either the class model
is misspelled in the definition of the class Poll
or it is misspelled in the module models
. Another possibility is that it is completely missing from the module models
. Maybe it is in another module or it is not yet implemented in models
.
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
Found this on HTML table: keep the same width for columns
If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .
I had the same issue every time I tried to create a new project, but based on the console output, it was because of two versions of android-support-v4 that were different:
[2014-10-29 16:31:57 - HeadphoneSplitter] Found 2 versions of android-support-v4.jar in the dependency list,
[2014-10-29 16:31:57 - HeadphoneSplitter] but not all the versions are identical (check is based on SHA-1 only at this time).
[2014-10-29 16:31:57 - HeadphoneSplitter] All versions of the libraries must be the same at this time.
[2014-10-29 16:31:57 - HeadphoneSplitter] Versions found are:
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\appcompat_v7\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter] Length: 627582
[2014-10-29 16:31:57 - HeadphoneSplitter] SHA-1: cb6883d96005bc85b3e868f204507ea5b4fa9bbf
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\HeadphoneSplitter\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter] Length: 758727
[2014-10-29 16:31:57 - HeadphoneSplitter] SHA-1: efec67655f6db90757faa37201efcee2a9ec3507
[2014-10-29 16:31:57 - HeadphoneSplitter] Jar mismatch! Fix your dependencies
I don't know a lot about Eclipse. but I simply deleted the copy of the jar file from my project's libs folder so that it would use the appcompat_v7 jar file instead. This fixed my issue.
I found an workaround on the web. I added to /etc/nginx/conf.d/default.conf the following:
location ~ \.css {
add_header Content-Type text/css;
}
location ~ \.js {
add_header Content-Type application/x-javascript;
}
The problem now is that a request to my css file isn't redirected well, as if root is not correctly set. In error.log I see
2012/04/11 14:01:23 [error] 7260#0: *2 open() "/etc/nginx//html/style.css"
So as a second workaround I added the root to each defined location. Now it works, but seems a little redundant. Isn't root inherited from / location ?
Your code looks correct. Try logging in through your browser and if you are able to access your account come back and try your code again. Just make sure that you have typed your username and password correct
EDIT: Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:
Go to this link and select Turn On
https://www.google.com/settings/security/lesssecureapps
system ('/usr/bin/pdfcrop filename.pdf');
Try this,
1. If you want to skip a particular iteration, use continue.
2. If you want to break out of the immediate loop use break
3 If there are 2 loop, outer and inner.... and you want to break out of both the loop from
the inner loop, use break with label.
eg:
continue
for(int i=0 ; i<5 ; i++){
if (i==2){
continue;
}
}
eg:
break
for(int i=0 ; i<5 ; i++){
if (i==2){
break;
}
}
eg:
break with label
lab1: for(int j=0 ; j<5 ; j++){
for(int i=0 ; i<5 ; i++){
if (i==2){
break lab1;
}
}
}
"??".encode('utf-8')
encode
converts a unicode object to a string
object. But here you have invoked it on a string
object (because you don't have the u). So python has to convert the string
to a unicode
object first. So it does the equivalent of
"??".decode().encode('utf-8')
But the decode fails because the string isn't valid ascii. That's why you get a complaint about not being able to decode.
Firstly, be sure where your python directory. It is normally in C:\Python27
. If yours is different then change it from the below command.
If after you install it python still isn’t recognized, then in PowerShell enter this:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27", "User")
Close PowerShell and then start it again to make sure Python now runs. If it doesn’t, restart may be required.
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
Other answers posted already may work equally well or better, but I haven't used them. However, the following SQL I have used, and it really helped me out when I was trying to reverse-engineer a big system with a huge (and very unorganzied) SQL Server database.
This isn't my code. I wish I could credit the original author, but I can't find the link to the article anymore :(
Use
go
declare @SearchChar varchar(8000)
Set @SearchChar = -- Like 'A%', '11/11/2006'
declare @CMDMain varchar(8000), @CMDMainCount varchar(8000),@CMDJoin varchar(8000)
declare @ColumnName varchar(100),@TableName varchar(100)
declare dbTable cursor for
SELECT
Distinct b.Name as TableName
FROM
sysobjects b
WHERE
b.type='u' and b.Name 'dtproperties'
order by b.name
open dbTable
fetch next from dbTable into @TableName
WHILE @@FETCH_STATUS = 0
BEGIN
declare db cursor for
SELECT
c.Name as ColumnName
FROM
sysobjects b,
syscolumns c
WHERE
C.id = b.id and
b.type='u' and b.Name = @TableName
order by b.name
open db
fetch next from db into @ColumnName
set @CMDMain = 'SELECT ' + char(39) + @TableName + char(39) + ' as TableName,'+
' ['+ @TableName + '].* FROM [' + @TableName + ']'+
' WHERE '
set @CMDMainCount = 'SELECT Count(*) FROM [' + @TableName + '] Where '
Set @CMDJoin = ''
WHILE @@FETCH_STATUS = 0
BEGIN
set @CMDJoin = @CMDJoin + 'Convert(varchar(5000),[' +@ColumnName + ']) like ' + char(39) + @SearchChar + char(39) + ' OR '
fetch next from db into @ColumnName
end
close db
deallocate db
Set @CMDMainCount = 'If ('+ @CMDMainCount + Left(@CMDJoin, len(@CMDJoin) - 3)+ ') > 0 Begin '
Set @CMDMain = @CMDMainCount + @CMDMain + Left(@CMDJoin, len(@CMDJoin) - 3)
Set @CMDMain = @CMDMain + ' End '
Print @CMDMain
exec (@CMDMain)
fetch next from dbTable into @TableName
end
close dbTable
deallocate dbTable
The date function would be defined something like this:
function date($format, $timestamp = null)
{
if ($timestamp === null) {
$timestamp = time();
}
// Format the timestamp according to $format
}
Usually, you would put the default value like this:
function foo($required, $optional = 42)
{
// This function can be passed one or more arguments
}
However, only literals are valid default arguments, which is why I used null
as default argument in the first example, not $timestamp = time()
, and combined it with a null check. Literals include arrays (array()
or []
), booleans, numbers, strings, and null
.
You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.
I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.
var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");
var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");
linkDeleter.appendChild(imgDeleter);
The answer to "Should I test private methods?" is ".......sometimes". Typically you should be testing against the interface of your classes.
Here is an example:
class Thing
def some_string
one + two
end
private
def one
'aaaa'
end
def two
'bbbb'
end
end
class RefactoredThing
def some_string
one + one_a + two + two_b
end
private
def one
'aa'
end
def one_a
'aa'
end
def two
'bb'
end
def two_b
'bb'
end
end
In RefactoredThing
you now have 5 tests, 2 of which you had to update for refactoring, but your object's functionality really hasn't changed. So let's say that things are more complex than that and you have some method that defines the order of the output such as:
def some_string_positioner
if some case
elsif other case
elsif other case
elsif other case
else one more case
end
end
This shouldn't be run by an outside user, but your encapsulating class may be to heavy to run that much logic through it over and over again. In this case maybe you would rather extract this into a seperate class, give that class an interface and test against it.
And finally, let's say that your main object is super heavy, and the method is quite small and you really need to ensure that the output is correct. You are thinking, "I have to test this private method!". Have you that maybe you can make your object lighter by passing in some of the heavy work as an initialization parameter? Then you can pass something lighter in and test against that.
Use acra crash reporter for android app..Acra lib
Go File > Invalidate Caches / Restart... > Click at Invalidate and Restart
This really works for me. source: https://code.google.com/p/android/issues/detail?id=61844#c4
I had exactly the same problem with you. And after two days wondering why this occurs to me, I finally got through this by moving the adb.exe from the unreliable software list of the COMODO anti-virus to its reliable software list. At that time, I had tried at least 5 kinds of measures to make the adb work, including all above...
Maybe you can try this: though please note - This pulls the column count, not the row count
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
int count = reader.VisibleFieldCount;
Console.WriteLine(count);
}
}
in ubuntu or windows
path php.ini
Remove the ; from ;extension=pdo_mysql or extension=php_pdo_mysql.dll and add extension=pdo_mysql.so
restart xampp or wampp
install sudo apt-get install php-mysql
and
php artisan migrate
dear friend, Jon Skeet said you can find character Decimal codebut it is not character Hex code as it should mention in unicode, so you should represent character codes via HexCode not in Deciaml.
there is an open source tool at http://unicode.codeplex.com that provides complete information about a characer or a sentece.
so it is better to create a parser that give a char as a parameter and return ahexCode as string
public static String GetHexCode(char character)
{
return String.format("{0:X4}", GetDecimal(character));
}//end
hope it help
Use DATESTR
>> datestr(40189)
ans =
12-Jan-0110
Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM
>> datenum(2010,1,11)
ans =
734149
>> datenum(2010,1,11)-40189
ans =
693960
>> datestr(40189+693960)
ans =
11-Jan-2010
In other words, to convert any serial Excel date, call
datestr(excelSerialDate + 693960)
EDIT
To get the date in mm/dd/yyyy format, call datestr
with the specified format
excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010
Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things
excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010
Here's an example if:
ifeq ($(strip $(OS)),Linux)
PYTHON = /usr/bin/python
FIND = /usr/bin/find
endif
Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.
Locate the file at /etc/mysql/my.cnf
Edit the file by adding the following lines:
[mysqld]
lower_case_table_names=1
sudo /etc/init.d/mysql restart
Run mysqladmin -u root -p variables | grep table
to check that lower_case_table_names
is 1
now
You might need to recreate these tables to make it work.
basically:
using System.Net;
using System.Net.Http; // in LINQPad, also add a reference to System.Net.Http.dll
WebRequest req = HttpWebRequest.Create("http://google.com");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
Console.WriteLine(source);
SQLFiddle will let you test out your queries, while it doesn't explicitly correct syntax etc. per se it does let you play around with the script and will definitely let you know if things are working or not.
This is what you really want.
<Button
android:id="@+id/settings"
android:layout_width="190dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@color/colorAccent"
android:drawableStart="@drawable/ic_settings_black_24dp"
android:paddingStart="40dp"
android:paddingEnd="40dp"
android:text="settings"
android:textColor="#FFF" />
You can use wget
command to download the page and read it into a variable as:
content=$(wget google.com -q -O -)
echo $content
We use the -O
option of wget
which allows us to specify the name of the file into which wget
dumps the page contents. We specify -
to get the dump onto standard output and collect that into the variable content
. You can add the -q
quiet option to turn off's wget output.
You can use the curl command for this aswell as:
content=$(curl -L google.com)
echo $content
We need to use the -L
option as the page we are requesting might have moved. In which case we need to get the page from the new location. The -L
or --location
option helps us with this.
If you want to start at the "application root" as you describe right click on the top level Default.aspx page and choose set as start page. Hit F5 and you're done.
If you want to start at a different controller action see Mark's answer.
Why not just use a custom format for the cell you need to quote?
If you set a custom format to the cell column, all values will take on that format.
For numbers....like a zip code....it would be this '#' For string text, it would be this '@'
You save the file as csv format, and it will have all the quotes wrapped around the cell data as needed.
This worked for me using ssh:
Settings → Developer settings → Generate new token.
git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git
If you like to have the modal fade in rather than slide in (why is it called .fade
anyway?) you can overwrite the class in your CSS file or directly in bootstrap.css
with this:
.modal.fade{
-webkit-transition: opacity .2s linear, none;
-moz-transition: opacity .2s linear, none;
-ms-transition: opacity .2s linear, none;
-o-transition: opacity .2s linear, none;
transition: opacity .2s linear, none;
top: 50%;
}
If you don't want any effect just remove the fade
class from the modal classes.
On the following option:
WebElement option = select.getFirstSelectedOption();
option.getText();
If from the method getText()
you get a blank, you can get the string from the value of the option using the method getAttribute
:
WebElement option = select.getFirstSelectedOption();
option.getAttribute("value");
try with this
$ cat /tmp/topfs.txt
/dev/sda2 xfs 32G 10G 22G 32% /
awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'
awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%
awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /
This thread was invaluable to figure out how to generate a binary file and prompt to download the named file, all in client code without a server.
First step for me was generating the binary blob from data that I was saving. There's plenty of samples for doing this for a single binary type, in my case I have a binary format with multiple types which you can pass as an array to create the blob.
saveAnimation: function() {
var device = this.Device;
var maxRow = ChromaAnimation.getMaxRow(device);
var maxColumn = ChromaAnimation.getMaxColumn(device);
var frames = this.Frames;
var frameCount = frames.length;
var writeArrays = [];
var writeArray = new Uint32Array(1);
var version = 1;
writeArray[0] = version;
writeArrays.push(writeArray.buffer);
//console.log('version:', version);
var writeArray = new Uint8Array(1);
var deviceType = this.DeviceType;
writeArray[0] = deviceType;
writeArrays.push(writeArray.buffer);
//console.log('deviceType:', deviceType);
var writeArray = new Uint8Array(1);
writeArray[0] = device;
writeArrays.push(writeArray.buffer);
//console.log('device:', device);
var writeArray = new Uint32Array(1);
writeArray[0] = frameCount;
writeArrays.push(writeArray.buffer);
//console.log('frameCount:', frameCount);
for (var index = 0; index < frameCount; ++index) {
var frame = frames[index];
var writeArray = new Float32Array(1);
var duration = frame.Duration;
if (duration < 0.033) {
duration = 0.033;
}
writeArray[0] = duration;
writeArrays.push(writeArray.buffer);
//console.log('Frame', index, 'duration', duration);
var writeArray = new Uint32Array(maxRow * maxColumn);
for (var i = 0; i < maxRow; ++i) {
for (var j = 0; j < maxColumn; ++j) {
var color = frame.Colors[i][j];
writeArray[i * maxColumn + j] = color;
}
}
writeArrays.push(writeArray.buffer);
}
var blob = new Blob(writeArrays, {type: 'application/octet-stream'});
return blob;
}
The next step is to get the browser to prompt the user to download this blob with a predefined name.
All I needed was a named link I added in the HTML5 that I could reuse to rename the initial filename. I kept it hidden since the link doesn't need display.
<a id="lnkDownload" style="display: none" download="client.chroma" href="" target="_blank"></a>
The last step is to prompt the user to download the file.
var data = animation.saveAnimation();
var uriContent = URL.createObjectURL(data);
var lnkDownload = document.getElementById('lnkDownload');
lnkDownload.download = 'theDefaultFileName.extension';
lnkDownload.href = uriContent;
lnkDownload.click();
When you use lazy load you need to delete your component's module and routing module from app module. If you don't, it'll try to load them when app started and throws that error.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule,
// YourComponentModule,
// YourComponentRoutingModule
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
After trying some answers and comments here, I finally found a solution! In this article The correct way to configure PHP I find a new way to configure PHP as a module in Apache.
For the author of this article, the official way to configure PHP is not the most optimal. The common and inappropriate way to configure PHP is this one:
# For PHP 5:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php
PHPIniDir "C:/php"
I've always done it this way, but in the article, it's suggested to configure the PHP module this way:
#For PHP5
LoadFile "C:/www/php5/php5ts.dll"
LoadModule php5_module "C:/www/php5/php5apache2.dll"
<IfModule php5_module>
#PHPIniDir "C:/Windows"
#PHPIniDir "C:/Winnt"
<Location />
AddType text/html .php .phps
AddHandler application/x-httpd-php .php
AddHandler application/x-httpd-php-source .phps
</Location>
</IfModule>
I even have IPV6 enabled, and my loading time drop down from 45 secs or 1 minute or more, to just 2 or 4 seconds! Thanks to other answers mentioned here, I also left enabled in my general configuration the following
HOST FILE:
127.0.0.1 localhost
127.0.0.1 127.0.0.1
# ::1 localhost
HTTPD.CONF
EnableMMAP on
EnableSendfile on
AcceptFilter http none
AcceptFilter https none
HostnameLookups Off
Other than that, I rolled back all other solutions I tried, so I'm sure this is the only ones that I used.
mkdir ~/bin
PATH=~/bin:$PATH
ln -s /usr/bin/python2 ~/bin/python
To stop using python2, exit
or rm ~/bin/python
.
My personal favorite, and easier than the answers I have seen here (for multiple columns):
df.drop(df.columns[22:56], axis=1, inplace=True)
You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm
Have a look and check the differences. specially the even_id in :
<set name="attendees" cascade="all">
<key column="event_id"/>
<one-to-many class="Attendee"/>
</set>
You're probably better off comparing the fields individually, rather than concatenating the strings.
SELECT t1.*
FROM Table1 t1
LEFT JOIN Table2 t2
ON t1.MAKE = t2.MAKE
AND t1.MODEL = t2.MODEL
AND t1.[serial number] = t2.[serial number]
WHERE t2.MAKE IS NULL
android developers documentation says : "Updated the AppCompatActivity as the base class for activities that use the support library action bar features. This class replaces the deprecated ActionBarActivity."
checkout changes for Android Support Library, revision 22.1.0 (April 2015)
This is just an updated version of Jesse Webbs code that doesn't append the unnecessary trailing ,
character.
public static string PrintBytes(this byte[] byteArray)
{
var sb = new StringBuilder("new byte[] { ");
for(var i = 0; i < byteArray.Length;i++)
{
var b = byteArray[i];
sb.Append(b);
if (i < byteArray.Length -1)
{
sb.Append(", ");
}
}
sb.Append(" }");
return sb.ToString();
}
The output from this method would be:
new byte[] { 48, ... 135, 31, 178, 7, 157 }
As others have already pointed out, Python includes a module to read and write CSV files. It works pretty well as long as the input characters stay within ASCII limits. In case you want to process other encodings, more work is needed.
The Python documentation for the csv module implements an extension of csv.reader, which uses the same interface but can handle other encodings and returns unicode strings. Just copy and paste the code from the documentation. After that, you can process a CSV file like this:
with open("some.csv", "rb") as csvFile:
for row in UnicodeReader(csvFile, encoding="iso-8859-15"):
print row
There's another, simpler way to do this:
npm install Node@8
(saves Node 8 as dependency in package.json)This works because node
is just a package that ships node as its package binary. It just includes as node_module/.bin which means it only makes node available to package scripts. Not main shell.
See discussion on Twitter here: https://twitter.com/housecor/status/962347301456015360
In February of 2020, Google announced a major upgrade to the built-in Google Apps Script IDE, and it now supports console.log(). So, you can now use both:
Happy coding!
Everyone knows (hopefully) its bad to terminate thread. The problem is when you don't own a piece of code you're calling. If this code is running in some do/while infinite loop , itself calling some native functions, etc. you're basically stuck. When this happens in your own code termination, stop or Dispose call, it's kinda ok to start shooting the bad guys (so you don't become a bad guy yourself).
So, for what it's worth, I've written those two blocking functions that use their own native thread, not a thread from the pool or some thread created by the CLR. They will stop the thread if a timeout occurs:
// returns true if the call went to completion successfully, false otherwise
public static bool RunWithAbort(this Action action, int milliseconds) => RunWithAbort(action, new TimeSpan(0, 0, 0, 0, milliseconds));
public static bool RunWithAbort(this Action action, TimeSpan delay)
{
if (action == null)
throw new ArgumentNullException(nameof(action));
var source = new CancellationTokenSource(delay);
var success = false;
var handle = IntPtr.Zero;
var fn = new Action(() =>
{
using (source.Token.Register(() => TerminateThread(handle, 0)))
{
action();
success = true;
}
});
handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
CloseHandle(handle);
return success;
}
// returns what's the function should return if the call went to completion successfully, default(T) otherwise
public static T RunWithAbort<T>(this Func<T> func, int milliseconds) => RunWithAbort(func, new TimeSpan(0, 0, 0, 0, milliseconds));
public static T RunWithAbort<T>(this Func<T> func, TimeSpan delay)
{
if (func == null)
throw new ArgumentNullException(nameof(func));
var source = new CancellationTokenSource(delay);
var item = default(T);
var handle = IntPtr.Zero;
var fn = new Action(() =>
{
using (source.Token.Register(() => TerminateThread(handle, 0)))
{
item = func();
}
});
handle = CreateThread(IntPtr.Zero, IntPtr.Zero, fn, IntPtr.Zero, 0, out var id);
WaitForSingleObject(handle, 100 + (int)delay.TotalMilliseconds);
CloseHandle(handle);
return item;
}
[DllImport("kernel32")]
private static extern bool TerminateThread(IntPtr hThread, int dwExitCode);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(IntPtr lpThreadAttributes, IntPtr dwStackSize, Delegate lpStartAddress, IntPtr lpParameter, int dwCreationFlags, out int lpThreadId);
[DllImport("kernel32")]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32")]
private static extern int WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);
For those who use Angular
, there's a package called angular-pipes
that has a pipe for this:
File
import { BytesPipe } from 'angular-pipes';
Usage
{{ 150 | bytes }} <!-- 150 B -->
{{ 1024 | bytes }} <!-- 1 KB -->
{{ 1048576 | bytes }} <!-- 1 MB -->
{{ 1024 | bytes: 0 : 'KB' }} <!-- 1 MB -->
{{ 1073741824 | bytes }} <!-- 1 GB -->
{{ 1099511627776 | bytes }} <!-- 1 TB -->
{{ 1073741824 | bytes : 0 : 'B' : 'MB' }} <!-- 1024 MB -->
You can use your own customize class based on the concept, here the code snippet which you can use to do the stuff
/*
* Stack implementation in JavaScript
*/
function Stack() {
this.top = null;
this.count = 0;
this.getCount = function() {
return this.count;
}
this.getTop = function() {
return this.top;
}
this.push = function(data) {
var node = {
data: data,
next: null
}
node.next = this.top;
this.top = node;
this.count++;
}
this.peek = function() {
if (this.top === null) {
return null;
} else {
return this.top.data;
}
}
this.pop = function() {
if (this.top === null) {
return null;
} else {
var out = this.top;
this.top = this.top.next;
if (this.count > 0) {
this.count--;
}
return out.data;
}
}
this.displayAll = function() {
if (this.top === null) {
return null;
} else {
var arr = new Array();
var current = this.top;
//console.log(current);
for (var i = 0; i < this.count; i++) {
arr[i] = current.data;
current = current.next;
}
return arr;
}
}
}
and to check this use your console and try these line one by one.
>> var st = new Stack();
>> st.push("BP");
>> st.push("NK");
>> st.getTop();
>> st.getCount();
>> st.displayAll();
>> st.pop();
>> st.displayAll();
>> st.getTop();
>> st.peek();
I recommend you exit the Python interpreter with Ctrl-D. This is the old ASCII code for end-of-file or end-of-transmission.
Every answer currently responding to this question tells you that the O(1)
means constant time (whatever it happens to measuring; could be runtime, number of operations, etc.). This is not accurate.
To say that runtime is O(1)
means that there is a constant c
such that the runtime is bounded above by c
, independent of the input. For example, returning the first element of an array of n
integers is O(1)
:
int firstElement(int *a, int n) {
return a[0];
}
But this function is O(1)
too:
int identity(int i) {
if(i == 0) {
sleep(60 * 60 * 24 * 365);
}
return i;
}
The runtime here is bounded above by 1 year, but most of the time the runtime is on the order of nanoseconds.
To say that runtime is O(n)
means that there is a constant c
such that the runtime is bounded above by c * n
, where n
measures the size of the input. For example, finding the number of occurrences of a particular integer in an unsorted array of n
integers by the following algorithm is O(n)
:
int count(int *a, int n, int item) {
int c = 0;
for(int i = 0; i < n; i++) {
if(a[i] == item) c++;
}
return c;
}
This is because we have to iterate through the array inspecting each element one at a time.
Check that All Files are Included in Your Project:
I had this same error pop up after I updated cLion. After hours of tinkering, I noticed one of my files was not included in the project target. After I added it back to the active project, I stopped getting the undefined reference to winmain16, and the code compiled.
Edit: It's also worthwhile to check the build settings within your IDE.
(Not sure if this error is related to having recently updated the IDE - could be causal or simply correlative. Feel free to comment with any insight on that factor!)
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
TreeSize professional has what you want. but it focus on the sizes of folders and files.
Problem: (Sql server 2014) This issue happens when assembly Microsoft.SqlServer.management.sdk.sfc version 12.0.0.0
not found by visual studio.
Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=42295 and download:
ENU\x64\SharedManagementObjects.msi
for X64 OS orENU\x86\SharedManagementObjects.msi
for X86 OS, then install it, and restart visual studio.
PS: You may need install DB2OLEDBV5_x64.msi
or DB2OLEDBV5_x86.msi
too.
Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0
not found by visual studio.
Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=35580 and download:
ENU\x64\SharedManagementObjects.msi
for X64 OS orENU\x86\SharedManagementObjects.msi
for X86 OS, then install it, and restart visual studio.
Microsoft.SqlServer.management.sdk.sfc version 10.0.0.0
not found by visual studio.
Solution: just go to http://www.microsoft.com/en-us/download/details.aspx?id=26728 and download:
1033\x64\SharedManagementObjects.msi
for X64 OS or1033\x86\SharedManagementObjects.msi
for X86 OS, (In most cases downloading this is better http://go.microsoft.com/fwlink/?LinkId=123708&clcid=0x409)
then install it, and restart visual studio.
Microsoft.SqlServer.ConnectionInfo, Version=12.0.0.0
not found by visual studio. The problem was Visual C++ Redistributable Packages for Visual Studio was not installed yet.
Solution: for Visual Studio 2013 just go to http://www.microsoft.com/en-us/download/details.aspx?id=40784 and download:
vcredist_x64.exe
for X64 OS orvcredist_x86.exe
for X86 OS, then install it, and restart visual studio.
PS: You can find Visual C++ Redistributable Packages for Visual Studio 20XX for other versions of Visual Studio easily by googling it.
Dirty; maybe could you just add a min-height: 100%; to the html, and body tags? That or at least set a default background color that is the end gradient color as well.
The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.
For example:
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
What's about Java code wrapped by a procedure? Simple and works fine.
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED SNOOZE AS
public final class Snooze {
private Snooze() {
}
public static void snooze(Long milliseconds) throws InterruptedException {
Thread.sleep(milliseconds);
}
}
CREATE OR REPLACE PROCEDURE SNOOZE(p_Milliseconds IN NUMBER) AS
LANGUAGE JAVA NAME 'Snooze.snooze(java.lang.Long)';
Generally speaking:
all
and any
are functions that take some iterable and return True
, if
all()
, no values in the iterable are falsy;any()
, at least one value is truthy.A value x
is falsy iff bool(x) == False
.
A value x
is truthy iff bool(x) == True
.
Any non-booleans in the iterable will be fine — bool(x)
will coerce any x
according to these rules: 0
, 0.0
, None
, []
, ()
, []
, set()
, and other empty collections will yield False
, anything else True
. The docstring for bool
uses the terms 'true'/'false' for 'truthy'/'falsy', and True
/False
for the concrete boolean values.
In your specific code samples:
You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:
if any(foobars) == big_foobar:
...because any(foobars)
would first be evaluated to either True
or False
, and then that boolean value would be compared to big_foobar
, which generally always gives you False
(unless big_foobar
coincidentally happened to be the same boolean value).
Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.
What you want instead is:
if any(x == big_foobar for x in foobars):
which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars
, it compares the item to big_foobar
and emits the resulting boolean into the resulting sequence:
tmp = (x == big_foobar for x in foobars)
then any
walks over all items in tmp
and returns True
as soon as it finds the first truthy element. It's as if you did the following:
In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']
In [2]: big_foobar = 'big'
In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])
Out[3]: True
Note: As DSM pointed out, any(x == y for x in xs)
is equivalent to y in xs
but the latter is more readable, quicker to write and runs faster.
Some examples:
In [1]: any(x > 5 for x in range(4))
Out[1]: False
In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True
In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True
In [4]: all([True, True, True, False, True])
Out[4]: False
See also: http://docs.python.org/2/library/functions.html#all
It sounds like you have a form tag in a Master Page and in the Page that is throwing the error.
You can have only one.
I would bind two different getters/setters pair to one variable:
class Coordinates{
int red;
@JsonProperty("red")
public byte getRed() {
return red;
}
public void setRed(byte red) {
this.red = red;
}
@JsonProperty("r")
public byte getR() {
return red;
}
public void setR(byte red) {
this.red = red;
}
}
Any checkout of a commit that is not the name of one of your branches will get you a detached HEAD. A SHA1 which represents the tip of a branch still gives a detached HEAD. Only a checkout of a local branch name avoids that mode.
See committing with a detached HEAD
When HEAD is detached, commits work like normal, except no named branch gets updated. (You can think of this as an anonymous branch.)
For example, if you checkout a "remote branch" without tracking it first, you can end up with a detached HEAD.
See git: switch branch without detaching head
Meaning: git checkout origin/main
(or origin/master
in the old days) would result in:
Note: switching to 'origin/main'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:
git switch -c <new-branch-name>
Or undo this operation with:
git switch -
Turn off this advice by setting config variable advice.detachedHead to false
HEAD is now at a1b2c3d My commit message
That is why you should not use git checkout
anymore, but the new git switch
command.
With git switch
, the same attempt to "checkout" (switch to) a remote branch would fail immediately:
git switch origin/main
fatal: a branch is expected, got remote branch 'origin/main'
To add more on git switch
:
With Git 2.23 (August 2019), you don't have to use the confusing git checkout
command anymore.
git switch
can also checkout a branch, and get a detach HEAD, except:
--detach
optionTo check out commit
HEAD~3
for temporary inspection or experiment without creating a new branch:git switch --detach HEAD~3 HEAD is now at 9fc9555312 Merge branch 'cc/shared-index-permbits'
See:
C:\Users\vonc\arepo>git checkout origin/master
Note: switching to 'origin/master'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.
Vs. using the new git switch
command:
C:\Users\vonc\arepo>git switch origin/master
fatal: a branch is expected, got remote branch 'origin/master'
If you wanted to create a new local branch tracking a remote branch:
git switch <branch>
If
<branch>
is not found but there does exist a tracking branch in exactly one remote (call it<remote>
) with a matching name, treat as equivalent togit switch -c <branch> --track <remote>/<branch>
No more mistake!
No more unwanted detached HEAD!
You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h
only for the _TCHAR
macro.
Then, precompiled header is usually a per-project file in Visual Studio world, so:
#include <stdafx.h>
to #include "stdafx.h"
. It is supposed to be a project local file, not to be resolved in include directories.Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h
.
There's a difference between additive colors (http://en.wikipedia.org/wiki/Additive_color) and subtractive colors (http://en.wikipedia.org/wiki/Subtractive_color).
With additive colors, the more you add, the brighter the colors become. This is because they are emitting light. This is why the day light is (more or less) white, since the Sun is emitting in almost all the visible wavelength spectrum.
On the other hand, with subtractive colors the more colors you mix, the darker the resulting color. This is because they are reflecting light. This is also why the black colors get hotter quickly, because it absorbs (almost) all light energy and reflects (almost) none.
Specifically to your question, it depends what medium you are working on. Traditionally, additive colors (RGB) are used because the canon for computer graphics was the computer monitor, and since it's emitting light, it makes sense to use the same structure for the graphic card (the colors are shown without conversions). However, if you are used to graphic arts and press, subtractive color model is used (CMYK). In programs such as Photoshop, you can choose to work in CMYK space although it doesn't matter what color model you use: the primary colors of one group are the secondary colors of the second one and viceversa.
P.D.: my father worked at graphic arts, this is why i know this... :-P
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
I have created a pub-sub sample here:
http://www.syntaxsuccess.com/viewarticle/pub-sub-in-angular-2.0
The idea is to use RxJs Subjects to wire up an Observer and and Observables as a generic solution for emitting and subscribing to custom events. In my sample I use a customer object for demo purposes
this.pubSubService.Stream.emit(customer);
this.pubSubService.Stream.subscribe(customer => this.processCustomer(customer));
Here is a live demo as well: http://www.syntaxsuccess.com/angular-2-samples/#/demo/pub-sub
If you're using docker-machine, the virtual machines can drift. To update the clock on the virtual machine without restarting run:
docker-machine ssh <machine-name|default>
sudo ntpclient -s -h pool.ntp.org
This will update the clock on the virtual machine using NTP and then all the containers launched will have the correct date.
Below is an alternative implementation of a 'create user' controller method using Claims based roles.
The created claims then work with the Authorize attribute e.g. [Authorize(Roles = "Admin, User.*, User.Create")]
// POST api/User/Create
[Route("Create")]
public async Task<IHttpActionResult> Create([FromBody]CreateUserModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Generate long password for the user
var password = System.Web.Security.Membership.GeneratePassword(25, 5);
// Create the user
var user = new ApiUser() { UserName = model.UserName };
var result = await UserManager.CreateAsync(user, password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
// Add roles (permissions) for the user
foreach (var perm in model.Permissions)
{
await UserManager.AddClaimAsync(user.Id, new Claim(ClaimTypes.Role, perm));
}
return Ok<object>(new { UserName = user.UserName, Password = password });
}
try this
describe table columnname
gives you all the information about that column in that table;
Use -1
index (negative indices count backward from the end of the array):
a[-1] # => 5
b[-1] # => 6
or Array#last
method:
a.last # => 5
b.last # => 6
I think the best option is to use guide_legend
within guides
:
p + guides(fill=guide_legend(
keywidth=0.1,
keyheight=0.1,
default.unit="inch")
)
Note the use of default.unit
, no need to load grid
package.
I've had the same error and I solve it with: git merge -s recursive -X theirs origin/master
NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor
of the TextBox
.
I think what you really want to do is enable the TextBox
and set the ReadOnly
property to true
.
It's a bit tricky to change the color of the text in a disabled TextBox
. I think you'd probably have to subclass and override the OnPaint
event.
ReadOnly
though should give you the same result as !Enabled
and allow you to maintain control of the color and formatting of the TextBox
. I think it will also still support selecting and copying text from the TextBox
which is not possible with a disabled TextBox
.
Another simple alternative is to use a Label
instead of a TextBox
.
Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim
(no syntax highlighting):
\documentclass{article}
\usepackage{spverbatim}
\begin{document}
\begin{spverbatim}
Your code here
\end{spverbatim}
\end{document}
Also, if syntax highlighting is not required, package alltt
:
\documentclass{article}
\usepackage{alltt}
\begin{document}
\begin{alltt}
Your code here
\end{alltt}
\end{document}
The below code reads a file, converts it to a byte array and then makes a request to the server.
public void PostImage()
{
HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();
byte[] imagebytearraystring = ImageFileToByteArray(@"C:\Users\Downloads\icon.png");
form.Add(new ByteArrayContent(imagebytearraystring, 0, imagebytearraystring.Count()), "profile_pic", "hello1.jpg");
HttpResponseMessage response = httpClient.PostAsync("your url", form).Result;
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
}
private byte[] ImageFileToByteArray(string fullFilePath)
{
FileStream fs = File.OpenRead(fullFilePath);
byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, Convert.ToInt32(fs.Length));
fs.Close();
return bytes;
}
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
Example code:
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
I use this way in work life: "Forget common loops" in this case and use this combination of "setInterval" includes "setTimeOut"s:
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
Could anybody post a working solution for doing this in the terminal?
ANDROID_HOME
is usually a directory like .android
. Its where things like the Debug Key will be stored.
export ANDROID_HOME=~/.android
You can automate it for your login. Just add it to your .bash_profile
(below is from my OS X 10.8.5 machine):
$ cat ~/.bash_profile
# MacPorts Installer addition on 2012-07-19 at 20:21:05
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
# Android
export ANDROID_NDK_ROOT=/opt/android-ndk-r9
export ANDROID_SDK_ROOT=/opt/android-sdk
export JAVA_HOME=`/usr/libexec/java_home`
export ANDROID_HOME=~/.android
export PATH="$ANDROID_SDK_ROOT/tools/":"$ANDROID_SDK_ROOT/platform-tools/":"$PATH"
According to David Turner on the NDK Mailing List, both ANDROID_NDK_ROOT
and ANDROID_SDK_ROOT
need to be set because other tools depend on those values (see Recommended NDK Directory?).
After modifying ~/.bash_profile
, then perform the following (or logoff and back on):
source ~/.bash_profile
If you are using vue2-google-maps like me, the code to set the size looks like this:
<gmap-marker
..
:icon="{
..
anchor: { x: iconSize, y: iconSize },
scaledSize: { height: iconSize, width: iconSize },
}"
>
Use the ListView.ItemContainerStyle property to give your ListViewItems an EventSetter that will handle the PreviewMouseLeftButtonDown event. Then, in the handler, check to see if the item that was clicked is selected.
XAML:
<ListView ItemsSource={Binding MyItems}>
<ListView.View>
<GridView>
<!-- declare a GridViewColumn for each property -->
</GridView>
</ListView.View>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
Code-behind:
private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var item = sender as ListViewItem;
if (item != null && item.IsSelected)
{
//Do your stuff
}
}
And yet another approach using the decorator pattern and PHPs magic getter & setters:
// A simple StdClass object
$stdclass = new StdClass();
$stdclass->foo = 'bar';
// Decorator base class to inherit from
class Decorator {
protected $object = NULL;
public function __construct($object)
{
$this->object = $object;
}
public function __get($property_name)
{
return $this->object->$property_name;
}
public function __set($property_name, $value)
{
$this->object->$property_name = $value;
}
}
class MyClass extends Decorator {}
$myclass = new MyClass($stdclass)
// Use the decorated object in any type-hinted function/method
function test(MyClass $object) {
echo $object->foo . '<br>';
$object->foo = 'baz';
echo $object->foo;
}
test($myclass);
When I have a Store Procedure name, and do not know which database it belongs to, I use the following -
Use [master]
GO
DECLARE @dbname VARCHAR(50)
DECLARE @statement NVARCHAR(max)
DECLARE db_cursor CURSOR
LOCAL FAST_FORWARD
FOR
--Status 48 (mirrored db)
SELECT name FROM MASTER.dbo.sysdatabases WHERE STATUS NOT LIKE 48 AND name NOT IN ('master','model','msdb','tempdb','distribution')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @statement = 'SELECT * FROM ['+@dbname+'].INFORMATION_SCHEMA.ROUTINES WHERE [ROUTINE_NAME] LIKE ''%name_of_proc%'''+';'
print @statement
EXEC sp_executesql @statement
FETCH NEXT FROM db_cursor INTO @dbname
END
CLOSE db_cursor
DEALLOCATE db_cursor
add this to your stylesheet. line-height should match the height of your logo
.navbar-nav li a {
line-height: 50px;
}
Check out the fiddle at: http://jsfiddle.net/nD4tW/
In [5]:
import pandas as pd
test = {
383: 3.000000,
663: 1.000000,
726: 1.000000,
737: 9.000000,
833: 8.166667
}
s = pd.Series(test)
s = s[s != 1]
s
Out[0]:
383 3.000000
737 9.000000
833 8.166667
dtype: float64
add colors in color.xml file and then add this line of code...
floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(R.color.fab2_color)));
I simplification for Science_Fiction's answer I think is to use the exclusive or function so you can just have:
if(checkbox1.checked ^ checkbox2.checked)
{
//do stuff
}
That is assuming you want to do the same thing for both situations.
os.path.exists
returns True
for folders as well as files. Consider using os.path.isfile
to check for whether the file exists instead.
Using JavaScript
public ActionResult Index()
{
return Content("<script>window.location = 'http://www.example.com';</script>");
}
Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.
Hope this helps.
Assuming a
is a string. The Slice notation in python has the syntax -
list[<start>:<stop>:<step>]
So, when you do a[::-1]
, it starts from the end towards the first taking each element. So it reverses a. This is applicable for lists/tuples as well.
Example -
>>> a = '1234'
>>> a[::-1]
'4321'
Then you convert it to int and then back to string (Though not sure why you do that) , that just gives you back the string.
def grade(inlist):
grade_1, grade_2, grade_3, average =inlist
print (grade_1)
print (grade_2)
mark=[1,2,3,4]
grade(mark)
The correct way to insert something (in Oracle) based on another record already existing is by using the MERGE statement.
Please note that this question has already been answered here on SO:
<input class="form-control search-query input_style" placeholder="Search…" name="" title="Search for:" type="text">
.input_style
{
padding-left:20px;
}
express-error-handler lets you specify custom templates, static pages, or error handlers for your errors. It also does other useful error-handling things that every app should implement, like protect against 4xx error DOS attacks, and graceful shutdown on unrecoverable errors. Here's how you do what you're asking for:
var errorHandler = require('express-error-handler'),
handler = errorHandler({
static: {
'404': 'path/to/static/404.html'
}
});
// After all your routes...
// Pass a 404 into next(err)
app.use( errorHandler.httpError(404) );
// Handle all unhandled errors:
app.use( handler );
Or for a custom handler:
handler = errorHandler({
handlers: {
'404': function err404() {
// do some custom thing here...
}
}
});
Or for a custom view:
handler = errorHandler({
views: {
'404': '404.jade'
}
});
I would use an intermediary object (itemsMap
), thus avoiding quadratic complexity:
function createItemsMap(itemsArray) { // {"a": ["Anne"], "b": ["Bob", "Henry"], …}
var itemsMap = {};
for (var i = 0, item; (item = itemsArray[i]); ++i) {
(itemsMap[item[1]] || (itemsMap[item[1]] = [])).push(item[0]);
}
return itemsMap;
}
function sortByKeys(itemsArray, sortingArr) {
var itemsMap = createItemsMap(itemsArray), result = [];
for (var i = 0; i < sortingArr.length; ++i) {
var key = sortingArr[i];
result.push([itemsMap[key].shift(), key]);
}
return result;
}
('very long string'.slice(0,10))+'...'
// "very long ..."
Had a similar issue when working with RN components in my Android project and the only way to get around this issue was to ignore the gradle project.
To do this:
No idea what causes this but I've had this happen to me when using React Native Maps.
Note: If you're still having issues following this. Try to refresh the gradle project which was causing issues.
Otro example, custom Data Pagination for JOIN
CODE in Controller CakePHP 2.6 is OK:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
'conditions'=>array(
'Clientes.requiere_senasa'=>1
),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
OR Example 2, NOT active conditions:
$this->SenasaPedidosFacturadosSds->recursive = -1;
// Filtro
$where = array(
'joins' => array(
array(
'table' => 'usuarios',
'alias' => 'Usuarios',
'type' => 'INNER',
'conditions' => array(
'Usuarios.usuario_id = SenasaPedidosFacturadosSds.usuarios_id'
)
),
array(
'table' => 'senasa_pedidos',
'alias' => 'SenasaPedidos',
'type' => 'INNER',
'conditions' => array(
'SenasaPedidos.id = SenasaPedidosFacturadosSds.senasa_pedidos_id'
)
),
array(
'table' => 'clientes',
'alias' => 'Clientes',
'type' => 'INNER',
'conditions' => array(
'Clientes.id_cliente = SenasaPedidos.clientes_id',
'Clientes.requiere_senasa = 1'
)
),
),
'fields'=>array(
'SenasaPedidosFacturadosSds.*',
'Usuarios.usuario_id',
'Usuarios.apellido_nombre',
'Usuarios.senasa_establecimientos_id',
'Clientes.id_cliente',
'Clientes.consolida_doc_sanitaria',
'Clientes.requiere_senasa',
'Clientes.razon_social',
'SenasaPedidos.id',
'SenasaPedidos.domicilio_entrega',
'SenasaPedidos.sds',
'SenasaPedidos.pt_ptr'
),
//'conditions'=>array(
// 'Clientes.requiere_senasa'=>1
//),
'order' => 'SenasaPedidosFacturadosSds.created DESC',
'limit'=>100
);
$this->paginate = $where;
// Get datos
$data = $this->Paginator->paginate();
exit(debug($data));
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<table class="table table-bordered">_x000D_
<thead>_x000D_
<tr>_x000D_
<th></th>_x000D_
<th class="text-center">Left</th>_x000D_
<th class="text-center">Center</th>_x000D_
<th class="text-center">Right</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<th>_x000D_
<span>Bootstrap (class="text-left")</span>_x000D_
</th>_x000D_
<td class="text-left">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
<td class="text-center">_x000D_
<input type="checkbox" checked />_x000D_
</td>_x000D_
<td class="text-right">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>_x000D_
<span>HTML attribute (align="left")</span>_x000D_
</th>_x000D_
<td align="left">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
<td align="center">_x000D_
<input type="checkbox" checked />_x000D_
</td>_x000D_
<td align="right">_x000D_
<input type="checkbox" />_x000D_
</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
I found a way to do it without replacing the slashes
select CONVERT(VARCHAR(10), GETDATE(), 112)
This would return: "YYYYMMDD"