WHERE id <> 2
should work fine...Is that what you are after?
Create a Java archive (.jar) file using NetBeans as follows:
Clean and Build will first delete build artifacts (such as .class
files), whereas Build will retain any existing .class
files, creating new versions necessary. To elucidate, imagine a project with two classes, A and B.
When built the first time, the IDE creates A.class
and B.class
. Now you delete B.java
but don't clear out B.class
. Executing Build should leave B.class
in the build directory, and bundle it into the JAR. Selecting Clean and Build will delete B.class
. Since B.java
was deleted, no longer will B.class
be bundled.
The JAR file is built. To view it inside NetBeans:
Ensure files aren't being excluded when building the JAR file.
Try Case
SELECT stock.name,
CASE
WHEN stock.quantity <20 THEN 'Buy urgent'
ELSE 'There is enough'
END
FROM stock
Laravel provides a method called keyBy
which allows to set keys by given key in model.
$collection = $collection->keyBy('id');
will return the collection but with keys being the values of id
attribute from any model.
Then you can say:
$desired_food = $foods->get(21); // Grab the food with an ID of 21
and it will grab the correct item without the mess of using a filter function.
You don't need to copy a Python string. They are immutable, and the copy
module always returns the original in such cases, as do str()
, the whole string slice, and concatenating with an empty string.
Moreover, your 'hello'
string is interned (certain strings are). Python deliberately tries to keep just the one copy, as that makes dictionary lookups faster.
One way you could work around this is to actually create a new string, then slice that string back to the original content:
>>> a = 'hello'
>>> b = (a + '.')[:-1]
>>> id(a), id(b)
(4435312528, 4435312432)
But all you are doing now is waste memory. It is not as if you can mutate these string objects in any way, after all.
If all you wanted to know is how much memory a Python object requires, use sys.getsizeof()
; it gives you the memory footprint of any Python object.
For containers this does not include the contents; you'd have to recurse into each container to calculate a total memory size:
>>> import sys
>>> a = 'hello'
>>> sys.getsizeof(a)
42
>>> b = {'foo': 'bar'}
>>> sys.getsizeof(b)
280
>>> sys.getsizeof(b) + sum(sys.getsizeof(k) + sys.getsizeof(v) for k, v in b.items())
360
You can then choose to use id()
tracking to take an actual memory footprint or to estimate a maximum footprint if objects were not cached and reused.
Not exactly answering your question, but if you could move away from your self-made wrapper then there is Simple Logging Facade for Java (SLF4J) which Hibernate has now switched to (instead of commons logging).
SLF4J suffers from none of the class loader problems or memory leaks observed with Jakarta Commons Logging (JCL).
SLF4J supports JDK logging, log4j and logback. So then it should be fairly easy to switch from log4j to logback when the time is right.
Edit: Aplogies that I hadn't made myself clear. I was suggesting using SLF4J to isolate yourself from having to make a hard choice between log4j or logback.
The smallest change to fix this would be to change
onClick="document.getElementById("datepicker").click()">
to
onClick="$('#datepicker').click()">
click()
is a jQuery method. Also, you had a collision between the double-quotes used for the HTML element attribute and those use for the JavaScript function argument.
If you want a real timer you need to use the date object.
Calculate the difference.
Format your string.
window.onload=function(){
var start=Date.now(),r=document.getElementById('r');
(function f(){
var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
if(diff>3e5){
start=Date.now()
}
setTimeout(f,1e3);
})();
}
Example
not so precise timer
var time=5*60,r=document.getElementById('r'),tmp=time;
setInterval(function(){
var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
tmp!=0||(tmp=time);
},1000);
Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.
Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\
pause
command is what you looking for.
If you looking ONLY the case when enter is hit you can abuse the runas
command:
runas /user:# "" >nul 2>&1
the screen will be frozen until enter is hit.What I like more than set/p=
is that if you press other buttons than enter they will be not displayed.
Something like this should work
var text = $('#toptitle').text();
if (text == 'Profil'){
$('#toptitle').text('New Word');
}
You are using an old version of the date picker js. Upgrade datepicker js with latest one.
Replace your bootstrap-datetimepicker.min.js file with this will work..
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/3.1.3/js/bootstrap-datetimepicker.min.js"></script>
Another option is to check if it's busy with a timer:
Set the timer as disabled by default. Then whenever navigating, enable it. i.e.:
WebBrowser1.Navigate("https://www.somesite.com")
tmrBusy.Enabled = True
And the timer:
Private Sub tmrBusy_Tick(sender As Object, e As EventArgs) Handles tmrBusy.Tick
If WebBrowser1.IsBusy = True Then
Debug.WriteLine("WB Busy ...")
Else
Debug.WriteLine("WB Done.")
tmrBusy.Enabled = False
End If
End Sub
In ES6, you can do like this.
var key = "name";
var person = {[key]:"John"}; // same as var person = {"name" : "John"}
console.log(person); // should print Object { name="John"}
var key = "name";_x000D_
var person = {[key]:"John"};_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
Its called Computed Property Names, its implemented using bracket notation( square brackets) []
Example: { [variableName] : someValue }
Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name.
For ES5, try something like this
var yourObject = {};
yourObject[yourKey] = "yourValue";
console.log(yourObject );
example:
var person = {};
var key = "name";
person[key] /* this is same as person.name */ = "John";
console.log(person); // should print Object { name="John"}
var person = {};_x000D_
var key = "name";_x000D_
_x000D_
person[key] /* this is same as person.name */ = "John";_x000D_
_x000D_
console.log(person); // should print Object { name="John"}
_x000D_
If you want to check the changed files you need to take care of many small things like which will be best to use , like if you want to check which of the files changed just type
git status -- it will show the files with changes
then if you want to know what changes are to be made it can be checked in ways ,
git diff -- will show all the changes in all files
it is good only when only one file is modified
and if you want to check particular file then use
git diff
Hi,
Well, I have tried the methods mentioned above! it's working yes, but not exactly the way I wanted. I wanted to redirect the default page extension to the main domain with our further action.
Here how I do that...
# Accesible Index Page
<IfModule dir_module>
DirectoryIndex index.php index.html
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.(html|htm|php|php3|php5|shtml|phtml) [NC]
RewriteRule ^index\.html|htm|php|php3|php5|shtml|phtml$ / [R=301,L]
</IfModule>
The above code simply captures any index.* and redirect it to the main domain.
Thank you
Compromise minimum solution:
| One | Two | Three | Four | Five | Six
| -
| Span <td colspan=3>triple <td colspan=2>double
So you can omit closing </td>
for speed, ?r can leave for consistency.
Result from http://markdown-here.com/livedemo.html :
Works in Jupyter Markdown.
As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.
| One | Two | Three | Four | Five | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple <td colspan=2>double
minimally:
One | Two | Three | Four | Five | Six
-|||||-
Span <td colspan=3>triple <td colspan=2>double
Use this in your batch file:
%~dp0\bin\Iris.exe
%~dp0
resolves to the full path of the folder in which the batch script resides.
Working with Angular 7 I needed to create a file upload with a description of the file.
HTML:
<div>
File Description: <input type="text" (change)="updateFileDescription($event.target.value)" #fileDescription />
</div>
<div>
<input type="file" accept="*" capture (change)="handleFileInput($event.target.files)" #fileInput /> <button class="btn btn-light" (click)="uploadFileToActivity()">Upload</button>
</div>
Here is the Component file
@ViewChild('fileDescription') fileDescriptionInput: ElementRef;
@ViewChild('fileInput') fileInput: ElementRef;
ClearInputs(){
this.fileDescriptionInput.nativeElement.value = '';
this.fileInput.nativeElement.value = '';
}
This will do the trick.
If you are running a website, you could also try to set your application pool to disable 32-bit Applications (under advanced settings of a pool).
Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:
var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;
The following should help
realpath
— Returns canonicalized absolute pathnameis_writable
— Tells whether the filename is writableunlink
— Deletes a fileRun your filepath through realpath, then check if the returned path is writable and if so, unlink it.
You can do this simply like this
$('#image_id').click(function() {
$("#some_id iframe").attr('src', $("#some_id iframe", parent).attr('src') + '?autoplay=1');
});
where image_id is your image id you are clicking and some_id is id of div in which iframe is also you can use iframe id directly.
This answer posted by Todd helped me.
find . -maxdepth 1 -type d \( ! -name . \) -exec bash -c "cd '{}' && pwd" \;
The \( ! -name . \)
avoids executing the command in current directory.
Yes, you need to use global foo
if you are going to write to it.
foo = []
def bar():
global foo
...
foo = [1]
Just a recommendation:
I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp
via a system
call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn't require any installation of extra libraries or extensions in PHP.
Could be the way to go if you don't want to use the ssh2
extensions
Try This
SELECT @PrimaryContactKey = c.PrimaryCntctKey
FROM tarcustomer c, tarinvoice i
WHERE i.custkey = c.custkey
AND i.invckey = @tmp_key
UPDATE tarinvoice SET confirmtocntctkey = @PrimaryContactKey
WHERE invckey = @tmp_key
FETCH NEXT FROM @get_invckey INTO @tmp_key
You would declare this variable outside of your loop as just a standard TSQL variable.
I should also note that this is how you would do it for any type of select into a variable, not just when dealing with cursors.
You can use the workbook.get_worksheet_by_name() feature: https://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
According to https://xlsxwriter.readthedocs.io/changes.html the feature has been added on May 13, 2016.
"Release 0.8.7 - May 13 2016
-Fix for issue when inserting read-only images on Windows. Issue #352.
-Added get_worksheet_by_name() method to allow the retrieval of a worksheet from a workbook via its name.
-Fixed issue where internal file creation and modification dates were in the local timezone instead of UTC."
This should be called a warning, not an error. At least the email says that the icon file is "recommended" and not "required". You can safely ignore this warning if you target iOS 6. Of course, for iOS 7 you would need the new dimensions and also look out for the new rounding of the icon's corners
Tips from 2020:
From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:
$ pip install -U flask
If you are using flask run
instead of app.run()
with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads
):
$ flask run --with-threads
It's same as app.run(threaded=True)
Actually I would do it this way:
L1 is the index list of elements satisfying condition 1;(maybe you can use somelist.index(condition1)
or np.where(condition1)
to get L1.)
Similarly, you get L2, a list of elements satisfying condition 2;
Then you find intersection using intersect(L1,L2)
.
You can also find intersection of multiple lists if you get multiple conditions to satisfy.
Then you can apply index in any other array, for example, x.
I had this problem when trying to consume a value returned from a stored procedure.
console.log(result[0]);
would output "[ RowDataPacket { datetime: '2019-11-15 16:37:05' } ]".
I found that
console.log(results[0][0].datetime);
Gave me the value I wanted.
declare
seprator varchar2(1):=',';
dosweeklist varchar2(4000):='a,b,c';
begin
for i in (SELECT SUBSTR(dosweeklist,
case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end,
NVL(NULLIF(INSTR(dosweeklist,seprator,1,LEVEL),0),length(dosweeklist)+1) - case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end) dat
FROM dual
CONNECT BY LEVEL <= LENGTH(dosweeklist) - LENGTH(REPLACE(dosweeklist,seprator,'')) +1)
loop
dbms_output.put_line(i.dat);
end loop;
end;
/
so select query only in for loop can do the trick, by replacing dosweeklist as your delimited string and seprator as your delimited character.
Lets see output
a
b
c
I had similar situation like Hobhouse. I wanted to use command
ssh myhost.com 'some_command'
and 'some_command' exists in '/var/some_location' so I tried to append '/var/some_location' in PATH environment by editing '$HOME/.bashrc'
but that wasn't working. because default .bashrc(Ubuntu 10.4 LTS) prevent from sourcing by code like below
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
so If you want to change environment for ssh non-login shell. you should add code above that line.
This is happens because Jenkins is not aware about the shell path. In Manage Jenkins -> Configure System -> Shell, set the shell path as
This is a String
extension written in Swift to return a HTML string as NSAttributedString
.
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
return html
}
}
To use,
label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()
In the above, I have purposely added a unicode \u2022 to show that it renders unicode correctly.
A trivial: The default encoding that NSAttributedString
uses is NSUTF16StringEncoding
(not UTF8!).
I've created a vertical menu and tabs changing in the middle of the page. I changed two words on the code source and I set apart two different divs
menu:
<div class="arrowgreen">
<ul class="tabNavigation">
<li> <a href="#first" title="Home">Tab 1</a></li>
<li> <a href="#secund" title="Home">Tab 2</a></li>
</ul>
</div>
content:
<div class="pages">
<div id="first">
CONTENT 1
</div>
<div id="secund">
CONTENT 2
</div>
</div>
the code works with the div apart
$(function () {
var tabContainers = $('div.pages > div');
$('div.arrowgreen ul.tabNavigation a').click(function () {
tabContainers.hide().filter(this.hash).show();
$('div.arrowgreen ul.tabNavigation a').removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(':first').click();
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />
<div class="View"><?php include 'Small.php'; ?></div>
<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
function ()
{
$('.View').load('Small.php').fadeIn("slow");
}, 15000); // refresh every 15000 milliseconds
$.ajaxSetup({ cache: true });
});
</script>
I may consider performance and memory utilization. One big difference is that EAGER fetch strategy allows to use fetched data object without session. Why?
All data is fetched when eager marked data in the object when session is connected. However, in case of lazy loading strategy, lazy loading marked object does not retrieve data if session is disconnected (after session.close()
statement). All that can be made by hibernate proxy. Eager strategy lets data to be still available after closing session.
You could create a List<Object>
, but you really don't want to do this. Mixed lists that abstract to Object are not very useful and are a potential source of bugs. In fact the fact that your code requires such a construct gives your code a bad code smell and suggests that its design may be off. Consider redesigning your program so you aren't forced to collect oranges with orangutans.
Instead -- do what G V recommends and I was about to recommend, create a custom class that holds both int and String and create an ArrayList of it. 1+ to his answer!
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
There are two ways. One is to aggregate:
SELECT array_agg(column_name::TEXT)
FROM information.schema.columns
WHERE table_name = 'aean'
The other is to use an array constructor:
SELECT ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name = 'aean')
I'm presuming this is for plpgsql. In that case you can assign it like this:
colnames := ARRAY(
SELECT column_name
FROM information.schema.columns
WHERE table_name='aean'
);
here is a method to point
sh -> bash
run this command on terminal
sudo dpkg-reconfigure dash
After this you should see
ls -l /bin/sh
point to /bin/bash (and not to /bin/dash)
AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).
If you want your Web site to force IE 8 standards mode, then use this metatag along with a valid DOCTYPE:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />
Note the "EmulateIE8" value rather than the plain "IE8".
According to IE devs, this should, "Display Standards DOCTYPEs in IE8 Standards mode; Display Quirks DOCTYPEs in Quirks mode. Use this tag to override compatibility view on client machines and force Standards to IE8 Standards."
more info on this IE blog post: http://blogs.msdn.com/b/ie/archive/2008/08/27/introducing-compatibility-view.aspx
Here is a talk about the differences between web sockets and server sent events. Since Java EE 7 a WebSocket API is already part of the specification and it seems that server sent events will be released in the next version of the enterprise edition.
This is the configuration that I use, which works fine, it is based on XML + JaninoEventEvaluator (requires the Janino library to be added to Classpath)
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date | [%-5level] in [%file:%line] - %msg %n</pattern>
</encoder>
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="ch.qos.logback.classic.boolex.JaninoEventEvaluator">
<expression>
level <= INFO
</expression>
</evaluator>
<OnMismatch>DENY</OnMismatch>
<OnMatch>NEUTRAL</OnMatch>
</filter>
</appender>
<appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
<target>System.err</target>
<encoder>
<pattern>%date | [%-5level] in [%file:%line] - %msg %n</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>WARN</level>
</filter>
</appender>
<root level="DEBUG">
<appender-ref ref="STDOUT" />
<appender-ref ref="STDERR" />
</root>
</configuration>
you can use git bash on the working directory command is as follow
git status -b
it will tell you on which branch you are on there are many commands which are useful some of them are
-s
--short Give the output in the short-format.
-b --branch Show the branch and tracking info even in short-format.
--porcelain[=] Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across Git versions and regardless of user configuration. See below for details.
The version parameter is used to specify the format version. This is optional and defaults to the original version v1 format.
--long Give the output in the long-format. This is the default.
-v --verbose In addition to the names of files that have been changed, also show the textual changes that are staged to be committed (i.e., like the output of git diff --cached). If -v is specified twice, then also show the changes in the working tree that have not yet been staged (i.e., like the output of git diff).
To expand upon Pavel Minaev's original comment - The GUI for Visual Studio supports relative references with the assumption that your .sln is the root of the relative reference. So if you have a solution C:\myProj\myProj.sln
, any references you add in subfolders of C:\myProj\
are automatically added as relative references.
To add a relative reference in a separate directory, such as C:/myReferences/myDLL.dll
, do the following:
Edit the < HintPath > to be equal to
<HintPath>..\..\myReferences\myDLL.dll</HintPath>
This now references C:\myReferences\myDLL.dll
.
Hope this helps.
Actually, I found that if you put the the android:gravity="center" at the end of your xml line, the hint text shows up fine with the android:inputType="textVisiblePassword"
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
Just set element child to position: relative and than move it top: 100% (that's the 100% height of the parent) and stick to bottom of parent by transform: translateY(-100%) (that's -100% of the height of the child).
BenefitS
But still just workaround :(
.copyright{
position: relative;
top: 100%;
transform: translateY(-100%);
}
Don't forget prefixes for the older browser.
WebDriver driver=new FirefoxDriver();
driver.get("http://www.java-examples.com/java-string-examples");
Thread.sleep(3000);
//Switch to nested frame
driver.switchTo().frame("aswift_2").switchTo().frame("google_ads_frame3");
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
In my case the excel was frozen when using the formula of
B2=INDEX($A$2:$A$20, MATCH(0, COUNTIF($B$1:B1, $A$2:$A$20), 0))
because there was many rows (10000). So I did in another way which I show below.
I have copied my original list to a second column and then with the function of Excel "remove duplicates" I could find the list of unique values.
Copied from Microsoft Office Website:
Select all the rows, including the column headers, in the list
you want to filter.
Click the top left cell of the range, and then drag to the bottom right cell.
On the Data menu, point to Filter, and then click Advanced Filter. In the Advanced Filter dialog box, click Filter the list, in place. Select the Unique records only check box, and then click OK.
The filtered list is displayed and the duplicate rows are hidden.
On the Edit menu, click Office Clipboard.
The Clipboard task pane is displayed.
Make sure the filtered list is still selected, and then click Copy Copy button.
The filtered list is highlighted with bounding outlines and the selection appears as an > > item at the top of the Clipboard.
On the Data menu, point to Filter, and then click Show All.
The original list is re-displayed.
Press the DELETE key.
The original list is deleted.
In the Clipboard, click on the filtered list item.
The filtered list appears in the same location as the original list.
Source: Microsoft Office Website (link removed, cause dead)
None of the above answers worked for me but this does -- Use <P style='line-height: 8px;'>
to replace <p>
wherever needed (or put it in the style tag like <style>P {line-height: 8px;}</style>
to affect all <p>
tags). I realise Mauro says this, but if someone comes here for help, I expect they would want to see an example.
You could do this:
InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));
Note the UTF-8
encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8
if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:
The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.
// Function to get the client ip address
function get_ip()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
If you are using Linux, these settings are available using /usr/bin/jcontrol
(or your path setting to get the current Java tools). You can also edit the files in ~/.java/deployment/deployment.properties
to set "deployment.security.level=MEDIUM".
Surprisingly, this information is not readily available from the Oracle web site. I miss java.sun.com...
If you want to add a flag to every link, e.g. -fsanitize=address
then I would not recommend using CMAKE_*_LINKER_FLAGS
. Even with them all set it still doesn't use the flag when linking a framework on OSX, and maybe in other situations. Instead use link_libraries()
:
add_compile_options("-fsanitize=address")
link_libraries("-fsanitize=address")
This works for everything.
Use -d
(full list of file tests)
if (-d "cgi-bin") {
# directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
# cgi-bin exists but is not a directory
}
else {
# nothing called cgi-bin exists
}
As a note, -e
doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f
.
I wanted a solution for Gnu sort on Windows, but none of the above solutions worked for me on the command line.
Using Lloyd's clue, the following batch file (.bat) worked for me.
Type the tab character within the double quotes.
C:\>cat foo.bat
sort -k3 -t" " tabfile.txt
This was how I added a tracking branch so I can pull from it into my new branch:
git branch --set-upstream-to origin/Development new-branch
You just need to add a jquery selector after the url.
See: http://api.jquery.com/load/
Example straight from the API:
$('#result').load('ajax/test.html #container');
So what that does is it loads the #container element from the specified url.
Just use a MaterialButton and the app:backgroundTint and android:textColor attributes:
<MaterialButton
app:backgroundTint="@color/my_color"
android:textColor="@android:color/white"/>
I had a similar exception at Swift 4.2. I spent around half an hour trying to find a bug in my code, but the issue has gone after closing Xcode and removing derived data folder. Here is the shortcut:
rm -rf ~/Library/Developer/Xcode/DerivedData
After extensive googling I found a working solution, which consists of two steps.
The first step is to set system wide environment variable ASPNET_ENV to Production and Restart the Windows Server. After this, all web apps are getting the value 'Production' as EnvironmentName.
The second step (to enable value 'Staging' for staging web) was rather more difficult to get to work correctly, but here it is:
Now the Staging web should have the EnvironmentName set to 'Staging'.
Update: In Windows 7+ there is a command that can set environment variables from CMD prompt also for a specified user. This outputs help plus samples:
>setx /?
There is now a HDF5 based clone of pickle
called hickle
!
https://github.com/telegraphic/hickle
import hickle as hkl
data = { 'name' : 'test', 'data_arr' : [1, 2, 3, 4] }
# Dump data to file
hkl.dump( data, 'new_data_file.hkl' )
# Load data from file
data2 = hkl.load( 'new_data_file.hkl' )
print( data == data2 )
EDIT:
There also is the possibility to "pickle" directly into a compressed archive by doing:
import pickle, gzip, lzma, bz2
pickle.dump( data, gzip.open( 'data.pkl.gz', 'wb' ) )
pickle.dump( data, lzma.open( 'data.pkl.lzma', 'wb' ) )
pickle.dump( data, bz2.open( 'data.pkl.bz2', 'wb' ) )
Appendix
import numpy as np
import matplotlib.pyplot as plt
import pickle, os, time
import gzip, lzma, bz2, h5py
compressions = [ 'pickle', 'h5py', 'gzip', 'lzma', 'bz2' ]
labels = [ 'pickle', 'h5py', 'pickle+gzip', 'pickle+lzma', 'pickle+bz2' ]
size = 1000
data = {}
# Random data
data['random'] = np.random.random((size, size))
# Not that random data
data['semi-random'] = np.zeros((size, size))
for i in range(size):
for j in range(size):
data['semi-random'][i,j] = np.sum(data['random'][i,:]) + np.sum(data['random'][:,j])
# Not random data
data['not-random'] = np.arange( size*size, dtype=np.float64 ).reshape( (size, size) )
sizes = {}
for key in data:
sizes[key] = {}
for compression in compressions:
if compression == 'pickle':
time_start = time.time()
pickle.dump( data[key], open( 'data.pkl', 'wb' ) )
time_tot = time.time() - time_start
sizes[key]['pickle'] = ( os.path.getsize( 'data.pkl' ) * 10**(-6), time_tot )
os.remove( 'data.pkl' )
elif compression == 'h5py':
time_start = time.time()
with h5py.File( 'data.pkl.{}'.format(compression), 'w' ) as h5f:
h5f.create_dataset('data', data=data[key])
time_tot = time.time() - time_start
sizes[key][compression] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot)
os.remove( 'data.pkl.{}'.format(compression) )
else:
time_start = time.time()
pickle.dump( data[key], eval(compression).open( 'data.pkl.{}'.format(compression), 'wb' ) )
time_tot = time.time() - time_start
sizes[key][ labels[ compressions.index(compression) ] ] = ( os.path.getsize( 'data.pkl.{}'.format(compression) ) * 10**(-6), time_tot )
os.remove( 'data.pkl.{}'.format(compression) )
f, ax_size = plt.subplots()
ax_time = ax_size.twinx()
x_ticks = labels
x = np.arange( len(x_ticks) )
y_size = {}
y_time = {}
for key in data:
y_size[key] = [ sizes[key][ x_ticks[i] ][0] for i in x ]
y_time[key] = [ sizes[key][ x_ticks[i] ][1] for i in x ]
width = .2
viridis = plt.cm.viridis
p1 = ax_size.bar( x-width, y_size['random'] , width, color = viridis(0) )
p2 = ax_size.bar( x , y_size['semi-random'] , width, color = viridis(.45))
p3 = ax_size.bar( x+width, y_size['not-random'] , width, color = viridis(.9) )
p4 = ax_time.bar( x-width, y_time['random'] , .02, color = 'red')
ax_time.bar( x , y_time['semi-random'] , .02, color = 'red')
ax_time.bar( x+width, y_time['not-random'] , .02, color = 'red')
ax_size.legend( (p1, p2, p3, p4), ('random', 'semi-random', 'not-random', 'saving time'), loc='upper center',bbox_to_anchor=(.5, -.1), ncol=4 )
ax_size.set_xticks( x )
ax_size.set_xticklabels( x_ticks )
f.suptitle( 'Pickle Compression Comparison' )
ax_size.set_ylabel( 'Size [MB]' )
ax_time.set_ylabel( 'Time [s]' )
f.savefig( 'sizes.pdf', bbox_inches='tight' )
var bs []byte
value, _ := strconv.ParseInt(string(bs), 10, 64)
Using GhostScript from the command line, I've used the following in the past:
on Windows:
gswin32c -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf
on *nix:
gs -dNOPAUSE -q -g300x300 -sDEVICE=tiffg4 -dBATCH -sOutputFile=output_file_name.tif input_file_name.pdf
For a large number of files, a simple batch/shell script could be used to convert an arbitrary number of files...
I just found the simplest way to find the channel ID of any YouTube channel !!
Step 1: Play a video of that channel.
Step 2: Click the channel name under that video.
Step 3: Look at the browser address bar.
If you look up continue and break they accept a "Label". Experiment with that. Goto itself won't work.
public class BreakContinueWithLabel {
public static void main(String args[]) {
int[] numbers= new int[]{100,18,21,30};
//Outer loop checks if number is multiple of 2
OUTER: //outer label
for(int i = 0; i<numbers.length; i++){
if(i % 2 == 0){
System.out.println("Odd number: " + i +
", continue from OUTER label");
continue OUTER;
}
INNER:
for(int j = 0; j<numbers.length; j++){
System.out.println("Even number: " + i +
", break from INNER label");
break INNER;
}
}
}
}
Just to add to @ThijsW's answer, there is a significant speed advantage to the first method over the concatenation method:
big = 1e5;
tic;
x = rand(big,1);
toc
x = zeros(big,1);
tic;
for ii = 1:big
x(ii) = rand;
end
toc
x = [];
tic;
for ii = 1:big
x(end+1) = rand;
end;
toc
x = [];
tic;
for ii = 1:big
x = [x rand];
end;
toc
Elapsed time is 0.004611 seconds.
Elapsed time is 0.016448 seconds.
Elapsed time is 0.034107 seconds.
Elapsed time is 12.341434 seconds.
I got these times running in 2012b however when I ran the same code on the same computer in matlab 2010a I get
Elapsed time is 0.003044 seconds.
Elapsed time is 0.009947 seconds.
Elapsed time is 12.013875 seconds.
Elapsed time is 12.165593 seconds.
So I guess the speed advantage only applies to more recent versions of Matlab
One important issue with long polling is error handling. There are two types of errors:
The request might timeout in which case the client should reestablish the connection immediately. This is a normal event in long polling when no messages have arrived.
A network error or an execution error. This is an actual error which the client should gracefully accept and wait for the server to come back on-line.
The main issue is that if your error handler reestablishes the connection immediately also for a type 2 error, the clients would DOS the server.
Both answers with code sample miss this.
function longPoll() {
var shouldDelay = false;
$.ajax({
url: 'poll.php',
async: true, // by default, it's async, but...
dataType: 'json', // or the dataType you are working with
timeout: 10000, // IMPORTANT! this is a 10 seconds timeout
cache: false
}).done(function (data, textStatus, jqXHR) {
// do something with data...
}).fail(function (jqXHR, textStatus, errorThrown ) {
shouldDelay = textStatus !== "timeout";
}).always(function() {
// in case of network error. throttle otherwise we DOS ourselves. If it was a timeout, its normal operation. go again.
var delay = shouldDelay ? 10000: 0;
window.setTimeout(longPoll, delay);
});
}
longPoll(); //fire first handler
You can use list comprehension:
content = open("path/to/file.txt").readlines()
lookup = 'the dog barked'
lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]
print(lines)
I spent a whole day on this error
if you are working with n-tear architecture
or you tried to separate Models
generated by EDMX
form DataAccessLayer to DomainModelLayer
maybe you will get this error
webconfig (UILayer)
and appconfig (DataAccessLayer)
are the same Second which is Very important the connection string
connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provid.....
which is the problem
from where on earth I got Model
or whatever .csdl in my connection string where are they
here I our solution look at the picture
hope the help you
Place the following in your jQuery mouseover
event handler:
$(this).css('color', 'red');
To set both color and size at the same time:
$(this).css({ 'color': 'red', 'font-size': '150%' });
You can set any CSS attribute using the .css()
jQuery function.
You can use jQuery UI plugin, following are reference URLs
Set track to TRUE for Tooltip position relative to mouse pointer eg.
$('.tooltip').tooltip({ track: true });
_x000D_
String is immutable means that you cannot change the object itself, but you can change the reference to the object.
When you execute a = "ty"
, you are actually changing the reference of a
to a new object created by the String literal "ty"
.
Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:
Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"
While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:
String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"
You can't cast a mammal into a dog - it might be a cat.
You can't cast a food into a sandwich - it might be a cheeseburger.
You can't cast a car into a Ferrari - it might be a Honda, or more specifically, You can't cast a Ferrari 360 Modena to a Ferrari 360 Challange Stradale - there are differnt parts, even though they are both Ferrari 360s.
If you're using PostgreSQL you can use DISTINCT ON
to find the first row in a group.
SELECT customer.*, purchase.*
FROM customer
JOIN (
SELECT DISTINCT ON (customer_id) *
FROM purchase
ORDER BY customer_id, date DESC
) purchase ON purchase.customer_id = customer.id
Note that the DISTINCT ON
field(s) -- here customer_id
-- must match the left most field(s) in the ORDER BY
clause.
Caveat: This is a nonstandard clause.
Static method example
class StaticDemo
{
public static void copyArg(String str1, String str2)
{
str2 = str1;
System.out.println("First String arg is: "+str1);
System.out.println("Second String arg is: "+str2);
}
public static void main(String agrs[])
{
//StaticDemo.copyArg("XYZ", "ABC");
copyArg("XYZ", "ABC");
}
}
Output:
First String arg is: XYZ
Second String arg is: XYZ
As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.
Non-static method example
class Test
{
public void display()
{
System.out.println("I'm non-static method");
}
public static void main(String agrs[])
{
Test obj=new Test();
obj.display();
}
}
Output:
I'm non-static method
A non-static method is always be called by using the object of class as shown in the above example.
Key Points:
How to call static methods: direct or using class name:
StaticDemo.copyArg(s1, s2);
or
copyArg(s1, s2);
How to call a non-static method: using object of the class:
Test obj = new Test();
This error can occur for lots of reasons, and the last time, I solved it by modifying the Reference.svcmap
file, and changing how the WSDL file is referenced.
Throwing exception:
<MetadataSource Address="C:\Users\Me\Repo\Service.wsdl" Protocol="file" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="file:///C:/Users/Me/Repo/Service.wsdl" />
Working fine:
<MetadataSource Address="https://server.domain/path/Service.wsdl" Protocol="http" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="https://server.domain/path/Service.wsdl" />
This seems weird, but I have reproduced it. This was in a console application on .NET 4.5 and 4.7, as well as a .NET WebAPI site on 4.7.
After insuring that the string "strOutput" has a correct XML structure, you can do this:
Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");
Also make sure the div is currently appended to the DOM and visible.
guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:
before :
document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;
After :
document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;
Credits to Divya Akka .... :)
This is working for me
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
This works from me:
public void showKeyboard(final EditText ettext){
ettext.requestFocus();
ettext.postDelayed(new Runnable(){
@Override public void run(){
InputMethodManager keyboard=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(ettext,0);
}
}
,200);
}
To hide:
private void hideSoftKeyboard(EditText ettext){
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(ettext.getWindowToken(), 0);
}
Added webkit specific values missing from above
white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera */
white-space: pre-wrap; /* Chrome */
word-wrap: break-word; /* IE */
I actually tend to prefer PascalCase here - but out of habit, I'm guilty of UPPER_CASE...
I know this is late, but it does answer your original question.
/*Read the comments the same way that SQL runs the query
1) FROM
2) GROUP
3) SELECT
4) My final notes at the bottom
*/
SELECT
list.invoiceid
, cust.customernumber
, MAX(list.inv_amount) AS invoice_amount/* we select the max because it will be the same for each payment to that invoice (presumably invoice amounts do not vary based on payment) */
, MAX(list.inv_amount) - SUM(list.pay_amount) AS [amount_due]
FROM
Customers AS cust
INNER JOIN
Payments AS pay
ON
pay.customerid = cust.customerid
INNER JOIN ( /* generate a list of payment_ids, their amounts, and the totals of the invoices they billed to*/
SELECT
inpay.paymentid AS paymentid
, inv.invoiceid AS invoiceid
, inv.amount AS inv_amount
, pay.amount AS pay_amount
FROM
InvoicePayments AS inpay
INNER JOIN
Invoices AS inv
ON inv.invoiceid = inpay.invoiceid
INNER JOIN
Payments AS pay
ON pay.paymentid = inpay.paymentid
) AS list
ON
list.paymentid = pay.paymentid
/* so at this point my result set would look like:
-- All my customers (crossed by) every paymentid they are associated to (I'll call this A)
-- Every invoice payment and its association to: its own ammount, the total invoice ammount, its own paymentid (what I call list)
-- Filter out all records in A that do not have a paymentid matching in (list)
-- we filter the result because there may be payments that did not go towards invoices!
*/
GROUP BY
/* we want a record line for each customer and invoice ( or basically each invoice but i believe this makes more sense logically */
cust.customernumber
, list.invoiceid
/*
-- we can improve this query by only hitting the Payments table once by moving it inside of our list subquery,
-- but this is what made sense to me when I was planning.
-- Hopefully it makes it clearer how the thought process works to leave it in there
-- as several people have already pointed out, the data structure of the DB prevents us from looking at customers with invoices that have no payments towards them.
*/
The delete
operator allows you to remove a property from an object.
The following examples all do the same thing.
// Example 1
var key = "Cow";
delete thisIsObject[key];
// Example 2
delete thisIsObject["Cow"];
// Example 3
delete thisIsObject.Cow;
If you're interested, read Understanding Delete for an in-depth explanation.
You would simply use jQuery like so...
<script>
jQuery(function(){
jQuery('#modal').click();
});
</script>
Use the click function to auto-click the #modal button
// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number
// so it returns the correct amount of days
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29
Based on A.K's code, here is a Helper Function. JS Fiddle Here (http://jsfiddle.net/M5vsL/1/) ...
// Helper Method Defined Here.
(function (helper, $) {
// This is now a utility function to "Get the Document Hash"
helper.getDocumentHash = function (urlString) {
var hashValue = "";
if (urlString.indexOf('#') != -1) {
hashValue = urlString.substring(parseInt(urlString.indexOf('#')) + 1);
}
return hashValue;
};
})(this.helper = this.helper || {}, jQuery);
If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control
public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
{
get
{
if (_ctrlToValidate == null)
_ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
return _ctrlToValidate;
}
}
protected override bool ControlPropertiesValid()
{
if (this.ControlToValidate.Length == 0)
throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
if (this.CheckBoxToValidate == null)
throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
return true;
}
protected override bool EvaluateIsValid()
{
return CheckBoxToValidate.Checked;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Visible && this.Enabled)
{
System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
}
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
{
cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
}
}
}
private string GetClientSideScript()
{
return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
}
}
It's document.getElementById()
and not document.getElementByID()
. Check the casing for Id
.
Your problem here is that to_datetime
silently failed so the dtype remained as str/object
, if you set param errors='coerce'
then if the conversion fails for any particular string then those rows are set to NaT
.
df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
So you need to find out what is wrong with those specific row values.
See the docs
Example: Getting app_name string:
Resources.getSystem().getString( R.string.app_name )
I have seen the error trying to run VC++ debug executable on a machine which did not have Visual C++ installed. Building a release version and using that fixed it.
I have used :after
and it is working in all major browsers. please check the link. just need to careful for the z-index as after is having position absolute.
<div class="splitBg">
<div style="max-width:960px; margin:0 auto; padding:0 15px; box-sizing:border-box;">
<div style="float:left; width:50%; position:relative; z-index:10;">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
</div>
<div style="float:left; width:50%; position:relative; z-index:10;">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec,
</div>
<div style="clear:both;"></div>
</div>
</div>`
css
.splitBg{
background-color:#666;
position:relative;
overflow:hidden;
}
.splitBg:after{
width:50%;
position:absolute;
right:0;
top:0;
content:"";
display:block;
height:100%;
background-color:#06F;
z-index:1;
}
Or simply:
Date.now
From MDN documentation:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970
Available since ECMAScript 5.1
It's the same as was mentioned above (new Date().getTime()
), but more shortcutted version.
In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.
What did the trick was:
bfg -b 100M # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive
Then, you need to push force on your branch:
git push origin <your_branch_name> --force
Note: bfg is a tool that can be installed on Linux and macOS using brew:
brew install bfg
Well in fact TryGetValue is faster. How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.
Edit:
Ok, I understand your confusion so let me elaborate:
Case 1:
if (myDict.Contains(someKey))
someVal = myDict[someKey];
In this case there are 2 calls to FindEntry, one to check if the key exists and one to retrieve it
Case 2:
myDict.TryGetValue(somekey, out someVal)
In this case there is only one call to FindKey because the resulting index is kept for the actual retrieval in the same method.
You can also use partial
from functools
if you want to use a function that takes parameters but the function you are mocking does not. E.g. like this:
def mock_year(year):
return datetime.datetime(year, 11, 28, tzinfo=timezone.utc)
@patch('django.utils.timezone.now', side_effect=partial(mock_year, year=2020))
This will return a callable that doesn't accept parameters (like Django's timezone.now()), but my mock_year function does.
// Set font-size and font-femily the way you want
UIFont *objFont = [UIFont fontWithName:@"DroidSans" size:18.0f];
// Add font object to Dictionary
NSDictionary *dictAttributes = [NSDictionary dictionaryWithObject:objFont forKey:NSFontAttributeName];
// Set dictionary to the titleTextAttributes
[yourSegment setTitleTextAttributes:dictAttributes forState:UIControlStateNormal];
If you have any query, Contact me.
Generally a .lock
file is created and it decides lock/unlock state checking the existince of this file. I think if you delete this .lock
file only, then the problem will go away.
It should be possible like this (or use jQuery like $('meta[name=author]').attr("content");
):
<html>
<head>
<title>Meta Data</title>
<meta name="Author" content="Martin Webb">
<meta name="Author" content="A.N. Other">
<meta name="Description" content="A sample html file for extracting meta data">
<meta name="Keywords" content="JavaScript, DOM, W3C">
</head>
<body>
<script language="JavaScript"><!--
if (document.getElementsByName) {
var metaArray = document.getElementsByName('Author');
for (var i=0; i<metaArray.length; i++) {
document.write(metaArray[i].content + '<br>');
}
var metaArray = document.getElementsByName('Description');
for (var i=0; i<metaArray.length; i++) {
document.write(metaArray[i].content + '<br>');
}
var metaArray = document.getElementsByName('Keywords');
for (var i=0; i<metaArray.length; i++) {
document.write(metaArray[i].content + '<br>');
}
}
//--></script>
</body>
</html>
Lists and Maps are different data structures. Maps are used for when you want to associate a key with a value and Lists are an ordered collection.
Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.
ArrayList and LinkedList are an implementation of the List interface. LinkedList provides sequential access and is generally more efficient at inserting and deleting elements in the list, however, it is it less efficient at accessing elements in a list. ArrayList provides random access and is more efficient at accessing elements but is generally slower at inserting and deleting elements.
more_itertools.unzip()
is easy to read, and it also works with generators.
import more_itertools
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r)) # a list of lists
or equivalently
import more_itertools
l = more_itertools.chunked(range(1,10), 3)
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r)) # a list of lists
Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.
I could not compile QT5 with any of the (fairly outdated) toolchains from git://github.com/raspberrypi/tools.git. The configure script kept failing with an "could not determine architecture" error and with massive path problems for include directories. What worked for me was using the Linaro toolchain
in combination with
https://raw.githubusercontent.com/riscv/riscv-poky/master/scripts/sysroot-relativelinks.py
Failing to fix the symlinks of the sysroot leads to undefined symbol errors as described here: An error building Qt libraries for the raspberry pi This happened to me when I tried the fixQualifiedLibraryPaths script from tools.git. Everthing else is described in detail in http://wiki.qt.io/RaspberryPi2EGLFS . My configure settings were:
./configure -opengl es2 -device linux-rpi3-g++ -device-option CROSS_COMPILE=/usr/local/rasp/gcc-linaro-4.9-2016.02-x86_64_arm-linux-gnueabihf/bin/arm-linux-gnueabihf- -sysroot /usr/local/rasp/sysroot -opensource -confirm-license -optimized-qmake -reduce-exports -release -make libs -prefix /usr/local/qt5pi -hostprefix /usr/local/qt5pi
with /usr/local/rasp/sysroot being the path of my local Raspberry Pi 3 Raspbian (Jessie) system copy and /usr/local/qt5pi being the path of the cross compiled QT that also has to be copied to the device. Be aware that Jessie comes with GCC 4.9.2 when you choose your toolchain.
John Gruber (who wrote Markdown, which is made of regular expressions and is used right here on Stack Overflow) had a go at producing a regular expression that recognises URLs in text:
http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
If you just want to grab the URL (i.e. you’re not really trying to parse the HTML), this might be more lightweight than an HTML parser.
As others have pointed out, you simply delimit them with a space.
However, knowing how the selectors work is also useful.
Consider this piece of HTML...
<div class="a"></div>
<div class="b"></div>
<div class="a b"></div>
Using .a { ... }
as a selector will select the first and third. However, if you want to select one which has both a
and b
, you can use the selector .a.b { ... }
. Note that this won't work in IE6, it will simply select .b
(the last one).
The Response
API consumes a (immutable) Blob
from which the data can be retrieved in several ways. The OP only asked for ArrayBuffer
, and here's a demonstration of it.
var blob = GetABlobSomehow();
// NOTE: you will need to wrap this up in a async block first.
/* Use the await keyword to wait for the Promise to resolve */
await new Response(blob).arrayBuffer(); //=> <ArrayBuffer>
alternatively you could use this:
new Response(blob).arrayBuffer()
.then(/* <function> */);
Note: This API isn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)
I had the same question and was trying to get a Div to load a scroll script, using onload or load. The problem I found was that it would always work before the Div could open, not during or after, so it wouldn't really work.
Then I came up with this as a work around.
<body>
<span onmouseover="window.scrollTo(0, document.body.scrollHeight);"
onmouseout="window.scrollTo(0, document.body.scrollHeight);">
<div id="">
</div>
<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>
</span>
</body>
I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.
According to some developers, "Core Java" refers to package API java.util.*
, which is mostly used in coding.
The term "Core Java" is not defined by Sun, it's just a slang definition.
J2ME / J2EE still depend on J2SDK API's for compilation and execution.
Nobody would say java.util.*
is separated from J2SDK for usage.
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
SELECT CAST(CAST(@DateField As Date) As DateTime) + CAST(CAST(@TimeField As Time) As DateTime)
I had a similar problem, however in my case I could pull/push to the remote branch but git status
didn't show the local branch state w.r.t the remote ones.
Also, in my case git config --get remote.origin.fetch
didn't return anything
The problem is that there was a typo in the .git/config
file in the fetch line of the respective remote block. Probably something I added by mistake previously (sometimes I directly look at this file, or even edit it)
So, check if your remote entry in the .git/config
file is correct, e.g.:
[remote "origin"]
url = https://[server]/[user or organization]/[repo].git
fetch = +refs/heads/*:refs/remotes/origin/*
Something I stumbled upon today for a DLL I knew was working fine with my VS2013 project, but not with VS2015:
Go to: Project -> XXXX Properties -> Build -> Uncheck "Prefer 32-bit"
This answer is way overdue and probably won't do any good, but if you. But I hope this will help somebody someday.
You can use this command and the video duration is still unaltered.
ffmpeg -i input.mp4 -r 24 output.mp4
A nice and easy way to do it using GregorianCalendar
Import these into the project:
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.Scanner;
And then:
Scanner s = new Scanner(System.in);
System.out.println("Seconds: ");
int secs = s.nextInt();
GregorianCalendar cal = new GregorianCalendar(0,0,0,0,0,secs);
Date dNow = cal.getTime();
SimpleDateFormat ft = new SimpleDateFormat("HH 'hours' mm 'minutes' ss 'seconds'");
System.out.println("Your time: " + ft.format(dNow));
A common use case appears to be to standardize line endings for all files committed to a Git repository:
git ls-files | xargs dos2unix
Keep in mind that certain files (e.g. *.sln
, *.bat
) etc are only used on Windows operating systems and should keep the CRLF
ending:
git ls-files '*.sln' '*.bat' | xargs unix2dos
If necessary, use .gitattributes
Inspired by Expire cache on require.js data-main we updated our deploy script with the following ant task:
<target name="deployWebsite">
<untar src="${temp.dir}/website.tar.gz" dest="${website.dir}" compression="gzip" />
<!-- fetch latest buildNumber from build agent -->
<replace file="${website.dir}/js/main.js" token="@Revision@" value="${buildNumber}" />
</target>
Where the beginning of main.js looks like:
require.config({
baseUrl: '/js',
urlArgs: 'bust=@Revision@',
...
});
The terminal-only (and simplest) solution, in case all those fancy UI's fail to install or to run:
ignore cProfile
completely and replace it with pyinstrument
, that will collect and display the tree of calls right after execution.
Install:
$ pip install pyinstrument
Profile and display result:
$ python -m pyinstrument ./prog.py
Works with python2 and 3.
[EDIT] The documentation of the API, for profiling only a part of the code, can be found here.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists this block.
sudo -u postgres psql template1
Then sudo nano /etc/postgresql/11/main/pg_hba.conf file
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
None of the solutions worked for me, since I am not working on Maven projects. There is a simpler solution. Go to:
File->Project Structure->Modules.
Instead of adding module, simply click the third option (copy). Browse your local directory and select the project you would like to add. Module name will resolve automatically. That's it.
Update: When you want to reopen to project with multiple sub-projects, in order to avoid re-doing steps as described above, just go to File->Open Recent->'Your Big Project'.
you can strip
the '/'
:
>>> os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/'.strip('/'))
'/home/build/test/sandboxes/04122019/new_sandbox'
It depends on what is in test.py
. The following is an appropriate structure:
# suppose this is your 'test.py' file
def main():
"""This function runs the core of your program"""
print("running main")
if __name__ == "__main__":
# if you call this script from the command line (the shell) it will
# run the 'main' function
main()
If you keep this structure, you can run it like this in the command line (assume that $
is your command-line prompt):
$ python test.py
$ # it will print "running main"
If you want to run it from the Python shell, then you simply do the following:
>>> import test
>>> test.main() # this calls the main part of your program
There is no necessity to use the subprocess
module if you are already using Python. Instead, try to structure your Python files in such a way that they can be run both from the command line and the Python interpreter.
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
I was having the same issue. My problem was that the computer that generated the initial certificate request had crashed before the extended ssl validation process was completed. I needed to generate a new private key and then import the updated certificate from the certificate provider. If the private key doesn't exist on your computer then you can't export the certificate as pfx. They option is greyed out.
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
If you are getting this after replacing your database files using the Device File Explorer, sometimes this happens due to permissions and SELinux security contexts. The Device File Explorer (as of AS3.6.3) will upload them with root permissions/rwxrwxrwx set for all (777). Look around in your app folders for the user id used for your app. Execute the following commands in terminal:
adb devices
emulator-5554
adb root
adb -s emulator-5554 shell
cd /data/data/com.yourorg.yourapp
ls -l
You'll get a listing like:
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 cache
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 code_cache
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 databases
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 shared_prefs
u0_a85 (or whatever it might be) will be the app owner and group id. Delete your databases on the device, drop in your replacement database files using Device File Explorer, and in terminal, execute the following (keeping in mind the owner id):
cd databases
chown u0_a85 *.db; chgrp u0_a85 *.db; chmod 600 *.db; restorecon *.db
This changes the database files to their appropriate owner/group id, RW permissions, and resets the SELinux security contexts for those files. Although I have had success replacing database files NOT having to do this, this problem seems to happen randomly enough that doing this works.
If you want to print more than a single result, just select rows into a temporary table, then select from that temp table into a buffer, then print the buffer:
drop table if exists #temp
-- we just want to see our rows, not how many were inserted
set nocount on
select * into #temp from MyTable
-- note: SSMS will only show 8000 chars
declare @buffer varchar(MAX) = ''
select @buffer = @buffer + Col1 + ' ' + Col2 + CHAR(10) from #temp
print @buffer
You could do:
return_it(){
eval ${FUNCNAME[1]}_r_val="\$1"
}
and then use it in your functions like this:
fun1(){
return_it 34
}
fun2(){
fun1; echo $fun1_r_val
}
If you must not use a loop (why?), you could use array_walk
,
function printer($v, $k) {
echo "$k is at $v\n";
}
array_walk($page, "printer");
You need to encode the URI to replace illegal characters with legal encoded characters. If you first make a URL (so you don't have to do the parsing yourself) and then make a URI using the five-argument constructor, then the constructor will do the encoding for you.
import java.net.*;
public class Test {
public static void main(String[] args) {
String myURL = "http://finance.yahoo.com/q/h?s=^IXIC";
try {
URL url = new URL(myURL);
String nullFragment = null;
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
System.out.println("URI " + uri.toString() + " is OK");
} catch (MalformedURLException e) {
System.out.println("URL " + myURL + " is a malformed URL");
} catch (URISyntaxException e) {
System.out.println("URI " + myURL + " is a malformed URL");
}
}
}
try this:
var result = from r in myDataTable.AsEnumerable()
where r.Field<string>("Name") != "n/a" &&
r.Field<string>("Name") != "" select r;
DataTable dtResult = result.CopyToDataTable();
you can use the google chart api and generate any color with rgb code on the fly:
example: marker with #ddd color:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ddd
include as stated above with
var marker = new google.maps.Marker({
position: marker,
title: 'Hello World',
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|ddd'
});
Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal
described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.
When you:
HandlerMethodArgumentResolver
or WebArgumentResolver
can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal
and AuthenticationPrincipalArgumentResolver
(because it is based on a HandlerMethodArgumentResolver
)then keep on reading — else just use @AuthenticationPrincipal
and thank to Rob Winch (Author of @AuthenticationPrincipal
) and Lukas Schmelzeisen (for his answer).
(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal
annotation solution base on Spring Security 3.2.)
Then you can use in your controller
public ModelAndView someRequestHandler(Principal principal) {
User activeUser = (User) ((Authentication) principal).getPrincipal();
...
}
That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.
So what you may really want is to have a controller like this:
public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
...
}
Therefore you only need to implement a WebArgumentResolver
. It has a method
Object resolveArgument(MethodParameter methodParameter,
NativeWebRequest webRequest)
throws Exception
That gets the web request (second parameter) and must return the User
if its feels responsible for the method argument (the first parameter).
Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver
. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))
public class CurrentUserWebArgumentResolver implements WebArgumentResolver{
Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
Principal principal = webRequest.getUserPrincipal();
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}
In the configuration you only need to add this:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
id="applicationConversionService">
<property name="customArgumentResolver">
<bean class="CurrentUserWebArgumentResolver"/>
</property>
</bean>
@See: Learn to customize Spring MVC @Controller method arguments
It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay
HandlerMethodArgumentResolver
for Spring 3.1+public class CurrentUserHandlerMethodArgumentResolver
implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return
methodParameter.getParameterAnnotation(ActiveUser.class) != null
&& methodParameter.getParameterType().equals(User.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
if (this.supportsParameter(methodParameter)) {
Principal principal = webRequest.getUserPrincipal();
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
In the configuration, you need to add this
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="CurrentUserHandlerMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface
Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal
(org.springframework.security.web.bind.annotation.AuthenticationPrincipal
) . This is nicely described in Lukas Schmelzeisen`s answer
It is just writing
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
To get this working you need to register the AuthenticationPrincipalArgumentResolver
(org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver
) : either by "activating" @EnableWebMvcSecurity
or by registering this bean within mvc:argument-resolvers
- the same way I described it with may Spring 3.1 solution above.
@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal
It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal
and AuthenticationPrincipalArgumentResolver
was "moved" to an other package:
org.springframework.security.core.annotation.AuthenticationPrincipal
org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver
(But the old classes in its old packges still exists, so do not mix them!)
It is just writing
import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
To get this working you need to register the (org.springframework.security.web.method.annotation.
) AuthenticationPrincipalArgumentResolver
: either by "activating" @EnableWebMvcSecurity
or by registering this bean within mvc:argument-resolvers
- the same way I described it with may Spring 3.1 solution above.
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal
I was also following the instructions on http://developer.android.com/training/basics/actionbar/setting-up.html
and even though I did everything in the tutorial, as soon as "extends Action" is changed to "extends ActionBarActivity" all sorts of errors appear in Eclipse, including the "ActionBarActivitycannot be resolved to a type"
None of the above solutions worked for me, but what did work is adding this line to the top:
import android.support.v7.app.ActionBarActivity;
You can do it in a single query:
Select t.Id, t.title, z.dupCount
From yourtable T
Join
(select title, Count (*) dupCount
from yourtable
group By title
Having Count(*) > 1) z
On z.title = t.Title
order By dupCount Desc
If you do not want to install sqlplus
on your server/machine then the following command-line tool can be your friend. It is a simple Java application, only Java 8 that you need in order to you can execute this tool.
The tool can be used to run any SQL from the Linux bash or Windows command line.
Example:
java -jar sql-runner-0.2.0-with-dependencies.jar \
-j jdbc:oracle:thin:@//oracle-db:1521/ORCLPDB1.localdomain \
-U "SYS as SYSDBA" \
-P Oradoc_db1 \
"select 1 from dual"
Documentation is here.
You can download the binary file from here.
I missed to add
@Controller("userBo") into UserBoImpl class.
The solution for this is adding this controller into Impl class.
In the device manager you can select View > Show hidden devices
Kill all processes having snippet
in startup path. You can kill all apps started from some directory by for putting /directory/ as a snippet. This is quite usefull when you start several components for the same application from the same app directory.
ps ax | grep <snippet> | grep -v grep | awk '{print $1}' | xargs kill
* I would preffer pgrep if available
it works with postgresql
UPDATE application
SET omts_received_date = (
SELECT
date_created
FROM
application_history
WHERE
application.id = application_history.application_id
AND application_history.application_status_id = 8
);
Have you given the permission in the manifest file
<uses-permission android:name="android.permission.CALL_PHONE"></uses-permission>
and inside your activity
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:123456789"));
startActivity(callIntent);
Let me know if you find any issue.
You can use a TextBox
and set multiline
to true
and canEdit
to false
.
The creators of java decided that the problems of multiple inheritance outweigh the benefits, so they did not include multiple inheritance. You can read about one of the largest issues of multiple inheritance (the double diamond problem) here.
The two most similar concepts are interface implementation and including objects of other classes as members of the current class. Using default methods in interfaces is almost exactly the same as multiple inheritance, however it is considered bad practice to use an interface with only default methods.
The question specifically states the performance needs to be improved for ad-hoc queries, and that indexes can't be added. So taking that at face value, what can be done to improve performance on any table?
Since we're considering ad-hoc queries, the WHERE clause and the ORDER BY clause can contain any combination of columns. This means that almost regardless of what indexes are placed on the table there will be some queries that require a table scan, as seen above in query plan of a poorly performing query.
Taking this into account, let's assume there are no indexes at all on the table apart from a clustered index on the primary key. Now let's consider what options we have to maximize performance.
Defragment the table
As long as we have a clustered index then we can defragment the table using DBCC INDEXDEFRAG (deprecated) or preferably ALTER INDEX. This will minimize the number of disk reads required to scan the table and will improve speed.
Use the fastest disks possible. You don't say what disks you're using but if you can use SSDs.
Optimize tempdb. Put tempdb on the fastest disks possible, again SSDs. See this SO Article and this RedGate article.
As stated in other answers, using a more selective query will return less data, and should be therefore be faster.
Now let's consider what we can do if we are allowed to add indexes.
If we weren't talking about ad-hoc queries, then we would add indexes specifically for the limited set of queries being run against the table. Since we are discussing ad-hoc queries, what can be done to improve speed most of the time?
Edit
I've run some tests on a 'large' table of 22 million rows. My table only has six columns but does contain 4GB of data. My machine is a respectable desktop with 8Gb RAM and a quad core CPU and has a single Agility 3 SSD.
I removed all indexes apart from the primary key on the Id column.
A similar query to the problem one given in the question takes 5 seconds if SQL server is restarted first and 3 seconds subsequently. The database tuning advisor obviously recommends adding an index to improve this query, with an estimated improvement of > 99%. Adding an index results in a query time of effectively zero.
What's also interesting is that my query plan is identical to yours (with the clustered index scan), but the index scan accounts for 9% of the query cost and the sort the remaining 91%. I can only assume your table contains an enormous amount of data and/or your disks are very slow or located over a very slow network connection.
If you want to use jQuery, the .load() function is the correct function you are after;
But you are missing the #
from the div1 id selector in the example 2)
This should work:
$("#div1").load("file2.html");
This answer is specific to a java.lang.NoClassDefFoundError happening in a service:
My team recently saw this error after upgrading an rpm that supplied a service. The rpm and the software inside of it had been built with Maven, so it seemed that we had a compile time dependency that had just not gotten included in the rpm.
However, when investigating, the class that was not found was in the same module as several of the classes in the stack trace. Furthermore, this was not a module that had only been recently added to the build. These facts indicated it might not be a Maven dependency issue.
The eventual solution: Restart the service!
It appears that the rpm upgrade invalidated the service's file handle on the underlying jar file. The service then saw a class that had not been loaded into memory, searched for it among its list of jar file handles, and failed to find it because the file handle that it could load the class from had been invalidated. Restarting the service forced it to reload all of its file handles, which then allowed it to load that class that had not been found in memory right after the rpm upgrade.
Hope that specific case helps someone.
You can try this snippet
$("#your-id")[0].selectedIndex = -1
It worked for me.
You can change the linter for Python extension for Visual Studio Code.
In VS open the Command Palette Ctrl+Shift+P and type in one of the following commands:
Python: Select Linter
when you select a linter it will be installed. I tried flake8 and it seems issue resolved for me.
I had some inter-dependency with the tests in order to build the package.
The following command manage to override the need for the test artifact in order to complete the goal:
mvn -DskipTests=true package
You can also try typecasting it with string.
package main
import "fmt"
func main() {
fmt.Println(string("Hello"[1]))
}
I think this is a solved problem (see above), but there's an interesting side case to keep in mind because it might get asked:
If there are exactly 4,294,967,295 (2^32 - 1) 32-bit integers with no repeats, and therefore only one is missing, there is a simple solution.
Start a running total at zero, and for each integer in the file, add that integer with 32-bit overflow (effectively, runningTotal = (runningTotal + nextInteger) % 4294967296). Once complete, add 4294967296/2 to the running total, again with 32-bit overflow. Subtract this from 4294967296, and the result is the missing integer.
The "only one missing integer" problem is solvable with only one run, and only 64 bits of RAM dedicated to the data (32 for the running total, 32 to read in the next integer).
Corollary: The more general specification is extremely simple to match if we aren't concerned with how many bits the integer result must have. We just generate a big enough integer that it cannot be contained in the file we're given. Again, this takes up absolutely minimal RAM. See the pseudocode.
# Grab the file size
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
# Print a '2' for every bit of the file.
for (c=0; c<sz; c++) {
for (b=0; b<4; b++) {
print "2";
}
}
Just call fig.tight_layout()
as you normally would. (pyplot
is just a convenience wrapper. In most cases, you only use it to quickly generate figure and axes objects and then call their methods directly.)
There shouldn't be a difference between the QtAgg
backend and the default backend (or if there is, it's a bug).
E.g.
import matplotlib.pyplot as plt
#-- In your case, you'd do something more like:
# from matplotlib.figure import Figure
# fig = Figure()
#-- ...but we want to use it interactive for a quick example, so
#-- we'll do it this way
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
plt.show()
import matplotlib.pyplot as plt
fig, axes = plt.subplots(nrows=4, ncols=4)
for i, ax in enumerate(axes.flat, start=1):
ax.set_title('Test Axes {}'.format(i))
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
fig.tight_layout()
plt.show()
I've contemplated this a few times in the past so thought I'd jot down the different ideas I've had / used. Something might be of use, but none are "perfect" Symfony2 solutions.
Constructor In the Entity you can do $this->setBar('default value'); but this is called every time you load the entity (db or not) and is a bit messy. It does however work for every field type as you can create dates or whatever else you need.
If statements within get's I wouldn't, but you could.
return ( ! $this->hasFoo() ) ? 'default' : $this->foo;
Factory / instance. Call a static function / secondary class which provides you a default Entity pre-populated with data. E.g.
function getFactory() {
$obj = new static();
$obj->setBar('foo');
$obj->setFoo('bar');
return $obj;
}
Not really ideal given you'll have to maintain this function if you add extra fields, but it does mean you're separating the data setters / default and that which is generated from the db. Similarly you can have multiple getFactories should you want different defaulted data.
Extended / Reflection entities Create a extending Entity (e.g. FooCreate extends Foo) which gives you the defaulted data at create time (through the constructor). Similar to the Factory / instance idea just a different approach - I prefer static methods personally.
Set Data before build form In the constructors / service, you know if you have a new entity or if it was populated from the db. It's plausible therefore to call set data on the different fields when you grab a new entity. E.g.
if( ! $entity->isFromDB() ) {
$entity->setBar('default');
$entity->setDate( date('Y-m-d');
...
}
$form = $this->createForm(...)
Form Events When you create the form you set default data when creating the fields. You override this use PreSetData event listener. The problem with this is that you're duplicating the form workload / duplicating code and making it harder to maintain / understand.
Extended forms Similar to Form events, but you call the different type depending on if it's a db / new entity. By this I mean you have FooType which defines your edit form, BarType extends FooType this and sets all the data to the fields. In your controller you then simply choose which form type to instigate. This sucks if you have a custom theme though and like events, creates too much maintenance for my liking.
Twig You can create your own theme and default the data using the value option too when you do it on a per-field basis. There is nothing stopping you wrapping this into a form theme either should you wish to keep your templates clean and the form reusable. e.g.
form_widget(form.foo, {attr: { value : default } });
JS It'd be trivial to populate the form with a JS function if the fields are empty. You could do something with placeholders for example. This is a bad, bad idea though.
Forms as a service For one of the big form based projects I did, I created a service which generated all the forms, did all the processing etc. This was because the forms were to be used across multiple controllers in multiple environments and whilst the forms were generated / handled in the same way, they were displayed / interacted with differently (e.g. error handling, redirections etc). The beauty of this approach was that you can default data, do everything you need, handle errors generically etc and it's all encapsulated in one place.
Conclusion As I see it, you'll run into the same issue time and time again - where is the defaulted data to live?
To that end, I've approached the problem differently each time. For example, a signup form "newsletter" option is easily (and logically) set in the constructor just before creating the form. When I was building forms collections which were linked together (e.g. which radio buttons in different form types linked together) then I've used Event Listeners. When I've built a more complicated entity (e.g. one which required children or lots of defaulted data) I've used a function (e.g. 'getFactory') to create it element as I need it.
I don't think there is one "right" approach as every time I've had this requirement it's been slightly different.
Good luck! I hope I've given you some food for thought at any rate and didn't ramble too much ;)
The best way to do it:
package main_package;
import java.util.ArrayList;
public class Stackkkk {
public static void main(String[] args) {
ArrayList<Object> list = new ArrayList<Object>();
add(list, "1", "2", "3", "4", "5", "6");
System.out.println("I added " + list.size() + " element in one line");
}
public static void add(ArrayList<Object> list,Object...objects){
for(Object object:objects)
list.add(object);
}
}
Just create a function that can have as many elements as you want and call it to add them in one line.
This are to way to bind add too numbers
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script>_x000D_
_x000D_
var app = angular.module("myApp", []);_x000D_
_x000D_
app.controller("myCtrl", function($scope) {_x000D_
$scope.total = function() { _x000D_
return parseInt($scope.num1) + parseInt($scope.num2) _x000D_
}_x000D_
})_x000D_
</script>_x000D_
<body ng-app='myApp' ng-controller='myCtrl'>_x000D_
_x000D_
<input type="number" ng-model="num1">_x000D_
<input type="number" ng-model="num2">_x000D_
Total:{{num1+num2}}_x000D_
_x000D_
Total: {{total() }}_x000D_
_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I think, the easiest way is to read readme file inside your Eclipse directory at path eclipse/readme/eclipse_readme
.
At the very top of this file it clearly tells the version number:
For My Eclipse Juno; it says version as Release 4.2.0
For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.
I have this in my Model.
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
public DateTime issueDate { get; set; }
and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.
To make it work the way I want I put this in the View...
@Html.EditorFor(m => m.issueDate, new{ @class="inp", @style="width:200px", @MaxLength = "200"})
and this in my ready function...
$('#issueDate').prop('readOnly', true);
I hope this would be helpful for someone out there. Sorry for my English
No.
But if you're looking to treat your person1
object as if it were a Person
, you can call methods on Person
's prototype on person1
with call
:
Person.prototype.getFullNamePublic = function(){
return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);
Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName
method.
I suppose you have enabled On-device Developer Options in your smartphone? If not you can take a look at the steps provided by Android, http://developer.android.com/tools/device.html#developer-device-options
You should actually be able to disable foreign key constraints the same way you temporarily disable other constraints:
Alter table MyTable nocheck constraint FK_ForeignKeyConstraintName
Just make sure you're disabling the constraint on the first table listed in the constraint name. For example, if my foreign key constraint was FK_LocationsEmployeesLocationIdEmployeeId, I would want to use the following:
Alter table Locations nocheck constraint FK_LocationsEmployeesLocationIdEmployeeId
even though violating this constraint will produce an error that doesn't necessarily state that table as the source of the conflict.
If by "checked out" you mean people who have cloned your project, then no it is not possible. You don't even need to be a GitHub user to clone a repository, so it would be infeasible to track this.
I think excessive uses of global variables with static keyword will also leads to memory leakage at some point of instance in the applica
>>> text = 'lipsum'
>>> text[3:]
'sum'
See the official documentation on strings for more information and this SO answer for a concise summary of the notation.
M refers to the first non-ambiguous character in "decimal". If you don't add it the number will be treated as a double.
D is double.
The short answer is: don't. (...) You really can't. And that's a good thing
I'd like to set the record straight regarding this:
NodeJS does support Synchronous Requests. It wasn't designed to support them out of the box, but there are a few workarounds if you are keen enough, here is an example:
var request = require('sync-request'),
res1, res2, ucomp, vcomp;
try {
res1 = request('GET', base + u_ext);
res2 = request('GET', base + v_ext);
ucomp = res1.split('\n')[1].split(', ')[1];
vcomp = res2.split('\n')[1].split(', ')[1];
doSomething(ucomp, vcomp);
} catch (e) {}
When you pop the hood open on the 'sync-request' library you can see that this runs a synchronous child process in the background. And as is explained in the sync-request README it should be used very judiciously. This approach locks the main thread, and that is bad for performance.
However, in some cases there is little or no advantage to be gained by writing an asynchronous solution (compared to the certain harm you are doing by writing code that is harder to read).
This is the default assumption held by many of the HTTP request libraries in other languages (Python, Java, C# etc), and that philosophy can also be carried to JavaScript. A language is a tool for solving problems after all, and sometimes you may not want to use callbacks if the benefits outweigh the disadvantages.
For JavaScript purists this may rankle of heresy, but I'm a pragmatist so I can clearly see that the simplicity of using synchronous requests helps if you find yourself in some of the following scenarios:
Test Automation (tests are usually synchronous by nature).
Quick API mash-ups (ie hackathon, proof of concept works etc).
Simple examples to help beginners (before and after).
Be warned that the code above should not be used for production. If you are going to run a proper API then use callbacks, use promises, use async/await, or whatever, but avoid synchronous code unless you want to incur a significant cost for wasted CPU time on your server.
I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.
For me it was that wrong Bits per second value was set.
Recently I was also having this issue, then I contacted Google Support and they gave me this link to provide required info, I posted and within 24 hours my problem was fixed.
Link: https://support.google.com/payments/contact/alt_account_verification
X <- c(1:3)*0
Maybe this is not the most efficient way to initialize a vector to zero, but this requires to remember only the c()
function, which is very frequently cited in tutorials as a usual way to declare a vector.
As as side-note: To someone learning her way into R from other languages, the multitude of functions to do same thing in R may be mindblowing, just as demonstrated by the previous answers here.
I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>
's and <ol>
's and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
I've figured out how to work around this issue without mixing parent and sub scope data.
Set a ng-if
on the the ng-include
element and set it to a scope variable.
For example :
<div ng-include="{{ template }}" ng-if="show"/>
In your controller, when you have set all the data you need in your sub scope, then set show to true
. The ng-include
will copy at this moment the data set in your scope and set it in your sub scope.
The rule of thumb is to reduce scope data deeper the scope are, else you have this situation.
Max
I've found the same thing, but only on emulators that have the Use Host GPU setting ticked. Try turning that off, you'll no longer see those warnings (and the emulator will run horribly, horribly slowly..)
In my experience those warnings are harmless. Notice that the "error" is EGL_SUCCESS, which would seem to indicate no error at all!
Since you have access to the .NET library, you could access the OSVersion
property of the System.Environment
class to get this information. For the version number, there is the Version
property.
For example,
PS C:\> [System.Environment]::OSVersion.Version
Major Minor Build Revision
----- ----- ----- --------
6 1 7601 65536
Details of Windows versions can be found here.
When this was asked there wasn't a way to do it natively, however this will be added on the next sync according to this pull request. Here is the last comment on the pull request - "Landed internally, will be out on the next sync"
When it is added you will be able to do something like this
<TextInput secureTextEntry={true} style={styles.default} value="abc" />
The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
Which I got from https://stackoverflow.com/a/8412989/1232175.
Anyone wants to use command line to sync projects with gradle files, please note:
Since Gradle 5.0,
The
--recompile-scripts
command-line option has been removed.
Do you want a tool for doing it? There is a website at http://www.canyouseeme.org/. Otherwise, you need some other server to call you back to see if a port is open...
You can use array_filter()
which works great for all situations:
$ray_state = array_filter($myarray);
if (empty($ray_state)) {
echo 'array is empty';
} else {
echo 'array is not empty';
}
Everyone tries Application.Wait
, but that's not really reliable. If you ask it to wait for less than a second, you'll get anything between 0 and 1, but closer to 10 seconds. Here's a demonstration using a wait of 0.5 seconds:
Sub TestWait()
Dim i As Long
For i = 1 To 5
Dim t As Double
t = Timer
Application.Wait Now + TimeValue("0:00:00") / 2
Debug.Print Timer - t
Next
End Sub
Here's the output, an average of 0.0015625 seconds:
0
0
0
0.0078125
0
Admittedly, Timer may not be the ideal way to measure these events, but you get the idea.
The Timer approach is better:
Sub TestTimer()
Dim i As Long
For i = 1 To 5
Dim t As Double
t = Timer
Do Until Timer - t >= 0.5
DoEvents
Loop
Debug.Print Timer - t
Next
End Sub
And the results average is very close to 0.5 seconds:
0.5
0.5
0.5
0.5
0.5
Here is how this particular deadlock problem actually occurred and how it was actually resolved. This is a fairly active database with 130K transactions occurring daily. The indexes in the tables in this database were originally clustered. The client requested us to make the indexes nonclustered. As soon as we did, the deadlocking began. When we reestablished the indexes as clustered, the deadlocking stopped.
It’s just HTML with Server Side Includes.
In my case, load time is 5 times faster when this is disabled in php.ini :
;zend_extension = "\xampp\php\ext\php_xdebug-2.1.0-5.3-vc6.dll"
You can try deleting the .git
file in the directory and doing everything again will fix your problem!
In last versions, it is easier. Just put a ml-auto
class in the ul
like so:
<ul class="nav navbar-nav ml-auto">
ORDER BY a date type does not depend on the date format, the date format is only for showing, in the database, they are same data.
Just ask it for the objectForKey:@"b"
. If it returns nil
, no object is set at that key.
if ([xyz objectForKey:@"b"]) {
NSLog(@"There's an object set for key @\"b\"!");
} else {
NSLog(@"No object set for key @\"b\"");
}
Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];
. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).
In theory, for long running server-type application, a JIT-compiled language can become much faster than a natively compiled counterpart. Since the JIT compiled language is generally first compiled to a fairly low-level intermediate language, you can do a lot of the high-level optimizations right at compile time anyway. The big advantage comes in that the JIT can continue to recompile sections of code on the fly as it gets more and more data on how the application is being used. It can arrange the most common code-paths to allow branch prediction to succeed as often as possible. It can re-arrange separate code blocks that are often called together to keep them both in the cache. It can spend more effort optimizing inner loops.
I doubt that this is done by .NET or any of the JREs, but it was being researched back when I was in university, so it's not unreasonable to think that these sort of things may find their way into the real world at some point soon.
Specifying a flex attribute to the container worked for me:
.container {
flex: 0 0 auto;
}
This ensures the height is set and doesn't grow either.