You will first need to update the local formulas by doing
brew update
and then upgrade the package by doing
brew upgrade formula-name
An example would be if i wanted to upgrade mongodb, i would do something like this, assuming mongodb was already installed :
brew update && brew upgrade mongodb && brew cleanup mongodb
Refactoring:
new WindowsMediaPlayer() { URL = "MyMusic.mp3" }.controls.play();
TL;DR: Always do your own research, in regard of generated machine code size, performance, readability and coding time before trusting random comments online, including this one.
I'm no expert. I just happened to overhear two co-workers talking about how we should avoid using C++ in embedded systems because of performance issues. Well, interesting enough, I did a benchmark based on a real project task.
In said task, we had to write some config to RAM. Something like:
coffee=hot
sugar=none
milk=breast
mac=AA:BB:CC:DD:EE:FF
Here's my benchmark programs (Yes, I know OP asked about printf(), not fprintf(). Try to capture the essence and by the way, OP's link points to fprintf() anyway.)
C program:
char coffee[10], sugar[10], milk[10];
unsigned char mac[6];
/* Initialize those things here. */
FILE * f = fopen("a.txt", "wt");
fprintf(f, "coffee=%s\nsugar=%s\nmilk=%s\nmac=%02X:%02X:%02X:%02X:%02X:%02X\n", coffee, sugar, milk, mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);
fclose(f);
C++ program:
//Everything else is identical except:
std::ofstream f("a.txt", std::ios::out);
f << "coffee=" << coffee << "\n";
f << "sugar=" << sugar << "\n";
f << "milk=" << milk << "\n";
f << "mac=" << (int)mac[0] << ":"
<< (int)mac[1] << ":"
<< (int)mac[2] << ":"
<< (int)mac[3] << ":"
<< (int)mac[4] << ":"
<< (int)mac[5] << endl;
f.close();
I did my best to polish them before I looped them both 100,000 times. Here are the results:
C program:
real 0m 8.01s
user 0m 2.37s
sys 0m 5.58s
C++ program:
real 0m 6.07s
user 0m 3.18s
sys 0m 2.84s
Object file size:
C - 2,092 bytes
C++ - 3,272 bytes
Conclusion: On my very specific platform, with a very specific processor, running a very specific version of Linux kernel, to run a program which is compiled with a very specific version of GCC, in order to accomplish a very specific task, I would say the C++ approach is more suitable because it runs significantly faster and provide much better readability. On the other hand, C offers small footprint, in my opinion, means nearly nothing because program size is not of our concern.
Remeber, YMMV.
Lets do some experimentation, to see how we could get/interpret the length of different dict/array values in a dict.
create our test dict, see list and dict comprehensions:
>>> my_dict = {x:[i for i in range(x)] for x in range(4)}
>>> my_dict
{0: [], 1: [0], 2: [0, 1], 3: [0, 1, 2]}
Get the length of the value of a specific key:
>>> my_dict[3]
[0, 1, 2]
>>> len(my_dict[3])
3
Get a dict of the lengths of the values of each key:
>>> key_to_value_lengths = {k:len(v) for k, v in my_dict.items()}
{0: 0, 1: 1, 2: 2, 3: 3}
>>> key_to_value_lengths[2]
2
Get the sum of the lengths of all values in the dict:
>>> [len(x) for x in my_dict.values()]
[0, 1, 2, 3]
>>> sum([len(x) for x in my_dict.values()])
6
This function will return an integer sequence.
const integerRange = (start, end, n = start, arr = []) =>
(n === end) ? [...arr, n]
: integerRange(start, end, start < end ? n + 1 : n - 1, [...arr, n]);
$> integerRange(1, 1)
<- Array [ 1 ]
$> integerRange(1, 3)
<- Array(3) [ 1, 2, 3 ]
$> integerRange(3, -3)
<- Array(7) [ 3, 2, 1, 0, -1, -2, -3 ]
HTML
<img id="close" className="fa fa-close" src="" alt="" title="Close Me" />
CSS
#close[title]:hover:after {
color: red;
content: attr(title);
position: absolute;
left: 50px;
}
Enter services.msc and shutdown anything SQL you have running. The SQL server might be taking over the port.
Oracle has two different ways of making views updatable:-
I would stay away from instead-of triggers and get your code to update the underlying tables directly rather than through the view.
select to_char(sysdate, 'Month') from dual
in your example will be:
select to_char(to_date('15-11-2010', 'DD-MM-YYYY'), 'Month') from dual
for bootstrap 4 this work with me good
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").addClass('is-invalid');
},
unhighlight: function(element) {
$(element).closest('.form-group').find(".form-control:first").removeClass('is-invalid');
$(element).closest('.form-group').find(".form-control:first").addClass('is-valid');
},
errorElement: 'span',
errorClass: 'invalid-feedback',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
hope it will help !
Open app page on Google Play:
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=" + context.getPackageName()));
startActivity(intent);
Well, if you want to do it using an algorithm. There are a plethora of sorting algorithms out there. If you aren't concerned too much about efficiency and more about readability and understandability. I recommend Insertion Sort. Here is the psudo code, it is trivial to translate this into java.
begin
for i := 1 to length(A)-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
else
done := true;
until done;
A[j + 1] := value;
end;
end;
I have 2 servers setup on docker, reverse proxy & web server. This error started happening for all my websites all of a sudden after 1 year. When setting up earlier, I generated a self signed certificate on the web server.
So, I had to generate the SSL certificate again and it started working...
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ssl.key -out ssl.crt
Quick answer
On src, you can always specify files to ignore using "!".
Example (you want to exclude all *.min.js files on your js folder and subfolder:
gulp.src(['js/**/*.js', '!js/**/*.min.js'])
You can do it as well for individual files.
Expanded answer:
Extracted from gulp documentation:
gulp.src(globs[, options])
Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.
glob refers to node-glob syntax or it can be a direct file path.
So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.
On minimatch documentation, they point out the following:
if the pattern starts with a ! character, then it is negated.
And that is why using ! symbol will exclude files / directories from a gulp task
Use this from mysql command window:
mysql> use db_name;
mysql> source backup-file.sql;
Open a command prompt and type one of the following lines according to your Visual Studio version and Operating System Architecture :
VS 2008 on 32bit Windows :
"%ProgramFiles%\Microsoft SDKs\Windows\v6.0A\bin\sn.exe" -T <assemblyname>
VS 2008 on 64bit Windows :
"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v6.0A\bin\sn.exe" -T <assemblyname>
VS 2010 on 32bit Windows :
"%ProgramFiles%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -T <assemblyname>
VS 2010 on 64bit Windows :
"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v7.0A\bin\sn.exe" -T <assemblyname>
VS 2012 on 32bit Windows :
"%ProgramFiles%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe" -T <assemblyname>
VS 2012 on 64bit Windows :
"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\sn.exe" -T <assemblyname>
VS 2015 on 64bit Windows :
"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\sn.exe" -T <assemblyname>
Note that for the versions VS2012+, sn.exe application isn't anymore in bin but in a sub-folder. Also, note that for 64bit you need to specify (x86) folder.
If you prefer to use Visual Studio command prompt, just type :
sn -T <assembly>
where <assemblyname>
is a full file path to the assembly you're interested in, surrounded by quotes if it has spaces.
You can add this as an external tool in VS, as shown here:
http://blogs.msdn.com/b/miah/archive/2008/02/19/visual-studio-tip-get-public-key-token-for-a-stong-named-assembly.aspx
Another common option is when you do want multiple plots in a single window
f = figure;
hold on
plot(x1,y1)
plot(x2,y2)
...
plots multiple data sets on the same (new) figure.
Just use the following sql, you are done:
SELECT replace(CustomerName,' ', '') FROM Customers;
you can test this sample over here: W3School
For document references, not collections, you need:
// when you know the 'id'
this.afs.doc(`items/${id}`)
.snapshotChanges().pipe(
map((doc: any) => {
const data = doc.payload.data();
const id = doc.payload.id;
return { id, ...data };
});
as .valueChanges({ idField: 'id'});
will not work here. I assume it was not implemented since generally you search for a document by the id...
Use the observer pattern. It works like this:
interface MyListener{
void somethingHappened();
}
public class MyForm implements MyListener{
MyClass myClass;
public MyForm(){
this.myClass = new MyClass();
myClass.addListener(this);
}
public void somethingHappened(){
System.out.println("Called me!");
}
}
public class MyClass{
private List<MyListener> listeners = new ArrayList<MyListener>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
void notifySomethingHappened(){
for(MyListener listener : listeners){
listener.somethingHappened();
}
}
}
You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.
This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.
In my example:
MyClass
is the producer here as its notifying a list of listeners.
MyListener
is the interface.
MyForm
is interested in when somethingHappened
, so it is implementing MyListener
and registering itself with MyClass
. Now MyClass
can inform MyForm
about events without directly referencing MyForm
. This is the strength of the observer pattern, it reduces dependency and increases reusability.
"Closing" the current iFrame is not possible but you can tell the parent to manipulate the dom and make it invisible.
In IFrame:
parent.closeIFrame();
In parent:
function closeIFrame(){
$('#youriframeid').remove();
}
One feature of my original code
if ( typeof(x.y) != 'undefined' ) ...
that might be useful in some situations is that it is safe to use whether x
exists or not. With either of the methods in gnarf's answer, one should first test for x
if there is any doubt if it exists.
So perhaps all three methods have a place in one's bag of tricks.
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
After testing I found that it was not the decimal place that was causing the problem, it was the precision (10)
This doesn't work: Arithmetic overflow error converting varchar to data type numeric.
DECLARE @TestConvert VARCHAR(MAX) = '123456789.12343594'
SELECT CAST(@TestConvert AS DECIMAL(10, 4))
This worked
DECLARE @TestConvert VARCHAR(MAX) = '123456789.12343594'
SELECT CAST(@TestConvert AS DECIMAL(18, 4))
a <- 1:120
b <- a[seq(1, length(a), 6)]
It is possible by recreating table.Its work for me please follow following step:
do all above steps in worker thread to reduce load on uithread
with gzip.open('features_train.csv.gz') as f:
features_train = pd.read_csv(f)
features_train.head()
Add this in your css file:
.custom_class
{
background-image: url(../img/beach.jpg);
-moz-background-size: cover;
-webkit-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
and then, in your .html (or .php) file call this class like that:
<div class="custom_class">
...
</div>
This is how I used it:
->where('b.status IN (:statuses)')
->setParameters([
'customerId' => $customerId,
'storeId' => $storeId,
'statuses' => [Status::OPEN, Status::AWAITING_APPROVAL, Status::APPROVED]
]);
Not sure why scripts here have never really worked for me. This works:
#!/bin/bash
for i in *.jar; do jar -tf "$i" | grep $1 | xargs -I{} echo -e "$i : {}" ; done
Function on swift 3 scroll to bottom
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
//scroll down
if lists.count > 2 {
let numberOfSections = self.tableView.numberOfSections
let numberOfRows = self.tableView.numberOfRows(inSection: numberOfSections-1)
let indexPath = IndexPath(row: numberOfRows-1 , section: numberOfSections-1)
self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.middle, animated: true)
}
}
Give them a class and add your style to the class.
<style>
p {
color: red;
}
.paragraph1 {
font-size: 18px;
}
.paragraph2 {
font-size: 13px;
}
</style>
<p class="paragraph1">Paragraph 1</p>
<p class="paragraph2">Paragraph 2</p>
Check this EXAMPLE
Add a label control to your Repeater's ItemTemplate. Handle OnItemCreated event.
ASPX
<asp:Repeater ID="rptr" runat="server" OnItemCreated="RepeaterItemCreated">
<ItemTemplate>
<div id="width:50%;height:30px;background:#0f0a0f;">
<asp:Label ID="lblSr" runat="server"
style="width:30%;float:left;text-align:right;text-indent:-2px;" />
<span
style="width:65%;float:right;text-align:left;text-indent:-2px;" >
<%# Eval("Item") %>
</span>
</div>
</ItemTemplate>
</asp:Repeater>
Code Behind:
protected void RepeaterItemCreated(object sender, RepeaterItemEventArgs e)
{
Label l = e.Item.FindControl("lblSr") as Label;
if (l != null)
l.Text = e.Item.ItemIndex + 1+"";
}
There is a special trick I discovered by accident.
plt.gca().xaxis.grid(True)
proved to be the solution for me
You can't, not using the standard API. HttpServletRequest
represent a request received by the server, and so adding new parameters is not a valid option (as far as the API is concerned).
You could in principle implement a subclass of HttpServletRequestWrapper
which wraps the original request, and intercepts the getParameter()
methods, and pass the wrapped request on when you forward.
If you go this route, you should use a Filter
to replace your HttpServletRequest
with a HttpServletRequestWrapper
:
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletRequest instanceof HttpServletRequest) {
HttpServletRequest request = (HttpServletRequest) servletRequest;
// Check wether the current request needs to be able to support the body to be read multiple times
if (MULTI_READ_HTTP_METHODS.contains(request.getMethod())) {
// Override current HttpServletRequest with custom implementation
filterChain.doFilter(new HttpServletRequestWrapper(request), servletResponse);
return;
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
RUn the following query to find if you are running spfile or not:
SELECT DECODE(value, NULL, 'PFILE', 'SPFILE') "Init File Type"
FROM sys.v_$parameter WHERE name = 'spfile';
If the result is "SPFILE", then use the following command:
alter system set open_cursors = 4000 scope=both; --4000 is the number of open cursor
if the result is "PFILE", then use the following command:
alter system set open_cursors = 1000 ;
You can read about SPFILE vs PFILE here,
Using Thread.currentThread()
:
private class MyTask implements Runnable {
public void run() {
long threadId = Thread.currentThread().getId();
logger.debug("Thread # " + threadId + " is doing this task");
}
}
Do not use the ToList()
method as in the accepted answer !
Running SQL profiler, I verified and found that ToList()
function gets all the records from the database. It is really bad performance !!
I would have run this query by pure sql command as follows:
string query = "Update YourTable Set ... Where ...";
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));
This would operate the update in one-shot without selecting even one row.
"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:
float(20)/15 #1.33333333
I like some of the answers here, but there is a sed command that should do the trick on any platform:
sed 'y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/'
Anyway, it's easy to understand. And knowing about the y command can come in handy sometimes.
You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.
So, instead of simply calling addWord("someWord")
, you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();
), and then call the method using that (i.e. list.addWord("someWord");
.
However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord()
static, or change the methods in the Words class so that they're not static.
My bad with the above paragraph - however you might want to reconsider ProcessInput()
being a static method - does it really need to be?
Tested On Ubuntu 20, sudo chown -R $USER:$USER /var/www
Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.
You can use tf.convert_to_tensor()
:
import tensorflow as tf
import numpy as np
data = [[1,2,3],[4,5,6]]
data_np = np.asarray(data, np.float32)
data_tf = tf.convert_to_tensor(data_np, np.float32)
sess = tf.InteractiveSession()
print(data_tf.eval())
sess.close()
Here's a link to the documentation for this method:
https://www.tensorflow.org/api_docs/python/tf/convert_to_tensor
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
It is dirty better use the overflow: hidden;
hack:
<div class="container">
<div style="float: left;">Left Div</div>
<div style="float: right;">Right Div</div>
</div>
.container { overflow: hidden; }
Or if you are going to do some fancy CSS3 drop-shadow stuff and you get in trouble with the above solution:
PS
If you want to go for clean I would rather worry about that inline javascript rather than the overflow: hidden;
hack :)
For some odd reason, the width and height of the button have been reset. You need to specify them in the ID selector as well:
#rock {
width: 150px;
height: 150px;
background-image: url(http://th07.deviantart.net/fs70/150/i/2013/012/c/6/rock_01_png___by_alzstock-d5r84up.png);
background-repeat: no-repeat;
}
Please try this one:
function used_to_compare_two_arrays(a, b)
{
// This block will make the array of indexed that array b contains a elements
var c = a.filter(function(value, index, obj) {
return b.indexOf(value) > -1;
});
// This is used for making comparison that both have same length if no condition go wrong
if (c.length !== a.length) {
return 0;
} else{
return 1;
}
}
The SQLite documentation is a great reference and the DateAndTimeFunctions page is a good one to bookmark.
It's also helpful to remember that it's pretty easy to play with queries with the sqlite command line utility:
sqlite> select julianday(datetime('now'));
2454788.09219907
sqlite> select datetime(julianday(datetime('now')));
2008-11-17 14:13:55
You have to use querySelectorAll
as you need to select all elements with the said class, again since querySelectorAll
is an array you need to iterate it and add the event handlers
var deleteLinks = document.querySelectorAll('.delete');
for (var i = 0; i < deleteLinks.length; i++) {
deleteLinks[i].addEventListener('click', function (event) {
event.preventDefault();
var choice = confirm("sure u want to delete?");
if (choice) {
return true;
}
});
}
Something like this:
mail("[email protected] , [email protected] , [email protected]", "Test e-mail", "Hi, this is a test message!");
You can use contains
(this works with an arbitrary sequence):
df.filter($"foo".contains("bar"))
like
(SQL like with SQL simple regular expression whith _
matching an arbitrary character and %
matching an arbitrary sequence):
df.filter($"foo".like("bar"))
or rlike
(like with Java regular expressions):
df.filter($"foo".rlike("bar"))
depending on your requirements. LIKE
and RLIKE
should work with SQL expressions as well.
These are good answers above, I just wanted to add a clarification:
You can't disown
a pid or process, you disown
a job, and that is an important distinction.
A job is something that is a notion of a process that is attached to a shell, therefore you have to throw the job into the background (not suspend it) and then disown it.
Issue:
% jobs
[1] running java
[2] suspended vi
% disown %1
See http://www.quantprinciple.com/invest/index.php/docs/tipsandtricks/unix/jobcontrol/ for a more detailed discussion of Unix Job Control.
explode() might be the function you are looking for
$array = explode(' ',$str);
You can use a tool like the TrIDNet - File Identifier to look for the Magic Number and other telltales, if the file format is in it's database it may tell you what it is for.
However searching the definitions did not turn up anything for the string "FLDB", but it checks more than magic numbers so it is worth a try.
If you are using Linux File is a command that will do a similar task.
The other thing to try is if you have access to the program that generated this file, there may be DLL's or EXE's from the database software that may contain meta information about the dll's creator which could give you a starting point for looking for software that can read the file outside of the program that originally created the .db
file.
If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE
like this:
UPDATE MyTable
SET MyColumn = UPPER(MyColumn)
WHERE MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS
Cases sensitivity is based on your collation settings, and is typically case insensitive by default.
Collation can be set at the Server, Database, Column, or Query Level:
-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL
Collation Names specify how a string should be encoded and read, for example:
Latin1_General_CI_AS
? Case InsensitiveLatin1_General_CS_AS
? Case SensitiveYou can do new ArrayList<T>(set).get(index)
This isn't really possible in HTML unless you use absolute positioning or javascript. So one solution would be to give this CSS to #bottom_link:
#bottom_link {
position:absolute;
bottom:0;
}
Otherwise you'd have to use some javascript. Here's a jQuery block that should do the trick, depending on the simplicity of the page.
$('#bottom_link').css({
position: 'relative',
top: $(this).parent().height() - $(this).height()
});
I was having a similar error installing php 5.3.3 with the Error Code 0x80070020 with a direction to a few lines in web.config in my www root directory (not the standard root directory).
The solution, while crude, worked perfectly. I simply deleted the web.config file and now everything works. I spent HOURS trying other solutions to no avail.
If anyone thinks this was stupid, please let me know. If anyone else has spent the same amount of time pulling out hair, try it and see (after backing up the file of course)
Regards FEQ
The accepted solution of modifying a Run Configuration wasn't ideal for me as I have a few different run configurations and could easily forget to do this when adding further ones in future. Also I wanted the setting to apply whenever running anything, e.g. when running JUnit tests by right-clicking and selecting "Run As" -> "JUnit Test".
The above can be achieved by modifying the JRE/JDK settings instead:-
-Xms512m -Xmx4G -XX:MaxPermSize=256M
The line starting ALREADYEXISTS
uses ’
as the closing quote, it should be using '
. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.
Using % you will run into a hex operation error when the time value is 7-9. To avoid this, use DelayedExpansion and grab time values with !min:~1!
An alternate method, if you have PowerShell is to call that:
for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)
You can use curl
as is in this thread
For the lazy:
*/5 * * * * curl --request GET 'http://exemple.com/path/check.php?param1=1'
This will be executed every 5 minutes.
return x2 >= y1 && x1 <= y2;
You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk
First, get the formats of the video:
? ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code extension resolution note
140 m4a audio only DASH audio 144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160 mp4 256x144 DASH video 124k , avc1.42c00b, 30fps, video only
133 mp4 426x240 DASH video 258k , avc1.4d4015, 30fps, video only
134 mp4 640x360 DASH video 646k , avc1.4d401e, 30fps, video only
135 mp4 854x480 DASH video 1171k , avc1.4d401f, 30fps, video only
136 mp4 1280x720 DASH video 2326k , avc1.4d401f, 30fps, video only
137 mp4 1920x1080 DASH video 4347k , avc1.640028, 30fps, video only
151 mp4 72p HLS , h264, aac @ 24k
132 mp4 240p HLS , h264, aac @ 48k
92 mp4 240p HLS , h264, aac @ 48k
93 mp4 360p HLS , h264, aac @128k
94 mp4 480p HLS , h264, aac @128k
95 mp4 720p HLS , h264, aac @256k
96 mp4 1080p HLS , h264, aac @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code extension resolution note
140 m4a audio only DASH audio 144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160 mp4 256x144 DASH video 124k , avc1.42c00b, 30fps, video only
133 mp4 426x240 DASH video 258k , avc1.4d4015, 30fps, video only
134 mp4 640x360 DASH video 646k , avc1.4d401e, 30fps, video only
135 mp4 854x480 DASH video 1171k , avc1.4d401f, 30fps, video only
136 mp4 1280x720 DASH video 2326k , avc1.4d401f, 30fps, video only
151 mp4 72p HLS , h264, aac @ 24k
132 mp4 240p HLS , h264, aac @ 48k
92 mp4 240p HLS , h264, aac @ 48k
93 mp4 360p HLS , h264, aac @128k
94 mp4 480p HLS , h264, aac @128k
95 mp4 720p HLS , h264, aac @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam
In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f
to pass in the format you would like to watch, and -g
to get that stream's URL:
? ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8
These are your HLS m3u8 playlists, one for each camera associated with the live stream.
Without youtube-dl, your flow might look like this:
Take your video id and make a GET request to the get_video_info
endpoint:
HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en
In the response, the hlsvp
value will be the link to the m3u8 HLS playlist:
https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8
Here are a few things you cant do with email:
- Include a section with styles. Apple Mail.app supports it, but Gmail and Hotmail do not, so it's a no-no. Hotmail will support a style section in the body but Gmail still doesn't.
- Link to an external stylesheet. Not many email clients support this, best to just forget it.
- Background-image / Background-position. Gmail is also the culprit on this one.
- Clear your floats. Gmail again.
- Margin. Yep, seriously, Hotmail ignores margins. Basically any CSS positioning at all doesn't work.
- Font-anything. Chances are Eudora will ignore anything you try to declare with fonts.
Source: http://css-tricks.com/using-css-in-html-emails-the-real-story/
Mailchimp has email templates you can use - here
A few more resources that should help you
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA- 5
to - 4
when setting MyFileName.Edit: put Local:=True
to save with my locale CSV delimiter.
A simple way :
select * from hockey_stats
where game_date >= '2012-03-11' and game_date <= '2012-05-11'
Try using p:ajax with event attribute,
A very easy solution via Keychains.
It's a simple wrapper for the system Keychain. Just add the SSKeychain.h
, SSKeychain.m
, SSKeychainQuery.h
and SSKeychainQuery.m
files to your project and add the Security.framework to your target.
To save a password:
[SSKeychain setPassword:@"AnyPassword" forService:@"AnyService" account:@"AnyUser"]
To retrieve a password:
NSString *password = [SSKeychain passwordForService:@"AnyService" account:@"AnyUser"];
Where setPassword
is what value you want saved and forService
is what variable you want it saved under and account is for what user/object the password and any other info is for.
The issue is with the Version of JSCH jar you are using.
Update it to latest jar.
I was also getting the same error and this solution worked.
You can download latest jar from
I also encountered the same problem but brew install python3
does not work properly to install pip3
.
brre will throw the warning The post-install step did not complete successfully
.
It has to do with homebrew does not have permission to /usr/local
Create the directory if not exist
sudo mkdir lib
sudo mkdir Frameworks
Give the permissions inside /usr/local
to homebrew so it can access them:
sudo chown -R $(whoami) $(brew --prefix)/*
Now ostinstall python3
brew postinstall python3
This will give you a successful installation
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
I'd like to suggest another approach to the "Oups I forgot to write sudo
while opening my file" issue:
Instead of receiving a permission denied
, and having to type :w!!
, I find it more elegant to have a conditional vim
command that does sudo vim
if file owner is root
.
This is as easy to implement (there might even be more elegant implementations, I'm clearly not a bash-guru):
function vim(){
OWNER=$(stat -c '%U' $1)
if [[ "$OWNER" == "root" ]]; then
sudo /usr/bin/vim $*;
else
/usr/bin/vim $*;
fi
}
And it works really well.
This is a more bash
-centered approach than a vim
-one so not everybody might like it.
Of course:
root
but requires sudo
, but the function can be edited anyway) vim
for reading-only a file (as far as I'm concerned, I use tail
or cat
for small files)But I find this brings a much better dev user experience, which is something that IMHO tends to be forgotten when using bash
. :-)
Example in Swift 3, with a previous and a next button in the top right.
let prevButtonItem = UIBarButtonItem(title: "\u{25C0}", style: .plain, target: self, action: #selector(prevButtonTapped))
let nextButtonItem = UIBarButtonItem(title: "\u{25B6}", style: .plain, target: self, action: #selector(nextButtonTapped))
self.navigationItem.rightBarButtonItems = [nextButtonItem, prevButtonItem]
Let's test 3 methods:
1)
public static double round1(double value, int scale) {
return Math.round(value * Math.pow(10, scale)) / Math.pow(10, scale);
}
2)
public static float round2(float number, int scale) {
int pow = 10;
for (int i = 1; i < scale; i++)
pow *= 10;
float tmp = number * pow;
return ( (float) ( (int) ((tmp - (int) tmp) >= 0.5f ? tmp + 1 : tmp) ) ) / pow;
}
3)
public static float round3(float d, int decimalPlace) {
return BigDecimal.valueOf(d).setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).floatValue();
}
Number is 0.23453f
We'll test 100,000 iterations each method.
Results:
Time 1 - 18 ms
Time 2 - 1 ms
Time 3 - 378 ms
Tested on laptop
Intel i3-3310M CPU 2.4GHz
After t.thielemans' answer, I worked that just
=VLOOKUP(A1, B:C, 2, FALSE)
works fine and does what I wanted, except that it returns #N/A
for non-matches; so it is suitable for the case where it is known that the value definitely exists in the look-up column.
Edit (based on t.thielemans' comment):
To avoid #N/A
for non-matches, do:
=IFERROR(VLOOKUP(A1, B:C, 2, FALSE), "No Match")
In my case, i tried all solutions but nothing worked.
My SO is windows 7 x64, with all the Redistributable Packages (x86,x64 / 2010,2013,2015)
The problem was that i tried to install the x64 workbench, but for some reason did not work (even my SO is x64).
so, the solution was download the x86 installer from : https://downloads.mysql.com/archives/workbench/
Gist with log rotation: https://gist.github.com/barsv/85c93b599a763206f47aec150fb41ca0
Usage:
. .\logger.ps1
Write-Log "debug message"
Write-Log "info message" "INFO"
After cleaning the string, you can match non-whitespace characters or word-boundaries.
Here are two simple regular expressions to capture words in a string:
/\S+/g
/\b[a-z\d]+\b/g
The example below shows how to retrieve the word count from a string, by using these capturing patterns.
/*Redirect console output to HTML.*/document.body.innerHTML='';console.log=function(s){document.body.innerHTML+=s+'\n';};_x000D_
/*String format.*/String.format||(String.format=function(f){return function(a){return f.replace(/{(\d+)}/g,function(m,n){return"undefined"!=typeof a[n]?a[n]:m})}([].slice.call(arguments,1))});_x000D_
_x000D_
// ^ IGNORE CODE ABOVE ^_x000D_
// =================_x000D_
_x000D_
// Clean and match sub-strings in a string._x000D_
function extractSubstr(str, regexp) {_x000D_
return str.replace(/[^\w\s]|_/g, '')_x000D_
.replace(/\s+/g, ' ')_x000D_
.toLowerCase().match(regexp) || [];_x000D_
}_x000D_
_x000D_
// Find words by searching for sequences of non-whitespace characters._x000D_
function getWordsByNonWhiteSpace(str) {_x000D_
return extractSubstr(str, /\S+/g);_x000D_
}_x000D_
_x000D_
// Find words by searching for valid characters between word-boundaries._x000D_
function getWordsByWordBoundaries(str) {_x000D_
return extractSubstr(str, /\b[a-z\d]+\b/g);_x000D_
}_x000D_
_x000D_
// Example of usage._x000D_
var edisonQuote = "I have not failed. I've just found 10,000 ways that won't work.";_x000D_
var words1 = getWordsByNonWhiteSpace(edisonQuote);_x000D_
var words2 = getWordsByWordBoundaries(edisonQuote);_x000D_
_x000D_
console.log(String.format('"{0}" - Thomas Edison\n\nWord count via:\n', edisonQuote));_x000D_
console.log(String.format(' - non-white-space: ({0}) [{1}]', words1.length, words1.join(', ')));_x000D_
console.log(String.format(' - word-boundaries: ({0}) [{1}]', words2.length, words2.join(', ')));
_x000D_
body { font-family: monospace; white-space: pre; font-size: 11px; }
_x000D_
You could also create a mapping of words to get unique counts.
function cleanString(str) {_x000D_
return str.replace(/[^\w\s]|_/g, '')_x000D_
.replace(/\s+/g, ' ')_x000D_
.toLowerCase();_x000D_
}_x000D_
_x000D_
function extractSubstr(str, regexp) {_x000D_
return cleanString(str).match(regexp) || [];_x000D_
}_x000D_
_x000D_
function getWordsByNonWhiteSpace(str) {_x000D_
return extractSubstr(str, /\S+/g);_x000D_
}_x000D_
_x000D_
function getWordsByWordBoundaries(str) {_x000D_
return extractSubstr(str, /\b[a-z\d]+\b/g);_x000D_
}_x000D_
_x000D_
function wordMap(str) {_x000D_
return getWordsByWordBoundaries(str).reduce(function(map, word) {_x000D_
map[word] = (map[word] || 0) + 1;_x000D_
return map;_x000D_
}, {});_x000D_
}_x000D_
_x000D_
function mapToTuples(map) {_x000D_
return Object.keys(map).map(function(key) {_x000D_
return [ key, map[key] ];_x000D_
});_x000D_
}_x000D_
_x000D_
function mapToSortedTuples(map, sortFn, sortOrder) {_x000D_
return mapToTuples(map).sort(function(a, b) {_x000D_
return sortFn.call(undefined, a, b, sortOrder);_x000D_
});_x000D_
}_x000D_
_x000D_
function countWords(str) {_x000D_
return getWordsByWordBoundaries(str).length;_x000D_
}_x000D_
_x000D_
function wordFrequency(str) {_x000D_
return mapToSortedTuples(wordMap(str), function(a, b, order) {_x000D_
if (b[1] > a[1]) {_x000D_
return order[1] * -1;_x000D_
} else if (a[1] > b[1]) {_x000D_
return order[1] * 1;_x000D_
} else {_x000D_
return order[0] * (a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0));_x000D_
}_x000D_
}, [1, -1]);_x000D_
}_x000D_
_x000D_
function printTuples(tuples) {_x000D_
return tuples.map(function(tuple) {_x000D_
return padStr(tuple[0], ' ', 12, 1) + ' -> ' + tuple[1];_x000D_
}).join('\n');_x000D_
}_x000D_
_x000D_
function padStr(str, ch, width, dir) { _x000D_
return (width <= str.length ? str : padStr(dir < 0 ? ch + str : str + ch, ch, width, dir)).substr(0, width);_x000D_
}_x000D_
_x000D_
function toTable(data, headers) {_x000D_
return $('<table>').append($('<thead>').append($('<tr>').append(headers.map(function(header) {_x000D_
return $('<th>').html(header);_x000D_
})))).append($('<tbody>').append(data.map(function(row) {_x000D_
return $('<tr>').append(row.map(function(cell) {_x000D_
return $('<td>').html(cell);_x000D_
}));_x000D_
})));_x000D_
}_x000D_
_x000D_
function addRowsBefore(table, data) {_x000D_
table.find('tbody').prepend(data.map(function(row) {_x000D_
return $('<tr>').append(row.map(function(cell) {_x000D_
return $('<td>').html(cell);_x000D_
}));_x000D_
}));_x000D_
return table;_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
$('#countWordsBtn').on('click', function(e) {_x000D_
var str = $('#wordsTxtAra').val();_x000D_
var wordFreq = wordFrequency(str);_x000D_
var wordCount = countWords(str);_x000D_
var uniqueWords = wordFreq.length;_x000D_
var summaryData = [_x000D_
[ 'TOTAL', wordCount ],_x000D_
[ 'UNIQUE', uniqueWords ]_x000D_
];_x000D_
var table = toTable(wordFreq, ['Word', 'Frequency']);_x000D_
addRowsBefore(table, summaryData);_x000D_
$('#wordFreq').html(table);_x000D_
});_x000D_
});
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
table-layout: fixed;_x000D_
width: 200px;_x000D_
font-family: monospace;_x000D_
}_x000D_
thead {_x000D_
border-bottom: #000 3px double;;_x000D_
}_x000D_
table, td, th {_x000D_
border: #000 1px solid;_x000D_
}_x000D_
td, th {_x000D_
padding: 2px;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
textarea, input[type="button"], table {_x000D_
margin: 4px;_x000D_
padding: 2px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<h1>Word Frequency</h1>_x000D_
<textarea id="wordsTxtAra" cols="60" rows="8">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal._x000D_
_x000D_
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this._x000D_
_x000D_
But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.</textarea><br />_x000D_
<input type="button" id="countWordsBtn" value="Count Words" />_x000D_
<div id="wordFreq"></div>
_x000D_
char_seen = []
for char in string:
if char not in char_seen:
char_seen.append(char)
print(''.join(char_seen))
This will preserve the order in which alphabets are coming,
output will be
abcd
Get counts of all tables in a schema and order by desc
select 'with tmp(table_name, row_number) as (' from dual
union all
select 'select '''||table_name||''',count(*) from '||table_name||' union ' from USER_TABLES
union all
select 'select '''',0 from dual) select table_name,row_number from tmp order by row_number desc ;' from dual;
Copy the entire result and execute
Had the same issue installing angular material CDK:
npm install --save @angular/material @angular/cdk @angular/animations
Adding -dev
like below worked for me:
npm install --save-dev @angular/material @angular/cdk @angular/animations
There might be a semicolon or bracket missing a line before your pasted line.
It seems fine to me; every string is allowed as an array index.
CREATE TEMPORARY TABLE IF NOT EXISTS to_table_name AS (SELECT * FROM from_table_name)
Use double braces {{
or }}
so your code becomes:
sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}",
prop.Type, prop.Name));
// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }
Try using attr.disabled
, instead of disabled
<input [attr.disabled]="disabled ? '' : null"/>
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5. Happy coding!
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
plt.errorbar
can be used to plot x, y, error data (as opposed to the usual plt.plot
)
import matplotlib.pyplot as plt
import numpy as np
x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])
plt.errorbar(x, y, e, linestyle='None', marker='^')
plt.show()
plt.errorbar
accepts the same arguments as plt.plot
with additional yerr
and xerr
which default to None (i.e. if you leave them blank it will act as plt.plot
).
You can use noWeekends function to disable the weekend selection
$(function() {
$( "#datepicker" ).datepicker({
beforeShowDay: $.datepicker.noWeekends
});
});
The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.
This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.
If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:
s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T
On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE
attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY
You are trying to assign a value to a function, which is not possible in C. Try the comparison operator instead:
if (strcmp("hello", "hello") == 0)
You can't force the String arrays to have a specific size. You can do this:
private List<String[]> addresses = new ArrayList<String[]>();
but an array of any size can be added to this list.
However, as others have mentioned, the correct thing to do here is to create a separate class representing addresses. Then you would have something like:
private List<Address> addresses = new ArrayList<Address>();
For Mac OSX: There is a way to install Visual Studio Code through Brew-Cask.
Now run following command and it will install latest Visual Studio Code on your Mac.
$> brew cask install visual-studio-code
Above command should install Visual Studio Code and also set up the command-line calling of Visual Studio Code.
If above steps don't work then you can do it manually. By following Microsoft Visual Studio Code documentation given here.
You need add -> contentType: "application/json; charset=utf-8",
<script type="text/javascript">
$(document).ready( function() {
$('#btnTest').click( function() {
$.ajax({
type: "POST",
url: "/Login/Test",
data: { ListID: '1', ItemName: 'test' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) { alert(response); },
error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
});
});
});
</script>
The indian rupee sign is pretty new (introduced this July if I read it correctly) and doesn't even have a Unicode position yet, much less a HTML entity.
Even when it gets a Unicode position, it will probably still take years until it can be reliably used on a web page, because the client computers' Fonts will need to be updated accordingly. (I could imagine a font-face
workaround with a custom font, though.)
Wikipedia uses an image file to display the symbol. It's far from good, but it may be the best workaround at the moment.
The generic rupee sign has three Unicode characters. See here.
Brendan is correct. You can edit the Select command to edit a filtered list of records. For instance "WHERE dept_no = 200"
.
You should declare it with declarations array(meta property) of @NgModule
as shown below (RC5 and later
),
import {CoursesComponent} from './courses.component';
@NgModule({
imports: [ BrowserModule],
declarations: [ AppComponent,CoursesComponent], //<----here
providers: [],
bootstrap: [ AppComponent ]
})
On Windows, I had this issue with static files cropping up under pydev/eclipse with python 2.7, due to an instance of django (1.8.7) that had been installed under cygwin. This caused a conflict between windows style paths and cygwin style paths. So, unfindable static files despite all the above fixes. I removed the extra distribution (so that all packages were installed by pip under windows) and this fixed the issue.
base on @Data-Base answer it will not work until make selection mode FullRow
MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
but if you need to make it work in CellSelect Mode
MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
// for cell selection
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hit = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
// cell selection
MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
How can I programatically (C#) ZIP a file (in Windows) without using any third party libraries?
If using the 4.5+ Framework, there is now the ZipArchive and ZipFile classes.
using (ZipArchive zip = ZipFile.Open("test.zip", ZipArchiveMode.Create))
{
zip.CreateEntryFromFile(@"c:\something.txt", "data/path/something.txt");
}
You need to add references to:
For .NET Core targeting net46, you need to add dependencies for
Example project.json:
"dependencies": {
"System.IO.Compression": "4.1.0",
"System.IO.Compression.ZipFile": "4.0.1"
},
"frameworks": {
"net46": {}
}
For .NET Core 2.0, just adding a simple using statement is all that is needed:
Create Proc[usp_mquestions]
(
@title nvarchar(500), --0
@tags nvarchar(max), --1
@category nvarchar(200), --2
@ispoll char(1), --3
@descriptions nvarchar(max), --4
)
AS
BEGIN TRY
BEGIN
DECLARE @message varchar(1000);
DECLARE @tempid bigint;
IF((SELECT count(id) from [xyz] WHERE title=@title)>0)
BEGIN
SELECT 'record already existed.';
END
ELSE
BEGIN
if @id=0
begin
select @tempid =id from [xyz] where id=@id;
if @tempid is null
BEGIN
INSERT INTO xyz
(entrydate,updatedate)
VALUES
(GETDATE(),GETDATE())
SET @tempid=@@IDENTITY;
END
END
ELSE
BEGIN
set @tempid=@id
END
if @tempid>0
BEGIN
-- Updation of table begin--
UPDATE tab_questions
set title=@title, --0
tags=@tags, --1
category=@category, --2
ispoll=@ispoll, --3
descriptions=@descriptions, --4
status=@status, --5
WHERE id=@tempid ; --9 ;
IF @id=0
BEGIN
SET @message= 'success:Record added successfully:'+ convert(varchar(10), @tempid)
END
ELSE
BEGIN
SET @message= 'success:Record updated successfully.:'+ convert(varchar(10), @tempid)
END
END
ELSE
BEGIN
SET @message= 'failed:invalid request:'+convert(varchar(10), @tempid)
END
END
END
END TRY
BEGIN CATCH
SET @message='failed:'+ ERROR_MESSAGE();
END CATCH
SELECT @message;
As GateKiller said you need to change the maxRequestLength. You may also need to change the executionTimeout in case the upload speed is too slow. Note that you don't want either of these settings to be too big otherwise you'll be open to DOS attacks.
The default for the executionTimeout is 360 seconds or 6 minutes.
You can change the maxRequestLength and executionTimeout with the httpRuntime Element.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime maxRequestLength="102400" executionTimeout="1200" />
</system.web>
</configuration>
EDIT:
If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.
If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:
public class Foo {
private static final int widgets;
static {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
widgets = first + second;
}
}
If first
and second
weren't in a block, they'd look like fields. If they were in a block without static
in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.
Now in this particular case, you could use a static method instead:
public class Foo {
private static final int widgets = getWidgets();
static int getWidgets() {
int first = Widgets.getFirstCount();
int second = Widgets.getSecondCount();
// Imagine more complex logic here which really used first/second
return first + second;
}
}
... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).
This one worked perfectly for me in JavaScript:
^[a-zA-Z]+[\s|-]?[a-zA-Z]+[\s|-]?[a-zA-Z]+$
Here is the method:
function isValidName(name) {
var found = name.search(/^[a-zA-Z]+[\s|-]?[a-zA-Z]+[\s|-]?[a-zA-Z]+$/);
return found > -1;
}
I think it is a problem(aka. bug) with the API you are using. JSONArray
implements Collection
(the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject
has an overloaded put()
method which takes a Collection and wraps it in a JSONArray
(thus causing the problem). I think you need to force the other JSONObject.put()
method to be used:
jsonObject.put("aoColumnDefs",(Object)arr);
You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection)
method is broken.
A call to vector<T>::size()
returns a value of type std::vector<T>::size_type
, not int, unsigned int or otherwise.
Also generally iteration over a container in C++ is done using iterators, like this.
std::vector<T>::iterator i = polygon.begin();
std::vector<T>::iterator end = polygon.end();
for(; i != end; i++){
sum += *i;
}
Where T is the type of data you store in the vector.
Or using the different iteration algorithms (std::transform
, std::copy
, std::fill
, std::for_each
et cetera).
All you need is a control that you can set the text of, and an UpdatePanel if the exception occurs during a postback.
If occurs during a postback: markup:
<ajax:UpdatePanel id="ErrorUpdatePanel" runat="server" UpdateMode="Coditional">
<ContentTemplate>
<asp:TextBox id="ErrorTextBox" runat="server" />
</ContentTemplate>
</ajax:UpdatePanel>
code:
try
{
do something
}
catch(YourException ex)
{
this.ErrorTextBox.Text = ex.Message;
this.ErrorUpdatePanel.Update();
}
The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be
int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());
and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be
int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());
In general, I break lines before operators, and indent the subsequent lines:
Map<long parameterization> longMap
= new HashMap<ditto>();
String longString = "some long text"
+ " some more long text";
To me, the leading operator clearly conveys that "this line was continued from something else, it doesn't stand on its own." Other people, of course, have different preferences.
In urlip3 there's no .urlopen
, instead try this:
import requests
html = requests.get(url)
Because the compiler needs to see them in order to inline them. And headers files are the "components" which are commonly included in other translation units.
#include "file.h"
// Ok, now me (the compiler) can see the definition of that inline function.
// So I'm able to replace calls for the actual implementation.
Another difference is when async
function returns just Task
instead of Task<T>
then you cannot use
GetFooAsync(...).Result;
Whereas
GetFooAsync(...).GetAwaiter().GetResult();
still works.
I know the example code in the question is for the case Task<T>
, however the question is asked generally.
I found how to run the query without error, but I hesitate to call it a "solution" without really understanding the underlying cause.
This more closely resembles the beginning of my actual query:
-- Comment
-- More comment
SELECT rf.flowrow, rf.stage, rf.process,
rf.instr instnum, rf.procedure_id, rtd_history.runtime, rtd_history.waittime
FROM
(
-- Comment at beginning of subquery
-- These two comment lines are the problem
SELECT sub2.flowrow, sub2.stage, sub2.process, sub2.instr, sub2.pid
FROM ( ...
The second set of comments above, at the beginning of the subquery, were the problem. When removed, the query executes. Other comments are fine. This is not a matter of some rogue or missing newline causing the following line to be commented, because the following line is a SELECT. A missing select would yield a different error than "not all variables bound."
I asked around and found one co-worker who has run into this -- comments causing query failures -- several times. Does anyone know how this can be the cause? It is my understanding that the very first thing a DBMS would do with comments is see if they contain hints, and if not, remove them during parsing. How can an ordinary comment containing no unusual characters (just letters and a period) cause an error? Bizarre.
foreach($array as $item=>$values){
echo $values->filepath;
}
The difference between PUT and PATCH is that:
PATCH requires some "patch language" to tell the server how to modify the resource. The caller and the server need to define some "operations" such as "add", "replace", "delete". For example:
GET /contacts/1
{
"id": 1,
"name": "Sam Kwee",
"email": "[email protected]",
"state": "NY",
"zip": "10001"
}
PATCH /contacts/1
{
[{"operation": "add", "field": "address", "value": "123 main street"},
{"operation": "replace", "field": "email", "value": "[email protected]"},
{"operation": "delete", "field": "zip"}]
}
GET /contacts/1
{
"id": 1,
"name": "Sam Kwee",
"email": "[email protected]",
"state": "NY",
"address": "123 main street",
}
Instead of using explicit "operation" fields, the patch language can make it implicit by defining conventions like:
in the PATCH request body:
With the above convention, the PATCH in the example can take the following form:
PATCH /contacts/1
{
"address": "123 main street",
"email": "[email protected]",
"zip":
}
Which looks more concise and user-friendly. But the users need to be aware of the underlying convention.
With the operations I mentioned above, the PATCH is still idempotent. But if you define operations like: "increment" or "append", you can easily see it won't be idempotent anymore.
No, you can't get it quite like background-size:cover
but..
This approach is pretty damn close: it uses JavaScript to determine if the image is landscape or portrait, and applies styles accordingly.
JS
$('.myImages img').load(function(){
var height = $(this).height();
var width = $(this).width();
console.log('widthandheight:',width,height);
if(width>height){
$(this).addClass('wide-img');
}else{
$(this).addClass('tall-img');
}
});
CSS
.tall-img{
margin-top:-50%;
width:100%;
}
.wide-img{
margin-left:-50%;
height:100%;
}
The correct parameter to set the maximum length is:
SET @@group_concat_max_len = value_numeric;
value_numeric
must be > 1024; by default the group_concat_max_len
value is 1024.
this code seems to have address the issue for me. it comes for a streaming class, ergo some of the nomenclature.
''' <summary> Reference to the awaiting task. </summary>
''' <value> The awaiting task. </value>
Protected ReadOnly Property AwaitingTask As Threading.Tasks.Task
''' <summary> Reference to the Action task; this task status undergoes changes. </summary>
Protected ReadOnly Property ActionTask As Threading.Tasks.Task
''' <summary> Reference to the cancellation source. </summary>
Protected ReadOnly Property TaskCancellationSource As Threading.CancellationTokenSource
''' <summary> Starts the action task. </summary>
''' <param name="taskAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
''' <returns> The awaiting task. </returns>
Private Async Function AsyncAwaitTask(ByVal taskAction As Action) As Task
Me._ActionTask = Task.Run(taskAction)
Await Me.ActionTask ' Task.Run(streamEntitiesAction)
Try
Me.ActionTask?.Wait()
Me.OnStreamTaskEnded(If(Me.ActionTask Is Nothing, TaskStatus.RanToCompletion, Me.ActionTask.Status))
Catch ex As AggregateException
Me.OnExceptionOccurred(ex)
Finally
Me.TaskCancellationSource.Dispose()
End Try
End Function
''' <summary> Starts Streaming the events. </summary>
''' <exception cref="InvalidOperationException"> Thrown when the requested operation is invalid. </exception>
''' <param name="bucketKey"> The bucket key. </param>
''' <param name="timeout"> The timeout. </param>
''' <param name="streamEntitiesAction"> The action to stream the entities, which calls
''' <see cref="StreamEvents(Of T)(IEnumerable(Of T), IEnumerable(Of Date), Integer, String)"/>. </param>
Public Overridable Sub StartStreamEvents(ByVal bucketKey As String, ByVal timeout As TimeSpan, ByVal streamEntitiesAction As Action)
If Me.IsTaskActive Then
Throw New InvalidOperationException($"Stream task is {Me.ActionTask.Status}")
Else
Me._TaskCancellationSource = New Threading.CancellationTokenSource
Me.TaskCancellationSource.Token.Register(AddressOf Me.StreamTaskCanceled)
Me.TaskCancellationSource.CancelAfter(timeout)
' the action class is created withing the Async/Await function
Me._AwaitingTask = Me.AsyncAwaitTask(streamEntitiesAction)
End If
End Sub
The method you want is toInt()
-- you have to be a little careful, since the toInt()
returns an optional Int.
let stringNumber = "1234"
let numberFromString = stringNumber.toInt()
// numberFromString is of type Int? with value 1234
let notANumber = "Uh oh"
let wontBeANumber = notANumber.toInt()
// wontBeANumber is of type Int? with value nil
On a BASH shell, you can very simply run:
export PATH=$PATH:`pwd`/somethingelse
No need to save the current working directory into a variable...
Download libeay32.dll and ssleay32.dll binary package for 32Bit and 64Bit from http://indy.fulgan.com/SSL/ then put it into executable or System32 directory.
There are many ways. Here are at least five:
/*
* An example of converting std::string to (const)char* using five
* different methods. Error checking is emitted for simplicity.
*
* Compile and run example (using gcc on Unix-like systems):
*
* $ g++ -Wall -pedantic -o test ./test.cpp
* $ ./test
* Original string (0x7fe3294039f8): hello
* s1 (0x7fe3294039f8): hello
* s2 (0x7fff5dce3a10): hello
* s3 (0x7fe3294000e0): hello
* s4 (0x7fe329403a00): hello
* s5 (0x7fe329403a10): hello
*/
#include <alloca.h>
#include <string>
#include <cstring>
int main()
{
std::string s0;
const char *s1;
char *s2;
char *s3;
char *s4;
char *s5;
// This is the initial C++ string.
s0 = "hello";
// Method #1: Just use "c_str()" method to obtain a pointer to a
// null-terminated C string stored in std::string object.
// Be careful though because when `s0` goes out of scope, s1 points
// to a non-valid memory.
s1 = s0.c_str();
// Method #2: Allocate memory on stack and copy the contents of the
// original string. Keep in mind that once a current function returns,
// the memory is invalidated.
s2 = (char *)alloca(s0.size() + 1);
memcpy(s2, s0.c_str(), s0.size() + 1);
// Method #3: Allocate memory dynamically and copy the content of the
// original string. The memory will be valid until you explicitly
// release it using "free". Forgetting to release it results in memory
// leak.
s3 = (char *)malloc(s0.size() + 1);
memcpy(s3, s0.c_str(), s0.size() + 1);
// Method #4: Same as method #3, but using C++ new/delete operators.
s4 = new char[s0.size() + 1];
memcpy(s4, s0.c_str(), s0.size() + 1);
// Method #5: Same as 3 but a bit less efficient..
s5 = strdup(s0.c_str());
// Print those strings.
printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
printf("s1 (%p): %s\n", s1, s1);
printf("s2 (%p): %s\n", s2, s2);
printf("s3 (%p): %s\n", s3, s3);
printf("s4 (%p): %s\n", s4, s4);
printf("s5 (%p): %s\n", s5, s5);
// Release memory...
free(s3);
delete [] s4;
free(s5);
}
You should be using a class
for multiple elements as an id
is meant to be only a single element. To answer your question on the .each()
syntax though, this is what it would look like:
$('#myID').each(function() {
$(this).remove();
});
Official JQuery documentation here.
For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"
I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.
let sortArray = array.sorted(by: { $0.name.lowercased() < $1.name.lowercased() })
Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:
var table = document.getElementById('tableID'),
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
console.log(this.innerHTML);
/* if you know it's going to be numeric:
console.log(parseInt(this.innerHTML),10);
*/
}
}
var table = document.getElementById('tableID'),_x000D_
cells = table.getElementsByTagName('td');_x000D_
_x000D_
for (var i = 0, len = cells.length; i < len; i++) {_x000D_
cells[i].onclick = function() {_x000D_
console.log(this.innerHTML);_x000D_
};_x000D_
}
_x000D_
th,_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column heading 1</th>_x000D_
<th>Column heading 2</th>_x000D_
<th>Column heading 3</th>_x000D_
<th>Column heading 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>43</td>_x000D_
<td>23</td>_x000D_
<td>89</td>_x000D_
<td>5</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>3</td>_x000D_
<td>0</td>_x000D_
<td>98</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>10</td>_x000D_
<td>32</td>_x000D_
<td>7</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
A revised approach, in response to the comment (below):
You're missing a semicolon. Also, don't make functions within a loop.
This revision binds a (single) named function as the click
event-handler of the multiple <td>
elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):
function logText() {
// 'this' is automatically passed to the named
// function via the use of addEventListener()
// (later):
console.log(this.textContent);
}
// using a CSS Selector, with document.querySelectorAll()
// to get a NodeList of <td> elements within the #tableID element:
var cells = document.querySelectorAll('#tableID td');
// iterating over the array-like NodeList, using
// Array.prototype.forEach() and Function.prototype.call():
Array.prototype.forEach.call(cells, function(td) {
// the first argument of the anonymous function (here: 'td')
// is the element of the array over which we're iterating.
// adding an event-handler (the function logText) to handle
// the click events on the <td> elements:
td.addEventListener('click', logText);
});
function logText() {_x000D_
console.log(this.textContent);_x000D_
}_x000D_
_x000D_
var cells = document.querySelectorAll('#tableID td');_x000D_
_x000D_
Array.prototype.forEach.call(cells, function(td) {_x000D_
td.addEventListener('click', logText);_x000D_
});
_x000D_
th,_x000D_
td {_x000D_
border: 1px solid #000;_x000D_
padding: 0.2em 0.3em 0.1em 0.3em;_x000D_
}
_x000D_
<table id="tableID">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>Column heading 1</th>_x000D_
<th>Column heading 2</th>_x000D_
<th>Column heading 3</th>_x000D_
<th>Column heading 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td>43</td>_x000D_
<td>23</td>_x000D_
<td>89</td>_x000D_
<td>5</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>4</td>_x000D_
<td>3</td>_x000D_
<td>0</td>_x000D_
<td>98</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>10</td>_x000D_
<td>32</td>_x000D_
<td>7</td>_x000D_
<td>2</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
References:
Nothing special. Just as same as common Java Class Instance.
But those class are Synthetic proxy classes
created by java.lang.reflect.Proxy#newProxyInstance
Introduced in 1.3
http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection
It is a part of Java. so each JVM should support it.
In short : they are created using JVM ASM tech ( defining javabyte code at runtime )
something using same tech:
java.lang.reflect.Proxy#newProxyInstance
getProxyClass0
to obtain a `Class
`
ProxyGenerator.generateProxyClass
which return a byte[]define class
to load the generated $Proxy
Class (the classname you have seen)each method is build with same bytecode like
invocation handler
's invoke()
invocation handler
's invoke()
the class(bytecode) represent in form of byte[]
How to draw a class
Thinking your java codes are compiled into bytecodes, just do this at runtime
core method in sun/misc/ProxyGenerator.java
generateClassFile
/**
* Generate a class file for the proxy class. This method drives the
* class file generation process.
*/
private byte[] generateClassFile() {
/* ============================================================
* Step 1: Assemble ProxyMethod objects for all methods to
* generate proxy dispatching code for.
*/
/*
* Record that proxy methods are needed for the hashCode, equals,
* and toString methods of java.lang.Object. This is done before
* the methods from the proxy interfaces so that the methods from
* java.lang.Object take precedence over duplicate methods in the
* proxy interfaces.
*/
addProxyMethod(hashCodeMethod, Object.class);
addProxyMethod(equalsMethod, Object.class);
addProxyMethod(toStringMethod, Object.class);
/*
* Now record all of the methods from the proxy interfaces, giving
* earlier interfaces precedence over later ones with duplicate
* methods.
*/
for (int i = 0; i < interfaces.length; i++) {
Method[] methods = interfaces[i].getMethods();
for (int j = 0; j < methods.length; j++) {
addProxyMethod(methods[j], interfaces[i]);
}
}
/*
* For each set of proxy methods with the same signature,
* verify that the methods' return types are compatible.
*/
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
checkReturnTypes(sigmethods);
}
/* ============================================================
* Step 2: Assemble FieldInfo and MethodInfo structs for all of
* fields and methods in the class we are generating.
*/
try {
methods.add(generateConstructor());
for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
for (ProxyMethod pm : sigmethods) {
// add static field for method's Method object
fields.add(new FieldInfo(pm.methodFieldName,
"Ljava/lang/reflect/Method;",
ACC_PRIVATE | ACC_STATIC));
// generate code for proxy method and add it
methods.add(pm.generateMethod());
}
}
methods.add(generateStaticInitializer());
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
if (methods.size() > 65535) {
throw new IllegalArgumentException("method limit exceeded");
}
if (fields.size() > 65535) {
throw new IllegalArgumentException("field limit exceeded");
}
/* ============================================================
* Step 3: Write the final class file.
*/
/*
* Make sure that constant pool indexes are reserved for the
* following items before starting to write the final class file.
*/
cp.getClass(dotToSlash(className));
cp.getClass(superclassName);
for (int i = 0; i < interfaces.length; i++) {
cp.getClass(dotToSlash(interfaces[i].getName()));
}
/*
* Disallow new constant pool additions beyond this point, since
* we are about to write the final constant pool table.
*/
cp.setReadOnly();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
try {
/*
* Write all the items of the "ClassFile" structure.
* See JVMS section 4.1.
*/
// u4 magic;
dout.writeInt(0xCAFEBABE);
// u2 minor_version;
dout.writeShort(CLASSFILE_MINOR_VERSION);
// u2 major_version;
dout.writeShort(CLASSFILE_MAJOR_VERSION);
cp.write(dout); // (write constant pool)
// u2 access_flags;
dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
// u2 this_class;
dout.writeShort(cp.getClass(dotToSlash(className)));
// u2 super_class;
dout.writeShort(cp.getClass(superclassName));
// u2 interfaces_count;
dout.writeShort(interfaces.length);
// u2 interfaces[interfaces_count];
for (int i = 0; i < interfaces.length; i++) {
dout.writeShort(cp.getClass(
dotToSlash(interfaces[i].getName())));
}
// u2 fields_count;
dout.writeShort(fields.size());
// field_info fields[fields_count];
for (FieldInfo f : fields) {
f.write(dout);
}
// u2 methods_count;
dout.writeShort(methods.size());
// method_info methods[methods_count];
for (MethodInfo m : methods) {
m.write(dout);
}
// u2 attributes_count;
dout.writeShort(0); // (no ClassFile attributes for proxy classes)
} catch (IOException e) {
throw new InternalError("unexpected I/O Exception");
}
return bout.toByteArray();
}
addProxyMethod
/**
* Add another method to be proxied, either by creating a new
* ProxyMethod object or augmenting an old one for a duplicate
* method.
*
* "fromClass" indicates the proxy interface that the method was
* found through, which may be different from (a subinterface of)
* the method's "declaring class". Note that the first Method
* object passed for a given name and descriptor identifies the
* Method object (and thus the declaring class) that will be
* passed to the invocation handler's "invoke" method for a given
* set of duplicate methods.
*/
private void addProxyMethod(Method m, Class fromClass) {
String name = m.getName();
Class[] parameterTypes = m.getParameterTypes();
Class returnType = m.getReturnType();
Class[] exceptionTypes = m.getExceptionTypes();
String sig = name + getParameterDescriptors(parameterTypes);
List<ProxyMethod> sigmethods = proxyMethods.get(sig);
if (sigmethods != null) {
for (ProxyMethod pm : sigmethods) {
if (returnType == pm.returnType) {
/*
* Found a match: reduce exception types to the
* greatest set of exceptions that can thrown
* compatibly with the throws clauses of both
* overridden methods.
*/
List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
collectCompatibleTypes(
exceptionTypes, pm.exceptionTypes, legalExceptions);
collectCompatibleTypes(
pm.exceptionTypes, exceptionTypes, legalExceptions);
pm.exceptionTypes = new Class[legalExceptions.size()];
pm.exceptionTypes =
legalExceptions.toArray(pm.exceptionTypes);
return;
}
}
} else {
sigmethods = new ArrayList<ProxyMethod>(3);
proxyMethods.put(sig, sigmethods);
}
sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
exceptionTypes, fromClass));
}
Full code about gen the proxy method
private MethodInfo generateMethod() throws IOException {
String desc = getMethodDescriptor(parameterTypes, returnType);
MethodInfo minfo = new MethodInfo(methodName, desc,
ACC_PUBLIC | ACC_FINAL);
int[] parameterSlot = new int[parameterTypes.length];
int nextSlot = 1;
for (int i = 0; i < parameterSlot.length; i++) {
parameterSlot[i] = nextSlot;
nextSlot += getWordsPerType(parameterTypes[i]);
}
int localSlot0 = nextSlot;
short pc, tryBegin = 0, tryEnd;
DataOutputStream out = new DataOutputStream(minfo.code);
code_aload(0, out);
out.writeByte(opc_getfield);
out.writeShort(cp.getFieldRef(
superclassName,
handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));
code_aload(0, out);
out.writeByte(opc_getstatic);
out.writeShort(cp.getFieldRef(
dotToSlash(className),
methodFieldName, "Ljava/lang/reflect/Method;"));
if (parameterTypes.length > 0) {
code_ipush(parameterTypes.length, out);
out.writeByte(opc_anewarray);
out.writeShort(cp.getClass("java/lang/Object"));
for (int i = 0; i < parameterTypes.length; i++) {
out.writeByte(opc_dup);
code_ipush(i, out);
codeWrapArgument(parameterTypes[i], parameterSlot[i], out);
out.writeByte(opc_aastore);
}
} else {
out.writeByte(opc_aconst_null);
}
out.writeByte(opc_invokeinterface);
out.writeShort(cp.getInterfaceMethodRef(
"java/lang/reflect/InvocationHandler",
"invoke",
"(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
"[Ljava/lang/Object;)Ljava/lang/Object;"));
out.writeByte(4);
out.writeByte(0);
if (returnType == void.class) {
out.writeByte(opc_pop);
out.writeByte(opc_return);
} else {
codeUnwrapReturnValue(returnType, out);
}
tryEnd = pc = (short) minfo.code.size();
List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
if (catchList.size() > 0) {
for (Class<?> ex : catchList) {
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc,
cp.getClass(dotToSlash(ex.getName()))));
}
out.writeByte(opc_athrow);
pc = (short) minfo.code.size();
minfo.exceptionTable.add(new ExceptionTableEntry(
tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));
code_astore(localSlot0, out);
out.writeByte(opc_new);
out.writeShort(cp.getClass(
"java/lang/reflect/UndeclaredThrowableException"));
out.writeByte(opc_dup);
code_aload(localSlot0, out);
out.writeByte(opc_invokespecial);
out.writeShort(cp.getMethodRef(
"java/lang/reflect/UndeclaredThrowableException",
"<init>", "(Ljava/lang/Throwable;)V"));
out.writeByte(opc_athrow);
}
curl --trace-ascii {filename} or use a single dash instead of file name to get it sent to stdout:
curl --trace-ascii - {URL}
CURLOPT_DEBUGFUNCTION if you're using libcurl
This shows you everything curl sends and receives, with some extra info thrown in.
improving the post of @Peter T, by gathering all solutions together at one place.
function myFunction() {
window.document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID" style="color:blue;"> With some data...</div>' );
}
function addElement(){
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'width:100%;height:10%;background:rgb(192,192,192);';
elemDiv.innerHTML = 'Added element with some data';
window.document.body.insertBefore(elemDiv, window.document.body.firstChild);
// document.body.appendChild(elemDiv); // appends last of that element
}
function addCSS() {
window.document.getElementsByTagName("style")[0].innerHTML += ".mycss {text-align:center}";
}
Using XPath
find the position of the Element in the DOM Tree and insert the specified text at a specified position to an XPath_Element. try this code over browser console.
function insertHTML_ByXPath( xpath, position, newElement) {
var element = document.evaluate(xpath, window.document, null, 9, null ).singleNodeValue;
element.insertAdjacentHTML(position, newElement);
element.style='border:3px solid orange';
}
var xpath_DOMElement = '//*[@id="answer-33669996"]/table/tbody/tr[1]/td[2]/div';
var childHTML = '<div id="Yash">Hi My name is <B>\"YASHWANTH\"</B></div>';
var position = 'beforeend';
insertHTML_ByXPath(xpath_DOMElement, position, childHTML);
vi can show all characters.
Since one div is initially hidden, you can simply call toggle for both divs:
<a href="javascript:void(0);" id="forgot-password">forgot password?</a>
<div id="login-form">login form</div>
<div id="recover-password" style="display:none;">recover password</div>
<script type="text/javascript">
$(function(){
$('#forgot-password').click(function(){
$('#login-form').toggle();
$('#recover-password').toggle();
});
});
</script>
You can also change the port when starting up:
$ pg_ctl -o "-F -p 5433" start
Or
$ postgres -p 5433
More about this in the manual.
I doubt the standard library supports this.
But you can use the google maps utility library:
http://code.google.com/p/google-maps-utility-library-v3/wiki/Libraries#MarkerWithLabel
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
var marker = new MarkerWithLabel({
position: myLatlng,
map: map,
draggable: true,
raiseOnDrag: true,
labelContent: "A",
labelAnchor: new google.maps.Point(3, 30),
labelClass: "labels", // the CSS class for the label
labelInBackground: false
});
The basics about marker can be found here: https://developers.google.com/maps/documentation/javascript/overlays#Markers
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
I would use a ByteArrayOutputStream
. And on finish you can call:
new String( baos.toByteArray(), codepage );
or better:
baos.toString( codepage );
For the String
constructor, the codepage
can be a String
or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.
The method toString()
accepts only a String
as a codepage
parameter (stand Java 8).
Try something like this
$state.go($state.$current.name, {... $state.params, 'key': newValue}, {notify: false})
Disclaimer: the following is a description of how I understand MVC-like patterns in the context of PHP-based web applications. All the external links that are used in the content are there to explain terms and concepts, and not to imply my own credibility on the subject.
The first thing that I must clear up is: the model is a layer.
Second: there is a difference between classical MVC and what we use in web development. Here's a bit of an older answer I wrote, which briefly describes how they are different.
The model is not a class or any single object. It is a very common mistake to make (I did too, though the original answer was written when I began to learn otherwise), because most frameworks perpetuate this misconception.
Neither is it an Object-Relational Mapping technique (ORM) nor an abstraction of database tables. Anyone who tells you otherwise is most likely trying to 'sell' another brand-new ORM or a whole framework.
In proper MVC adaptation, the M contains all the domain business logic and the Model Layer is mostly made from three types of structures:
A domain object is a logical container of purely domain information; it usually represents a logical entity in the problem domain space. Commonly referred to as business logic.
This would be where you define how to validate data before sending an invoice, or to compute the total cost of an order. At the same time, Domain Objects are completely unaware of storage - neither from where (SQL database, REST API, text file, etc.) nor even if they get saved or retrieved.
These objects are only responsible for the storage. If you store information in a database, this would be where the SQL lives. Or maybe you use an XML file to store data, and your Data Mappers are parsing from and to XML files.
You can think of them as "higher level Domain Objects", but instead of business logic, Services are responsible for interaction between Domain Objects and Mappers. These structures end up creating a "public" interface for interacting with the domain business logic. You can avoid them, but at the penalty of leaking some domain logic into Controllers.
There is a related answer to this subject in the ACL implementation question - it might be useful.
The communication between the model layer and other parts of the MVC triad should happen only through Services. The clear separation has a few additional benefits:
Prerequisites: watch lectures "Global State and Singletons" and "Don't Look For Things!" from the Clean Code Talks.
For both the View and Controller instances (what you could call: "UI layer") to have access these services, there are two general approaches:
As you might suspect, the DI container is a lot more elegant solution (while not being the easiest for a beginner). The two libraries, that I recommend considering for this functionality would be Syfmony's standalone DependencyInjection component or Auryn.
Both the solutions using a factory and a DI container would let you also share the instances of various servers to be shared between the selected controller and view for a given request-response cycle.
Now that you can access to the model layer in the controllers, you need to start actually using them:
public function postLogin(Request $request)
{
$email = $request->get('email');
$identity = $this->identification->findIdentityByEmailAddress($email);
$this->identification->loginWithPassword(
$identity,
$request->get('password')
);
}
Your controllers have a very clear task: take the user input and, based on this input, change the current state of business logic. In this example the states that are changed between are "anonymous user" and "logged in user".
Controller is not responsible for validating user's input, because that is part of business rules and controller is definitely not calling SQL queries, like what you would see here or here (please don't hate on them, they are misguided, not evil).
Ok, user has logged in (or failed). Now what? Said user is still unaware of it. So you need to actually produce a response and that is the responsibility of a view.
public function postLogin()
{
$path = '/login';
if ($this->identification->isUserLoggedIn()) {
$path = '/dashboard';
}
return new RedirectResponse($path);
}
In this case, the view produced one of two possible responses, based on the current state of model layer. For a different use-case you would have the view picking different templates to render, based on something like "current selected of article" .
The presentation layer can actually get quite elaborate, as described here: Understanding MVC Views in PHP.
Of course, there are situations, when this is a overkill.
MVC is just a concrete solution for Separation of Concerns principle. MVC separates user interface from the business logic, and it in the UI it separated handling of user input and the presentation. This is crucial. While often people describe it as a "triad", it's not actually made up from three independent parts. The structure is more like this:
It means, that, when your presentation layer's logic is close to none-existent, the pragmatic approach is to keep them as single layer. It also can substantially simplify some aspects of model layer.
Using this approach the login example (for an API) can be written as:
public function postLogin(Request $request)
{
$email = $request->get('email');
$data = [
'status' => 'ok',
];
try {
$identity = $this->identification->findIdentityByEmailAddress($email);
$token = $this->identification->loginWithPassword(
$identity,
$request->get('password')
);
} catch (FailedIdentification $exception) {
$data = [
'status' => 'error',
'message' => 'Login failed!',
]
}
return new JsonResponse($data);
}
While this is not sustainable, when you have complicate logic for rendering a response body, this simplification is very useful for more trivial scenarios. But be warned, this approach will become a nightmare, when attempting to use in large codebases with complex presentation logic.
Since there is not a single "Model" class (as explained above), you really do not "build the model". Instead you start from making Services, which are able to perform certain methods. And then implement Domain Objects and Mappers.
In the both approaches above there was this login method for the identification service. What would it actually look like. I am using a slightly modified version of the same functionality from a library, that I wrote .. because I am lazy:
public function loginWithPassword(Identity $identity, string $password): string
{
if ($identity->matchPassword($password) === false) {
$this->logWrongPasswordNotice($identity, [
'email' => $identity->getEmailAddress(),
'key' => $password, // this is the wrong password
]);
throw new PasswordMismatch;
}
$identity->setPassword($password);
$this->updateIdentityOnUse($identity);
$cookie = $this->createCookieIdentity($identity);
$this->logger->info('login successful', [
'input' => [
'email' => $identity->getEmailAddress(),
],
'user' => [
'account' => $identity->getAccountId(),
'identity' => $identity->getId(),
],
]);
return $cookie->getToken();
}
As you can see, at this level of abstraction, there is no indication of where the data was fetched from. It might be a database, but it also might be just a mock object for testing purposes. Even the data mappers, that are actually used for it, are hidden away in the private
methods of this service.
private function changeIdentityStatus(Entity\Identity $identity, int $status)
{
$identity->setStatus($status);
$identity->setLastUsed(time());
$mapper = $this->mapperFactory->create(Mapper\Identity::class);
$mapper->store($identity);
}
To implement an abstraction of persistence, on the most flexible approaches is to create custom data mappers.
From: PoEAA book
In practice they are implemented for interaction with specific classes or superclasses. Lets say you have Customer
and Admin
in your code (both inheriting from a User
superclass). Both would probably end up having a separate matching mapper, since they contain different fields. But you will also end up with shared and commonly used operations. For example: updating the "last seen online" time. And instead of making the existing mappers more convoluted, the more pragmatic approach is to have a general "User Mapper", which only update that timestamp.
Database tables and model
While sometimes there is a direct 1:1:1 relationship between a database table, Domain Object, and Mapper, in larger projects it might be less common than you expect:
Information used by a single Domain Object might be mapped from different tables, while the object itself has no persistence in the database.
Example: if you are generating a monthly report. This would collect information from different of tables, but there is no magical MonthlyReport
table in the database.
A single Mapper can affect multiple tables.
Example: when you are storing data from the User
object, this Domain Object could contain collection of other domain objects - Group
instances. If you alter them and store the User
, the Data Mapper will have to update and/or insert entries in multiple tables.
Data from a single Domain Object is stored in more than one table.
Example: in large systems (think: a medium-sized social network), it might be pragmatic to store user authentication data and often-accessed data separately from larger chunks of content, which is rarely required. In that case you might still have a single User
class, but the information it contains would depend of whether full details were fetched.
For every Domain Object there can be more than one mapper
Example: you have a news site with a shared codebased for both public-facing and the management software. But, while both interfaces use the same Article
class, the management needs a lot more info populated in it. In this case you would have two separate mappers: "internal" and "external". Each performing different queries, or even use different databases (as in master or slave).
A view is not a template
View instances in MVC (if you are not using the MVP variation of the pattern) are responsible for the presentational logic. This means that each View will usually juggle at least a few templates. It acquires data from the Model Layer and then, based on the received information, chooses a template and sets values.
One of the benefits you gain from this is re-usability. If you create a ListView
class, then, with well-written code, you can have the same class handing the presentation of user-list and comments below an article. Because they both have the same presentation logic. You just switch templates.
You can use either native PHP templates or use some third-party templating engine. There also might be some third-party libraries, which are able to fully replace View instances.
What about the old version of the answer?
The only major change is that, what is called Model in the old version, is actually a Service. The rest of the "library analogy" keeps up pretty well.
The only flaw that I see is that this would be a really strange library, because it would return you information from the book, but not let you touch the book itself, because otherwise the abstraction would start to "leak". I might have to think of a more fitting analogy.
What is the relationship between View and Controller instances?
The MVC structure is composed of two layers: ui and model. The main structures in the UI layer are views and controller.
When you are dealing with websites that use MVC design pattern, the best way is to have 1:1 relation between views and controllers. Each view represents a whole page in your website and it has a dedicated controller to handle all the incoming requests for that particular view.
For example, to represent an opened article, you would have \Application\Controller\Document
and \Application\View\Document
. This would contain all the main functionality for UI layer, when it comes to dealing with articles (of course you might have some XHR components that are not directly related to articles).
Try this:
$("#test-element").on("click" ,function() {
alert("click");
});
The document way of doing it is weird too. That would make sense to me if used for a class selector, but in the case of an id you probably just have useless DOM traversing there. In the case of the id selector, you get that element instantly.
Checkout BigDecimal
and BigInteger
.
Try with: $('.onediv').eq(0)
From the demo: Other examples of selectors and methods targeting the first LI
unside an UL
:
.eq()
Method:$('li').eq(0)
:eq()
selector:$('li:eq(0)')
.first()
Method$('li').first()
:first
selector:$('li:first')
:first-child
selector:$('li:first-child')
:lt()
selector:$('li:lt(1)')
:nth-child()
selector:$('li:nth-child(1)')
jQ + JS:
you can also use [i]
to get the JS HTMLelement
index out of the jQuery el. (array) collection like eg:
$('li')[0]
now that you have the JS element representation you have to use JS native methods eg:
$('li')[0].className = 'active'; // Adds class "active" to the first LI in the DOM
or you can (don't - it's bad design) wrap it back into a jQuery object
$( $('li')[0] ).addClass('active'); // Don't. Use .eq() instead
I think if you closed a program
taskkill /f /im "winamp.exe"
//....(winamp.exe is example)...
end, so if you want to start a program that you can use
start "" /normal winamp.exe
(/norma,/max/min are that process value cpu)
ALSO
if you want command line without openning an new window you write that
/B is 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.
There actually is a way to deploy to a device running a newer iOS that the particular version of Xcode
might not actually support. What you need to do is copy over the folder that contains the Developer Disk Image from the newer version of Xcode
.
For example, you can deploy to a device running iOS 9.3
using Xcode 7.2.1
(which only supports up to iOS 9.2
) using this method. Go to the Xcode 7.3
install and navigate to:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
From here, copy over the folder that contains the version you are trying to run on the older version of Xcode (for this example, it's 9.3 with the build number in parenthesis). Copy this folder over to the other install of Xcode, and now you should be able to deploy to a device running that particular version of iOS.
This will fail, however, if you're utilizing API calls that were specifically added to the newer version of the SDK
. In that case, you will be forced to update Xcode.
I have used text/comma-separated-values
for CSV mime-type in accept attribute and it works fine in Opera. Tried text/csv
without luck.
Some others MIME-Types for CSV if the suggested do not work:
I recently encountered this issue with .eot and .otf fonts producing the CSS3114 and CSS3111 errors in the console when loading. The solution that worked for me was to use only .woff and .woff2 formats with a .ttf format fallback. The .woff formats will be used before .ttf in most browsers and don't seem to trigger the font embedding permissions issue (css3114) and the font naming incorrect format issue (css3111). I found my solution in this extremely helpful article about the CSS3111 and CSS3114 issue, and also reading this article on using @font-face.
note: This solution does not require re-compiling, converting or editing any font files. It is a css-only solution. The font I tested with did have .eot, .otf, .woff, .woff2 and .svg versions generated for it, probably from the original .ttf source which did produce the 3114 error when i tried it, however the .woff and .woff2 files seemed to be immune to this issue.
This is what DID work for me with @font-face:
@font-face {
font-family: "Your Font Name";
font-weight: normal;
src: url('your-font-name.woff2') format('woff2'),
url('your-font-name.woff') format('woff'),
url('your-font-name.ttf') format('truetype');
}
This was what triggered the errors with @font-face in IE:
@font-face {
font-family: 'Your Font Name';
src: url('your-font-name.eot');
src: url('your-font-name.eot?#iefix') format('embedded-opentype'),
url('your-font-name.woff2') format('woff2'),
url('your-font-name.woff') format('woff'),
url('your-font-name.ttf') format('truetype'),
url('your-font-name.svg#svgFontName') format('svg');
}
Had same issue, and was solved by running regedit
, erasing some entries in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\ShellIconOverlayIdentifiers
and restarting.
Deleting OneDrive1... enties was not permited, but I had some from Google Drive.
You can also make a bakup by double-clicking in the registry directory and doing an "Export" to a file.
On Windows 10, most of the entries are used by OneDrive and you won't have permission to remove them. In order to do so, right click on the entry (Example: "OneDrive1", then click "Advanced", then click the link labled "Change" at the very top next to "Owner". This lets you change the owner. Type in your username and hit OK. Now give yourself "Full Control" and then apply it. Now you should be able to delete or rename it.
I stumbled over the same issue and found a nice solution which does not need any static ip configuration:
You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local
You can use that DNS name to reference it in another namespace via a local service:
kind: Service
apiVersion: v1
metadata:
name: service-y
namespace: namespace-a
spec:
type: ExternalName
externalName: service-x.namespace-b.svc.cluster.local
ports:
- port: 80
Use the MultiValueDict's get
method. This is also present on standard dicts and is a way to fetch a value while providing a default if it does not exist.
is_private = request.POST.get('is_private', False)
Generally,
my_var = dict.get(<key>, <default>)
Just before </body>
is the best place according to Yahoo Developer Network's Best Practices for Speeding Up Your Web Site this link, it makes sense.
The best thing to do is to test by yourself.
This could help:
$('#test').find('option[text="B"]').val();
This would give you the option with text B
and not the ones which has text that contains B
. Hope this helps
For recent versions of jQuery the above does not work. As commented by Quandary below, this is what works for jQuery 1.9.1:
$('#test option').filter(function () { return $(this).html() == "B"; }).val();
Can this not be done with a user-defined function to replicate whatever your stored procedure is doing?
SELECT udfMyFunction(user_id), someOtherField, etc FROM MyTable WHERE WhateverCondition
where udfMyFunction is a function you make that takes in the user ID and does whatever you need to do with it.
See http://www.sqlteam.com/article/user-defined-functions for a bit more background
I agree that cursors really ought to be avoided where possible. And it usually is possible!
(of course, my answer presupposes that you're only interested in getting the output from the SP and that you're not changing the actual data. I find "alters user data in a certain way" a little ambiguous from the original question, so thought I'd offer this as a possible solution. Utterly depends on what you're doing!)
I just want to make a specific point about the for in loop in Ruby. It might seem like a construct similar to other languages, but in fact it is an expression like every other looping construct in Ruby. In fact, the for in works with Enumerable objects just as the each iterator.
The collection passed to for in can be any object that has an each iterator method. Arrays and hashes define the each method, and many other Ruby objects do, too. The for/in loop calls the each method of the specified object. As that iterator yields values, the for loop assigns each value (or each set of values) to the specified variable (or variables) and then executes the code in body.
This is a silly example, but illustrates the point that the for in loop works with ANY object that has an each method, just like how the each iterator does:
class Apple
TYPES = %w(red green yellow)
def each
yield TYPES.pop until TYPES.empty?
end
end
a = Apple.new
for i in a do
puts i
end
yellow
green
red
=> nil
And now the each iterator:
a = Apple.new
a.each do |i|
puts i
end
yellow
green
red
=> nil
As you can see, both are responding to the each method which yields values back to the block. As everyone here stated, it is definitely preferable to use the each iterator over the for in loop. I just wanted to drive home the point that there is nothing magical about the for in loop. It is an expression that invokes the each method of a collection and then passes it to its block of code. Hence, it is a very rare case you would need to use for in. Use the each iterator almost always (with the added benefit of block scope).
That will work just fine. You can export an entire calendar with File
> Export…
, or individual events by dragging them to the Finder.
iCalendar (.ics
) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN:
and end with END:
. You'll mostly find VEVENT
sections (each of which represents an event) and VTIMEZONE
sections, each of which represents a time zone that's referenced from one or more events.
You can also do like this:
- command: "{{ item }}"
args:
chdir: "/src/package/"
with_items:
- "./configure"
- "/usr/bin/make"
- "/usr/bin/make install"
Hope that might help other
It is very likely that the pickled file is empty.
It is surprisingly easy to overwrite a pickle file if you're copying and pasting code.
For example the following writes a pickle file:
pickle.dump(df,open('df.p','wb'))
And if you copied this code to reopen it, but forgot to change 'wb'
to 'rb'
then you would overwrite the file:
df=pickle.load(open('df.p','wb'))
The correct syntax is
df=pickle.load(open('df.p','rb'))
You have various possibilies. The most simple and the most ugly is:
XAML
<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/>
Code Behind
private void Button_Clicked(object sender, RoutedEventArgs e) {
FrameworkElement fe=sender as FrameworkElement;
((YourClass)fe.DataContext).DoYourCommand();
}
Another solution (better) is to provide a ICommand-property on your YourClass
. This command will have already a reference to your YourClass
-object and therefore can execute an action on this class.
XAML
<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>
Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.
The default to open/add rows to a table is Edit Top 200 Rows. If you have more than 200 rows, like me now, then you need to change the default setting. Here's what I did to change the edit default to 300:
Beginner, not too elegant, but shows the basic steps and deductions in JavaScript
/* Array Four Million Numbers */
var j = [];
var x = [1,2];
var even = [];
for (var i = 1;i<4000001;i++){
j.push(i);
}
// Array Even Million
i = 1;
while (i<4000001){
var k = j[i] + j[i-1];
j[i + 1] = k;
if (k < 4000001){
x.push(k);
}
i++;
}
var total = 0;
for (w in x){
if (x[w] %2 === 0){
even.push(x[w]);
}
}
for (num in even){
total += even[num];
}
console.log(x);
console.log(even);
console.log(total);
In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.
Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the executable but an environment variable in the OS. You can then check the stack size with ulimit -s
and set it to a new value with for example ulimit -s 16384
.
Here's a link with default stack sizes for gcc.
DFS without recursion:
std::stack<Node> dfs;
dfs.push(start);
do {
Node top = dfs.top();
if (top is what we are looking for) {
break;
}
dfs.pop();
for (outgoing nodes from top) {
dfs.push(outgoing node);
}
} while (!dfs.empty())
/* while loop
5 bucks
1 chocolate = 1 bucks
while my money is greater than 1 bucks
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1
end
come to home and cant go to while shop because my money = 0 bucks */
#include<stdio.h>
int main(){
int money = 5;
while( money >= 1){
printf("inside the shopk and selecting chocolate\n");
printf("after selecting chocolate paying 1 bucks\n");
money = money - 1 ;
printf("my remaining moeny = %d\n", money);
printf("\n\n");
}
printf("dont have money cant go inside the shop, money = %d", money);
return 0;
}
infinite money
while( codition ){ // condition will always true ....infinite loop
statement(s)
}
please visit this video for better understanding https://www.youtube.com/watch?v=eqDv2wxDMJ8&t=25s
/* for loop
5 bucks
for my money is greater than equal to 1 bucks 0 money >= 1
select chocolate
pay 1 bucks to the shopkeeper
money = money - 1 1-1 => 0
end
*/
#include<stdio.h>
int main(){
int money = 5;
for( ; money >= 1; ){ 0>=1 false
printf("select chocolate \n");
printf("paying 1 bucks to the shopkeeper\n");
money = money - 1; 1-1 = 0
printf(" remaining money =%d\n", money);
printf("\n\n");
}
return 0;
}
For better understanding please visit https://www.youtube.com/watch?v=_vdvyzzp-R4&t=25s
For me, I was getting latest from source control and this happened.
The applicationhost.config file's virtualDirectory path was different than in my machine.
I restored my own copy and it works. I am using IIS express.
Store the return of setInterval
in a variable, and use it later to clear the interval.
var timer = null;
$("textarea").blur(function(){
timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
if(timer){
window.clearInterval(timer);
timer = null
}
});
In IntelliJ Do as they say in eclipse "If you're facing this problem with Eclipse, I've been following many different solutions but the one that worked for me is this:
Right click your project folder and open up Properties.
From the right panel, select Java Build Path then go to Libraries tab.
Select Add External JARs to import the mysql driver.
From the right panel, select Deployment Assembly.
Select Add..., then select Java Build Path Entries and click Next.
You should see the sql driver on the list. Select it and click first.
And that's it! Try to run it again! Cheers!"
Here we have to add the jar file in Project Structure -> Libraries -> +(add)
If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot
You can use the following regex to replace non-ASCII characters
str = str.replace(/[^A-Za-z 0-9 \.,\?""!@#\$%\^&\*\(\)-_=\+;:<>\/\\\|\}\{\[\]`~]*/g, '')
However, note that spaces, colons and commas are all valid ASCII, so the result will be
> str
"INFO] :, , , (Higashikurume)"
<tbody *ngFor="let defect of items">
<tr>
<td>{{defect.param1}}</td>
<td>{{defect.param2}}</td>
<td>{{defect.param3}}</td>
<td>{{defect.param4}}</td>
<td>{{defect.param5}} </td>
<td>{{defect.param6}}</td>
<td>{{defect.param7}}</td>
</tr>
<tr>
<td> <strong> Notes:</strong></td>
<td colspan="6"> {{defect.param8}}
</td>`enter code here`
</tr>
</tbody>
Don't use NULL
, C++ allows you to use the unadorned 0
instead:
previous = 0;
next = 0;
And, as at C++11, you generally shouldn't be using either NULL
or 0
since it provides you with nullptr
of type std::nullptr_t
, which is better suited to the task.
The problem lies in https.conf file!
# Virtual hosts
# Include conf/extra/httpd-vhosts.conf
The error occurs when hash(#) is removed or messed around with. These two lines should appear as shown above.
Your return function is in line of def function(main function), you must give one tab to it. And Use
%%debug
instead of
%debug
to debug the whole cell not only line. Hope, maybe this will help you.
I faced this issue too. I was using jquery.poptrox.min.js
for image popping and zooming and I received an error which said:
“Uncaught TypeError: a.indexOf is not a function” error.
This is because indexOf
was not supported in 3.3.1/jquery.min.js
so a simple fix to this is to change it to an old version 2.1.0/jquery.min.js
.
This fixed it for me.
Use .toInt()
for int .toFloat()
for float and .toDouble()
for double
I think pressing Q should work.
You can concatenate two transitions or more, and visibility
is what comes handy this time.
div {_x000D_
border: 1px solid #eee;_x000D_
}_x000D_
div > ul {_x000D_
visibility: hidden;_x000D_
opacity: 0;_x000D_
transition: visibility 0s, opacity 0.5s linear;_x000D_
}_x000D_
div:hover > ul {_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
}
_x000D_
<div>_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 2</li>_x000D_
<li>Item 3</li>_x000D_
</ul>_x000D_
</div>
_x000D_
(Don't forget the vendor prefixes to the transition
property.)
More details are in this article.
json
is a built-in module, you don't need to install it with pip
.
I had to install RazorGenerator.Templating
to get it all to work. From the NuGet console, type:
Install-Package RazorGenerator.Templating
Besides the redundant )
this expression will always be true
because currentStatus
will always match one of these two conditions:
currentStatus !== 'open' || currentStatus !== 'reopen'
perhaps you mean one of
!(currentStatus === 'open' || currentStatus === 'reopen')
(currentStatus !== 'open' && currentStatus !== 'reopen')
To kill from the application, you can do:
android.os.Process.killProcess(android.os.Process.myPid());
I found Steve Hibbert's response to be very helpful. The problem the OP seemed to be describing is that of an AutoGeneratedColumns on a GridView.
In this instance you can set which columns will be "visible" and which will be hidden when you bind a data table in the code behind.
For example: A Gridview is on the page as follows.
<asp:GridView ID="gv" runat="server" AutoGenerateColumns="False" >
</asp:GridView>
And then in the code behind a PopulateGridView routine is called during the page load event.
protected void PopulateGridView()
{
DataTable dt = GetDataSource();
gv.DataSource = dt;
foreach (DataColumn col in dt.Columns)
{
BoundField field = new BoundField();
field.DataField = col.ColumnName;
field.HeaderText = col.ColumnName;
if (col.ColumnName.EndsWith("ID"))
{
field.Visible = false;
}
gv.Columns.Add(field);
}
gv.DataBind();
}
In the above the GridView AutoGenerateColumns is set to False and the codebehind is used to create the bound fields. One is obtaining the datasource as a datatable through one's own process which here I labeled GetDataSource(). Then one loops through the columns collection of the datatable. If the column name meets a given criteria, you can set the bound field visible property accordingly. Then you bind the data to the gridview. This is very similar to AutoGenerateColumns="True" but you get to have criteria for the columns. This approach is most useful when the criteria for hiding and un-hiding is based upon the column name.
In the latest version of Twitter Bootstrap the layout is fluid by default, hence you don't need extra classes to declare your layout as fluid.
You can further refer to -
http://bassjobsen.weblogs.fm/migrate-your-templates-from-twitter-bootstrap-2-x-to-twitter-bootstrap-3/ http://blog.getbootstrap.com/
To remove a element from scope use:
// remove an item
$scope.remove = function(index) {
$scope.items.splice(index, 1);
};
In Order to obtain real path to the file you can try this:
URL fileUrl = Resourceloader.class.getResource("resources/repository/SSL-Key/cert.jks");
String pathToClass = fileUrl.getPath;
Resourceloader is classname here. "resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.
This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(fileUrl.openStream()));
A simple way is to use a configuration data object, save it as an XML file with the name of the application in the local Folder and on startup read it back.
Here is an example to store the position and size of a form.
The configuration dataobject is strongly typed and easy to use:
[Serializable()]
public class CConfigDO
{
private System.Drawing.Point m_oStartPos;
private System.Drawing.Size m_oStartSize;
public System.Drawing.Point StartPos
{
get { return m_oStartPos; }
set { m_oStartPos = value; }
}
public System.Drawing.Size StartSize
{
get { return m_oStartSize; }
set { m_oStartSize = value; }
}
}
A manager class for saving and loading:
public class CConfigMng
{
private string m_sConfigFileName = System.IO.Path.GetFileNameWithoutExtension(System.Windows.Forms.Application.ExecutablePath) + ".xml";
private CConfigDO m_oConfig = new CConfigDO();
public CConfigDO Config
{
get { return m_oConfig; }
set { m_oConfig = value; }
}
// Load configuration file
public void LoadConfig()
{
if (System.IO.File.Exists(m_sConfigFileName))
{
System.IO.StreamReader srReader = System.IO.File.OpenText(m_sConfigFileName);
Type tType = m_oConfig.GetType();
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
object oData = xsSerializer.Deserialize(srReader);
m_oConfig = (CConfigDO)oData;
srReader.Close();
}
}
// Save configuration file
public void SaveConfig()
{
System.IO.StreamWriter swWriter = System.IO.File.CreateText(m_sConfigFileName);
Type tType = m_oConfig.GetType();
if (tType.IsSerializable)
{
System.Xml.Serialization.XmlSerializer xsSerializer = new System.Xml.Serialization.XmlSerializer(tType);
xsSerializer.Serialize(swWriter, m_oConfig);
swWriter.Close();
}
}
}
Now you can create an instance and use in your form's load and close events:
private CConfigMng oConfigMng = new CConfigMng();
private void Form1_Load(object sender, EventArgs e)
{
// Load configuration
oConfigMng.LoadConfig();
if (oConfigMng.Config.StartPos.X != 0 || oConfigMng.Config.StartPos.Y != 0)
{
Location = oConfigMng.Config.StartPos;
Size = oConfigMng.Config.StartSize;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// Save configuration
oConfigMng.Config.StartPos = Location;
oConfigMng.Config.StartSize = Size;
oConfigMng.SaveConfig();
}
And the produced XML file is also readable:
<?xml version="1.0" encoding="utf-8"?>
<CConfigDO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<StartPos>
<X>70</X>
<Y>278</Y>
</StartPos>
<StartSize>
<Width>253</Width>
<Height>229</Height>
</StartSize>
</CConfigDO>
A working example:
// Add an event listener
document.addEventListener("name-of-event", function(e) {
console.log(e.detail); // Prints "Example of an event"
});
// Create the event
var event = new CustomEvent("name-of-event", { "detail": "Example of an event" });
// Dispatch/Trigger/Fire the event
document.dispatchEvent(event);
For older browsers polyfill and more complex examples, see MDN docs.
See support tables for EventTarget.dispatchEvent
and CustomEvent
.
Try using a format file since your data file only has 4 columns. Otherwise, try OPENROWSET
or use a staging table.
myTestFormatFiles.Fmt
may look like:
9.0 4 1 SQLINT 0 3 "," 1 StudentNo "" 2 SQLCHAR 0 100 "," 2 FirstName SQL_Latin1_General_CP1_CI_AS 3 SQLCHAR 0 100 "," 3 LastName SQL_Latin1_General_CP1_CI_AS 4 SQLINT 0 4 "\r\n" 4 Year "
(source: microsoft.com)
This tutorial on skipping a column with BULK INSERT
may also help.
Your statement then would look like:
USE xta9354
GO
BULK INSERT xta9354.dbo.Students
FROM 'd:\userdata\xta9_Students.txt'
WITH (FORMATFILE = 'C:\myTestFormatFiles.Fmt')
Something like this?
<a href="#" onClick="MyWindow=window.open('http://www.google.com','MyWindow','width=600,height=300'); return false;">Click Here</a>
You can view which modules (compiled in) are available via terminal through php -m
Here's how I fixed it:
nltk.download()
.The download graphic window opened and all the packages got installed.Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.
Here are the commands to retrieve key value:
<key>
<key>
<key> <start> <end>
<key>
<key> <min> <max>
Use the TYPE
command to check the type of value a key is mapping to:
<key>
Please check your listenning ports with :
netstat -nat |grep :3306
If it show
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN
Thats is ok for your remote connection.
But in this case i think you have
tcp 0 192.168.1.3:3306 0.0.0.0:* LISTEN
Thats is ok for your remote connection. You should also check your firewall (iptables if you centos/redhat)
services iptables stop
for testing or use :
iptables -A input -p tcp -i eth0 --dport 3306 -m state NEW,ESTABLISHED -j ACCEPT
iptables -A output -p tcp -i eth0 --sport 3306 -m state NEW,ESTABLISHED -j ACCEPT
And another thing to check your grant permission for remote connection :
GRANT ALL ON *.* TO remoteUser@'remoteIpadress' IDENTIFIED BY 'my_password';
$('.radio-button-class-name').is('checked') didn't work for me, but the next code worked well:
if(typeof $('.radio-button-class-name:checked').val() !== 'undefined'){
// radio button is checked
}
I had challenge with users innocently entering € and some using double quotes to define their content. I tweaked a couple of answers from this page and others to finally define my small little work-around
$products = array($ofDirtyArray);
if($products !=null) {
header("Content-type: application/json");
header('Content-Type: charset=utf-8');
array_walk_recursive($products, function(&$val) {
$val = html_entity_decode(htmlentities($val, ENT_QUOTES, "UTF-8"));
});
echo json_encode($products, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
}
I hope it helps someone/someone improves it.
Try typing in 'cls', if that doesn't work, type 'Clear' capital C. No quotes for any. Hope this helps.