Use fabs() instead of abs(), it's the same but for floats instead of integers.
Use file this code
function move_file($path,$to){
if(copy($path, $to)){
unlink($path);
return true;
} else {
return false;
}
}
This works for me:
for each series, use a random rgb colour generator
c = color[np.random.random_sample(), np.random.random_sample(), np.random.random_sample()]
The semicolon was throwing me off: I had JAVA_HOME
set to "C:\jdk1.6.0_26;" instead of "C:\jdk1.6.0_26". I removed the trailing semicolon after following Jon Skeet's suggestion to examine the ant.bat
file. This is part of that file:
if "%JAVA_HOME%" == "" goto noJavaHome
if not exist "%JAVA_HOME%\bin\java.exe" goto noJavaHome
So the semi-colon wasn't being trimmed off the end, causing this to fail to find the file, therefore defaulting to "C:\Java\jre6" or something like that.
The confusing part is that the HowtoBuild page states to use the semi-colon, but that seems to break it.
Because the static version of the .Equal
method was not mentioned so far, I would like to add this here to summarize and to compare the 3 variations.
MyString.Equals("Somestring")) //Method 1
MyString == "Somestring" //Method 2
String.Equals("Somestring", MyString); //Method 3 (static String.Equals method) - better
where MyString
is a variable that comes from somewhere else in the code.
Background info and to summerize:
In Java using ==
to compare strings should not be used. I mention this in case you need to use both languages and also
to let you know that using ==
can also be replaced with something better in C#.
In C# there's no practical difference for comparing strings using Method 1 or Method 2 as long as both are of type string. However, if one is null, one is of another type (like an integer), or one represents an object that has a different reference, then, as the initial question shows, you may experience that comparing the content for equality may not return what you expect.
Suggested solution:
Because using ==
is not exactly the same as using .Equals
when comparing things, you can use the static String.Equals method instead. This way, if the two sides are not the same type you will still compare the content and if one is null, you will avoid the exception.
bool areEqual = String.Equals("Somestring", MyString);
It is a little more to write, but in my opinion, safer to use.
Here is some info copied from Microsoft:
public static bool Equals (string a, string b);
Parameters
a
String
The first string to compare, or null
.
b
String
The second string to compare, or null
.
Returns Boolean
true
if the value of a
is the same as the value of b
; otherwise, false
. If both a
and b
are null
, the method returns true
.
If you use Java and spring MVC you just need to add the following annotation to your method returning your page :
@CrossOrigin(origins = "*")
"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.
You could also check out the "Data Scripter Add-In" for SQL Server Management Studio 2008 from:
http://www.mssql-vehicle-data.com/SSMS
Their features list:
It was developed on SSMS 2008 and is not supported on the 2005 version at this time (soon!)
Export data quickly to T-SQL for MSSQL and MySQL syntax
CSV, TXT, XML are also supported! Harness the full potential, power, and speed that SQL has to offer.
Don't wait for Access or Excel to do scripting work for you that could take several minutes to do -- let SQL Server do it for you and take all the guess work out of exporting your data!
Customize your data output for rapid backups, DDL manipulation, and more...
Change table names and database schemas to your needs, quickly and efficiently
Export column names or simply generate data without the names.
You can chose individual columns to script.
You can chose sub-sets of data (WHERE clause).
You can chose ordering of data (ORDER BY clause).
Great backup utility for those grungy database debugging operations that require data manipulation. Don't lose data while experimenting. Manipulate data on the fly!
Use an array, not a string, as given as guidance in BashFAQ #50.
Using a string is extremely bad security practice: Consider the case where password
(or a where clause in the query, or any other component) is user-provided; you don't want to eval
a password containing $(rm -rf .)
!
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
"${cmd[@]}"
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf 'Proposing to run: '
printf '%q ' "${cmd[@]}"
printf '\n'
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host 'bash -s' <<<"$cmd_str"
cmd=( mysql AMORE -u username -ppassword -h localhost -e "SELECT host FROM amoreconfig" )
printf -v cmd_str '%q ' "${cmd[@]}"
ssh other_host "bash -c $cmd_str"
If you use vim-plug (Plug), " A minimalist Vim plugin manager.":
:PlugStatus
That will not only list your plugins but check their status.
Well, you have [[
and ]]
to go to the start and end of file. This works in vi.
A quick decision for .bat files if you computer displays your path/file name correct when you typing it in DOS-window:
This way you create a .txt file - temp.txt. Open it in Notepad, copy the text (don't worry it will look unreadable) and paste it in your .bat file. Executing the .bat created this way in DOS-window worked for m? (Cyrillic, Bulgarian).
I combined the top two answers here
In Plesk 12, I had nginx running as a reverse proxy (which I think is the default). So the current top answer doesn't work as nginx is also being run as a proxy.
I went to Subscriptions | [subscription domain] | Websites & Domains (tab) | [Virtual Host domain] | Web Server Settings
.
Then at the bottom of that page you can set the Additional nginx directives which I set to be a combination of the top two answers here:
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
Matvey is right, but you should quote $x and consider any kind of "spaces" (e.g. new line) with
[[ $list =~ (^|[[:space:]])"$x"($|[[:space:]]) ]] && echo 'yes' || echo 'no'
so, i.e.
# list_include_item "10 11 12" "2"
function list_include_item {
local list="$1"
local item="$2"
if [[ $list =~ (^|[[:space:]])"$item"($|[[:space:]]) ]] ; then
# yes, list include item
result=0
else
result=1
fi
return $result
}
end then
`list_include_item "10 11 12" "12"` && echo "yes" || echo "no"
or
if `list_include_item "10 11 12" "1"` ; then
echo "yes"
else
echo "no"
fi
Note that you must use ""
in case of variables:
`list_include_item "$my_list" "$my_item"` && echo "yes" || echo "no"
For bash, Bourne shell and fish:
curl -s http://server/path/script.sh | bash -s arg1 arg2
Flag "-s" makes shell read from stdin.
if the system you use is CentOS/RedHat, and rpm is the way you install MySQL, there is no my.cnf in /etc/ folder, you could use: #whereis mysql #cd /usr/share/mysql/ cp -f /usr/share/mysql/my-medium.cnf /etc/my.cnf
Not sure you resolved this issue or not, but this is how I do it and it works on Android:
"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"
Just had the same issue while using the latest Python 3.6. With Windows OS 10 Home Edition and 64 Bit Operation System
Steps to solve this issue :
Without wanting to give you the answer here is the logic.
You have 2 possible values in each digit. you have 9 of them.
like in base 10 where you have 10 different values by digit say you have 2 of them (which makes from 0 to 99) : 0 to 99 makes 100 numbers. if you do the calcul you have an exponential function
base^numberOfDigits:
10^2 = 100 ;
2^9 = 512
var metaTag = document.getElementsByTagName('meta');
for (var i=0; i < metaTag.length; i++) {
if (metaTag[i].getAttribute("http-equiv")=='refresh')
metaTag[i].content = '666';
if (metaTag[i].getAttribute("name")=='Keywords')
metaTag[i].content = 'js, solver';
}
With usort. Here's a generic solution, that you can use for different columns:
class TableSorter {
protected $column;
function __construct($column) {
$this->column = $column;
}
function sort($table) {
usort($table, array($this, 'compare'));
return $table;
}
function compare($a, $b) {
if ($a[$this->column] == $b[$this->column]) {
return 0;
}
return ($a[$this->column] < $b[$this->column]) ? -1 : 1;
}
}
To sort by first column:
$sorter = new TableSorter(0); // sort by first column
$mdarray = $sorter->sort($mdarray);
Inserts, updates, deletes and reads are generally OK from multiple threads, but Brad's answer is not correct. You have to be careful with how you create your connections and use them. There are situations where your update calls will fail, even if your database doesn't get corrupted.
The basic answer.
The SqliteOpenHelper object holds on to one database connection. It appears to offer you a read and write connection, but it really doesn't. Call the read-only, and you'll get the write database connection regardless.
So, one helper instance, one db connection. Even if you use it from multiple threads, one connection at a time. The SqliteDatabase object uses java locks to keep access serialized. So, if 100 threads have one db instance, calls to the actual on-disk database are serialized.
So, one helper, one db connection, which is serialized in java code. One thread, 1000 threads, if you use one helper instance shared between them, all of your db access code is serial. And life is good (ish).
If you try to write to the database from actual distinct connections at the same time, one will fail. It will not wait till the first is done and then write. It will simply not write your change. Worse, if you don’t call the right version of insert/update on the SQLiteDatabase, you won’t get an exception. You’ll just get a message in your LogCat, and that will be it.
So, multiple threads? Use one helper. Period. If you KNOW only one thread will be writing, you MAY be able to use multiple connections, and your reads will be faster, but buyer beware. I haven't tested that much.
Here's a blog post with far more detail and an example app.
Gray and I are actually wrapping up an ORM tool, based off of his Ormlite, that works natively with Android database implementations, and follows the safe creation/calling structure I describe in the blog post. That should be out very soon. Take a look.
In the meantime, there is a follow up blog post:
Also checkout the fork by 2point0 of the previously mentioned locking example:
If you're okay with Apache commons lib
outputWriter.write(ArrayUtils.join(array, ","));
for (var i in conf) {
val = conf[i];
console.log(val.path);
}
If you want a Date object with fields adjusted for UTC you can do it like this with Joda Time:
import org.joda.time.DateTimeZone;
import java.util.Date;
...
Date local = new Date();
System.out.println("Local: " + local);
DateTimeZone zone = DateTimeZone.getDefault();
long utc = zone.convertLocalToUTC(local.getTime(), false);
System.out.println("UTC: " + new Date(utc));
i use like tim say sprintf('%0.6f', x)
, it's a string then i change it to number by using command str2double(x)
.
SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.
An Ad-Hoc Query is a query that cannot be determined prior to the moment the query is issued. It is created in order to get information when need arises and it consists of dynamically constructed SQL which is usually constructed by desktop-resident query tools.
Check: http://www.learn.geekinterview.com/data-warehouse/dw-basics/what-is-an-ad-hoc-query.html
Look here: http://www.w3schools.com/tags/tag_p.asp
The p element automatically creates some space before and after itself. The space is automatically applied by the browser, or you can specify it in a style sheet.
you could remove the extra space by using css
p {
margin: 0px;
padding: 0px;
}
or use the element <span>
which has no default margins and is an inline element.
In pgAdmin you can also use
SET search_path TO your_db_name;
Update:
This feature is now part of the proplot matplotlib package that I recently released on pypi. By default, when you make figures, the labels are "shared" between axes.
Original answer:
I discovered a more robust method:
If you know the bottom
and top
kwargs that went into a GridSpec
initialization, or you otherwise know the edges positions of your axes in Figure
coordinates, you can also specify the ylabel position in Figure
coordinates with some fancy "transform" magic. For example:
import matplotlib.transforms as mtransforms
bottom, top = .1, .9
f, a = plt.subplots(nrows=2, ncols=1, bottom=bottom, top=top)
avepos = (bottom+top)/2
a[0].yaxis.label.set_transform(mtransforms.blended_transform_factory(
mtransforms.IdentityTransform(), f.transFigure # specify x, y transform
)) # changed from default blend (IdentityTransform(), a[0].transAxes)
a[0].yaxis.label.set_position((0, avepos))
a[0].set_ylabel('Hello, world!')
...and you should see that the label still appropriately adjusts left-right to keep from overlapping with ticklabels, just like normal -- but now it will adjust to be always exactly between the desired subplots.
Furthermore, if you don't even use set_position
, the ylabel will show up by default exactly halfway up the figure. I'm guessing this is because when the label is finally drawn, matplotlib
uses 0.5 for the y
-coordinate without checking whether the underlying coordinate transform has changed.
Not quite, the AND has to be lower-case.
<xsl:when test="4 < 5 and 1 < 2">
<!-- do something -->
</xsl:when>
This is a Bash line that prints all available mac addresses, except the loopback:
for x in `ls /sys/class/net |grep -v lo`; do cat /sys/class/net/$x/address; done
Can be executed from a C program.
Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.
.iframe-embed {
position: absolute;
top: 0;
left: 0;
bottom: 0;
height: 100%;
width: 100%;
border: 0;
}
.iframe-embed-wrapper {
position: relative;
display: block;
height: 0;
padding: 0;
overflow: hidden;
}
.iframe-embed-responsive-16by9 {
padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
<iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>
I have jus implement this library:https://github.com/jose78/go-collection. This is an example about how to use the Foreach loop:
package main
import (
"fmt"
col "github.com/jose78/go-collection/collections"
)
type user struct {
name string
age int
id int
}
func main() {
newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
newList = append(newList, user{"Mon", 0, 3})
newList.Foreach(simpleLoop)
if err := newList.Foreach(simpleLoopWithError); err != nil{
fmt.Printf("This error >>> %v <<< was produced", err )
}
}
var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
fmt.Printf("%d.- item:%v\n", index, mapper)
}
var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
if index > 1{
panic(fmt.Sprintf("Error produced with index == %d\n", index))
}
fmt.Printf("%d.- item:%v\n", index, mapper)
}
The result of this execution should be:
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2
ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
<<< was produced
You can simply add this line into your bootstrap_and_overides.css.less file
body { background: #000000 !important;}
that's it
If you want to remove everything after the last occurrence of separator in a string I find this works well:
<separator>.join(string_to_split.split(<separator>)[:-1])
For example, if string_to_split
is a path like root/location/child/too_far.exe
and you only want the folder path, you can split by "/".join(string_to_split.split("/")[:-1])
and you'll get
root/location/child
The answer from this question provided the answer to this question much more simply.
Write is a special statement designed to generate machine-readable files that are later consumed with Input.
Use Print to avoid any fiddling with data.
Thank you user GSerg
From Xcode 9 and on you can take screenshot or record Video using simctl binary that you can find it here:
/Applications/Xcode.app/Contents/Developer/usr/bin/simctl
You can use it with xcrun to command the simulator in the command line.
For taking screenshot run this in command line:
xcrun simctl io booted screenshot
For recording video on the simulator using command line:
xcrun simctl io booted recordVideo fileName.videoType(e.g mp4/mov)
Note: You can use this command in any directory of your choice. The file will be saved in that directory.
Andrey Tarasevich provides the following explanation:
[Minor changes to formatting made. Parenthetical annotations added in square brackets []
].
The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.
Consider the following code sketch:
if (<condition>) foo(a); else bar(a);
where
foo
andbar
are ordinary functions. Now imagine that you'd like to replace functionfoo
with a macro of the above nature [namedCALL_FUNCS
]:if (<condition>) CALL_FUNCS(a); else bar(a);
Now, if your macro is defined in accordance with the second approach (just
{
and}
) the code will no longer compile, because the 'true' branch ofif
is now represented by a compound statement. And when you put a;
after this compound statement, you finished the wholeif
statement, thus orphaning theelse
branch (hence the compilation error).One way to correct this problem is to remember not to put
;
after macro "invocations":if (<condition>) CALL_FUNCS(a) else bar(a);
This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:
#define CALL_FUNCS(x) \ do { \ func1(x); \ func2(x); \ func3(x); \ } while (0)
Now this code:
if (<condition>) CALL_FUNCS(a); else bar(a);
will compile without any problems.
However, note the small but important difference between my definition of
CALL_FUNCS
and the first version in your message. I didn't put a;
after} while (0)
. Putting a;
at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.I don't know why the author of the code you quoted in your original message put this
;
afterwhile (0)
. In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final;
into the macro (for the reasons that I explained above).
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
touchstart
event as well:As of Angular 4, the HostListener
decorate is the preferred way to do this
import { Component, OnInit, HostListener, ElementRef } from '@angular/core';
...
@Component({...})
export class MyComponent implement OnInit {
constructor(private eRef: ElementRef){}
@HostListener('document:click', ['$event'])
@HostListener('document:touchstart', ['$event'])
handleOutsideClick(event) {
// Some kind of logic to exclude clicks in Component.
// This example is borrowed Kamil's answer
if (!this.eRef.nativeElement.contains(event.target) {
doSomethingCool();
}
}
}
Perfect solution that find old fragment in stack and load it if exist in stack.
/**
* replace or add fragment to the container
*
* @param fragment pass android.support.v4.app.Fragment
* @param bundle pass your extra bundle if any
* @param popBackStack if true it will clear back stack
* @param findInStack if true it will load old fragment if found
*/
public void replaceFragment(Fragment fragment, @Nullable Bundle bundle, boolean popBackStack, boolean findInStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
String tag = fragment.getClass().getName();
Fragment parentFragment;
if (findInStack && fm.findFragmentByTag(tag) != null) {
parentFragment = fm.findFragmentByTag(tag);
} else {
parentFragment = fragment;
}
// if user passes the @bundle in not null, then can be added to the fragment
if (bundle != null)
parentFragment.setArguments(bundle);
else parentFragment.setArguments(null);
// this is for the very first fragment not to be added into the back stack.
if (popBackStack) {
fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
ft.addToBackStack(parentFragment.getClass().getName() + "");
}
ft.replace(R.id.contenedor_principal, parentFragment, tag);
ft.commit();
fm.executePendingTransactions();
}
use it like
Fragment f = new YourFragment();
replaceFragment(f, null, boolean true, true);
You can make the .navbar
fixed width, then set it's left and right margin to auto
.
.navbar{
width: 80%;
margin: 0 auto;
}?
\b
is a zero-width word boundary. Specifically:
Matches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters.
Example: .\b
matches c
in abc
\B
is a zero-width non-word boundary. Specifically:
Matches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W).
Example: \B.\B
matches b
in abc
See regular-expressions.info for more great regex info
Here is a dplyr solution:
df %>% select_if(~sum(!is.na(.)) > 0)
Update: The summarise_if()
function is superseded as of dplyr 1.0
. Here are two other solutions that use the where()
tidyselect function:
df %>%
select(
where(
~sum(!is.na(.x)) > 0
)
)
df %>%
select(
where(
~!all(is.na(.x))
)
)
You can find the info here: http://www.php.net/manual/en/language.operators.comparison.php
It's scarce because it wasn't added until PHP4. What you have is fine though, if you know there may be a type difference then it's a much better comparison, since it's testing value and type in the comparison, not just value.
I have faced this problem in many occassions when I try to start an old rails 2.3.5 project after having worked with rails 3>. In my case to solve the problem, I must do a rubygems update to version 1.4.2, this is:
sudo gem update --system 1.4.2
.img-responsive {
margin: 0 auto;
}
you can write like above code in your document so no need to add one another class in image tag.
Note that you should note that your logic flow must never rely on accessing the HashMap
elements in some order, simply put because HashMap
s are not ordered Collection
s and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).
Back to the post, you already did half the job by loading the first element key:
Object myKey = statusName.keySet().toArray()[0];
Just call map.get(key)
to get the respective value:
Object myValue = statusName.get(myKey);
There is opportunity for several improvements (if you are using DbContext
):
Set:
yourContext.Configuration.AutoDetectChangesEnabled = false;
yourContext.Configuration.ValidateOnSaveEnabled = false;
Do SaveChanges()
in packages of 100 inserts... or you can try with packages of 1000 items and see the changes in performance.
Since during all this inserts, the context is the same and it is getting bigger, you can rebuild your context object every 1000 inserts. var yourContext = new YourContext();
I think this is the big gain.
Doing this improvements in an importing data process of mine, took it from 7 minutes to 6 seconds.
The actual numbers... could not be 100 or 1000 in your case... try it and tweak it.
although it is invalid html but you can use selector context to limit your selector in your case it would be like :
$("input[name='name']" , "#form2").val("Hello World! ");
The easiest way to do this is to click on the Terminate button(red square) in the console:
To break completely out of a foreach loop, break is used;
To go to the next iteration in the loop, continue is used;
Break is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.
Continue is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have continue after an if.
"Just because you send an email doesn't mean it will arrive."
Sending mail is Serious Business - e.g. the domain you're using as your "From:" address may be configured to reject e-mails from your webserver. For a longer overview (and some tips what to check), see http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
The "int" instruction causes an interrupt.
Simple Answer: An interrupt, put simply, is an event that interrupts the CPU, and tells it to run a specific task.
Detailed Answer:
The CPU has a table of Interrupt Service Routines (or ISRs) stored in memory. In Real (16-bit) Mode, this is stored as the IVT, or Interrupt Vector Table. The IVT is typically located at 0x0000:0x0000
(physical address 0x00000
), and it is a series of segment-offset addresses that point to the ISRs. The OS may replace the pre-existing IVT entries with its own ISRs.
(Note: The IVT's size is fixed at 1024 (0x400) bytes.)
In Protected (32-bit) Mode, the CPU uses an IDT. The IDT is a variable-length structure that consists of descriptors (otherwise known as gates), which tell the CPU about the interrupt handlers. The structure of these descriptors is much more complex than the IVT's simple segment-offset entries; here it is:
bytes 0, 1: Lower 16 bits of the ISR's address.
bytes 2, 3: A code segment selector (in the GDT/LDT)
byte 4: Zero.
byte 5: A type field consisting of several bitfields.
bit 0: P (Present): 0 for unused interrupts, 1 for used interrupts.*
bits 1, 2: DPL (Descriptor Privilege Level): The privilege level the descriptor (bytes 2, 3) must have.
bit 3: S (Storage Segment): Is 0 for interrupt and trap gates. Otherwise, is one.
bits 4, 5, 6, 7: GateType:
0101: 32 bit task gate
0110: 16-bit interrupt gate
0111: 16-bit trap gate
1110: 32-bit interrupt gate
1111: 32-bit trap gate
*The IDT may be of variable size, but it must be sequential, i.e. if you declare your IDT to be from 0x00 to 0x50, you must have every interrupt from 0x00 to 0x50. The OS does not necessarily use all of them, so the Present bit allows the CPU to properly handle interrupts the OS does not intend to handle.
When an interrupt occurs (either by an external trigger (e.g. a hardware device) in an IRQ, or by the int
instruction from a program), the CPU pushes EFLAGS, then CS, and then EIP. (These are automatically restored by iret
, the interrupt return instruction.) The OS usually stores more information about the state of the machine, handles the interrupt, restores the machine state, and continues on.
In many *NIX OSes (including Linux), system calls are interrupt based. The program puts the arguments to the system call in the registers (EAX, EBX, ECX, EDX, etc..), and calls interrupt 0x80. The kernel has already set the IDT to contain an interrupt handler on 0x80, which is called when it receives interrupt 0x80. The kernel then reads the arguments and invokes a kernel function accordingly. It may store a return in EAX/EBX. System calls have largely been replaced by the sysenter
and sysexit
(or syscall
and sysret
on AMD) instructions, which allow for faster entry into ring 0.
This interrupt could have a different meaning in a different OS. Be sure to check its documentation.
Put your jQuery function in
$(document).ready(function(){
});
It's surely solved.
Nobody mentioned it, but Putty scp (pscp) has a -pw option for password.
Documentation can be found here: https://the.earth.li/~sgtatham/putty/0.67/htmldoc/Chapter5.html#pscp
Magic strings are mentioned above - I believe they come from the terminfo database:
http://www.google.com/?q=x#q=terminfo
http://www.google.com/?q=x#q=tput+command+in+unix
$ tput clear| od -t x1z 0000000 1b 5b 48 1b 5b 32 4a >.[H.[2J< 0000007
Use -50%
instead of +50%
They will be aligned to left..
Sorry to post answer for very old thread. my answer may help other in future.
string[] TobeDistinct = {"Name","City","State"};
DataTable dtDistinct = GetDistinctRecords(DTwithDuplicate, TobeDistinct);
//Following function will return Distinct records for Name, City and State column.
public static DataTable GetDistinctRecords(DataTable dt, string[] Columns)
{
DataTable dtUniqRecords = new DataTable();
dtUniqRecords = dt.DefaultView.ToTable(true, Columns);
return dtUniqRecords;
}
As pointed out by in the comments, this answers is outdated. youcompleteme
now supports python3 and jedi-vim
no longer breaks the undo history.
Original answer below.
AFAIK there are three options, each with its disadvantages:
Python 3 and undo history (gundo!) are a must for me, so options 1 and 2 are out.
Use checked="checked"
attribute if you want your checkbox to be checked.
I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html
<Button Background="#FF4148" BorderThickness="0" BorderBrush="Transparent">
<Border HorizontalAlignment="Right" BorderBrush="#FF6A6A" BorderThickness="0>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF6A6A" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel Orientation="Horizontal">
<Image RenderOptions.BitmapScalingMode="HighQuality" Source="//ImageName.png" />
</StackPanel>
</Border>
</Button>
As I see PostgreSQL installer doesn't include 64 bit version of ODBC driver, which is necessary in your case. Download psqlodbc_09_00_0310-x64.zip and install it instead. I checked that on Win 7 64 bit and PostgreSQL 9.0.4 64 bit and it looks ok:
Test connection:
After reading so many articles Stackoverflow posts and demo applications to check variable property attributes, I decided to put all the attributes information together:
Below is the detailed article link where you can find above mentioned all attributes, that will definitely help you. Many thanks to all the people who give best answers here!!
1.strong (iOS4 = retain )
Example:
@property (strong, nonatomic) ViewController *viewController;
@synthesize viewController;
2.weak -
Example :
@property (weak, nonatomic) IBOutlet UIButton *myButton;
@synthesize myButton;
Strong & Weak Explanation, Thanks to BJ Homer:
Imagine our object is a dog, and that the dog wants to run away (be deallocated).
Strong pointers are like a leash on the dog. As long as you have the leash attached to the dog, the dog will not run away. If five people attach their leash to one dog, (five strong pointers to one object), then the dog will not run away until all five leashes are detached.
Weak pointers, on the other hand, are like little kids pointing at the dog and saying "Look! A dog!" As long as the dog is still on the leash, the little kids can still see the dog, and they'll still point to it. As soon as all the leashes are detached, though, the dog runs away no matter how many little kids are pointing to it.
As soon as the last strong pointer (leash) no longer points to an object, the object will be deallocated, and all weak pointers will be zeroed out.
When we use weak?
The only time you would want to use weak, is if you wanted to avoid retain cycles (e.g. the parent retains the child and the child retains the parent so neither is ever released).
3.retain = strong
Example:
@property (nonatomic, retain) NSString *name;
@synthesize name;
4.assign
Example:
@property (nonatomic, assign) NSString *address;
@synthesize address;
It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.
REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.
In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."
Worth reading:
in the first you don't define the type that will be held and linked within your arraylist construct
this is the preferred method to do so, you define the type of list and the ide will handle the rest
in the third one you will better just define List for shorter code
response.session doesn't work anymore because response.authResponse is the new way to access the response content after the oauth migration.
Check this for details:
SDKs & Tools › JavaScript SDK › FB.login
Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.
Am I just missing the point here?
A way to look at advantages of arrays is to see where is the O(1) access capability of arrays is required and hence capitalized:
In Look-up tables of your application (a static array for accessing certain categorical responses)
Memoization (already computed complex function results, so that you don't calculate the function value again, say log x)
High Speed computer vision applications requiring image processing (https://en.wikipedia.org/wiki/Lookup_table#Lookup_tables_in_image_processing)
php.ini probably needs to read:
extension=ext\php_sqlsrv_53_nts.dll
Or move the file to same directory as the php executable. This is what I did to my php5 install this week to get odbc_pdo working. :P
Additionally, that doesn't look like proper phpinfo() output. If you make a file with contents<? phpinfo(); ?>
and visit that page, the HTML output should show several sections, including one with loaded modules. (Edited to add: like shown in the screenshot of the above accepted answer)
String.compareTo
might or might not be what you need.
Take a look at this link if you need localized ordering of strings.
Windows uses a different epoch and time units: see Convert Windows Filetime to second in Unix/Linux
What std::time() returns on Windows is (as yet) unknown to me (;-))
For External Tables, Hive stores the data in the LOCATION specified during creation of the table(generally not in warehouse directory). If the external table is dropped, then the table metadata is deleted but not the data.
For Internal tables, Hive stores data into its warehouse directory. If the table is dropped then both the table metadata and the data will be deleted.
Difference between Internal & External tables :
For External Tables -
External table stores files on the HDFS server but tables are not linked to the source file completely.
If you delete an external table the file still remains on the HDFS server.
As an example if you create an external table called “table_test” in HIVE using HIVE-QL and link the table to file “file”, then deleting “table_test” from HIVE will not delete “file” from HDFS.
External table files are accessible to anyone who has access to HDFS file structure and therefore security needs to be managed at the HDFS file/folder level.
Meta data is maintained on master node, and deleting an external table from HIVE only deletes the metadata not the data/file.
For Internal Tables-
- Stored in a directory based on settings in
hive.metastore.warehouse.dir
, by default internal tables are stored in the following directory “/user/hive/warehouse” you can change it by updating the location in the config file .- Deleting the table deletes the metadata and data from master-node and HDFS respectively.
- Internal table file security is controlled solely via HIVE. Security needs to be managed within HIVE, probably at the schema level (depends on organization).
Hive may have internal or external tables, this is a choice that affects how data is loaded, controlled, and managed.
Use EXTERNAL tables when:
Use INTERNAL tables when:
Source :
I think you could do:
$('#google_translate_element').find('*').each(function(){
$(this).unbind('click');
});
but it would cause a lot of overhead
Swift 3 and Above Version(s) for a delay of 10 seconds
DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [unowned self] in
self.functionToCall()
}
I managed to hit this error when simply creating a table! There was obviously no contention problem on a table that didn't yet exist. The CREATE TABLE
statement contained a CONSTRAINT fk_name FOREIGN KEY
clause referencing a well-populated table. I had to:
I just now downgraded my Python 3.9 to 3.6 because I wanted to use the librosa package but it does not support Python 3.9 still now.
Steps -
Run python3 --version
in the terminal and it will show this version of Python.
No, there isn't.
I'm pretty sure there is no way to intercept a click on the refresh button from JS, and even if there was, JS can be turned off.
You should probably step back from your X (preventing refreshing) and find a different solution to Y (whatever that might be).
This is what I found after a more specific Google search than just UTF-8 encode/decode. so for those who are looking for a converting library to convert between encodings, here you go.
https://github.com/inexorabletash/text-encoding
var uint8array = new TextEncoder().encode(str);
var str = new TextDecoder(encoding).decode(uint8array);
Paste from repo readme
All encodings from the Encoding specification are supported:
utf-8 ibm866 iso-8859-2 iso-8859-3 iso-8859-4 iso-8859-5 iso-8859-6 iso-8859-7 iso-8859-8 iso-8859-8-i iso-8859-10 iso-8859-13 iso-8859-14 iso-8859-15 iso-8859-16 koi8-r koi8-u macintosh windows-874 windows-1250 windows-1251 windows-1252 windows-1253 windows-1254 windows-1255 windows-1256 windows-1257 windows-1258 x-mac-cyrillic gb18030 hz-gb-2312 big5 euc-jp iso-2022-jp shift_jis euc-kr replacement utf-16be utf-16le x-user-defined
(Some encodings may be supported under other names, e.g. ascii, iso-8859-1, etc. See Encoding for additional labels for each encoding.)
Neither main()
or void main()
are standard C. The former is allowed as it has an implicit int
return value, making it the same as int main()
. The purpose of main
's return value is to return an exit status to the operating system.
In standard C, the only valid signatures for main
are:
int main(void)
and
int main(int argc, char **argv)
The form you're using: int main()
is an old style declaration that indicates main
takes an unspecified number of arguments. Don't use it - choose one of those above.
The concept of interval notation comes up in both Mathematics and Computer Science. The Mathematical notation [
, ]
, (
, )
denotes the domain (or range) of an interval.
The brackets [
and ]
means:
The parenthesis (
and )
means:
An interval with mixed states is called "half-open".
For example, the range of consecutive integers from 1 .. 10 (inclusive) would be notated as such:
Notice how the word inclusive
was used. If we want to exclude the end point but "cover" the same range we need to move the end-point:
For both left and right edges of the interval there are actually 4 permutations:
(1,10) = 2,3,4,5,6,7,8,9 Set has 8 elements
(1,10] = 2,3,4,5,6,7,8,9,10 Set has 9 elements
[1,10) = 1,2,3,4,5,6,7,8,9 Set has 9 elements
[1,10] = 1,2,3,4,5,6,7,8,9,10 Set has 10 elements
How does this relate to Mathematics and Computer Science?
Array indexes tend to use a different offset depending on which field are you in:
These differences can lead to subtle fence post errors, aka, off-by-one bugs when implementing Mathematical algorithms such as for-loops.
If we have a set or array, say of the first few primes [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ]
, Mathematicians would refer to the first element as the 1st
absolute element. i.e. Using subscript notation to denote the index:
Some programming languages, in contradistinction, would refer to the first element as the zero'th
relative element.
Since the array indexes are in the range [0,N-1] then for clarity purposes it would be "nice" to keep the same numerical value for the range 0 .. N instead of adding textual noise such as a -1
bias.
For example, in C or JavaScript, to iterate over an array of N elements a programmer would write the common idiom of i = 0, i < N
with the interval [0,N) instead of the slightly more verbose [0,N-1]:
function main() {_x000D_
var output = "";_x000D_
var a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];_x000D_
for( var i = 0; i < 10; i++ ) // [0,10)_x000D_
output += "[" + i + "]: " + a[i] + "\n";_x000D_
_x000D_
if (typeof window === 'undefined') // Node command line_x000D_
console.log( output )_x000D_
else_x000D_
document.getElementById('output1').innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
<body onload="main();">_x000D_
<pre id="output1"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
Mathematicians, since they start counting at 1, would instead use the i = 1, i <= N
nomenclature but now we need to correct the array offset in a zero-based language.
e.g.
function main() {_x000D_
var output = "";_x000D_
var a = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ];_x000D_
for( var i = 1; i <= 10; i++ ) // [1,10]_x000D_
output += "[" + i + "]: " + a[i-1] + "\n";_x000D_
_x000D_
if (typeof window === 'undefined') // Node command line_x000D_
console.log( output )_x000D_
else_x000D_
document.getElementById( "output2" ).innerHTML = output;_x000D_
}
_x000D_
<html>_x000D_
<body onload="main()";>_x000D_
<pre id="output2"></pre>_x000D_
</body>_x000D_
</html>
_x000D_
Aside:
In programming languages that are 0-based you might need a kludge of a dummy zero'th element to use a Mathematical 1-based algorithm. e.g. Python Index Start
Interval notation is also important for floating-point numbers to avoid subtle bugs.
When dealing with floating-point numbers especially in Computer Graphics (color conversion, computational geometry, animation easing/blending, etc.) often times normalized numbers are used. That is, numbers between 0.0 and 1.0.
It is important to know the edge cases if the endpoints are inclusive or exclusive:
Where M is some machine epsilon. This is why you might sometimes see const float EPSILON = 1e-#
idiom in C code (such as 1e-6
) for a 32-bit floating point number. This SO question Does EPSILON guarantee anything? has some preliminary details. For a more comprehensive answer see FLT_EPSILON
and David Goldberg's What Every Computer Scientist Should Know About Floating-Point Arithmetic
Some implementations of a random number generator, random()
may produce values in the range 0.0 .. 0.999... instead of the more convenient 0.0 .. 1.0. Proper comments in the code will document this as [0.0,1.0) or [0.0,1.0] so there is no ambiguity as to the usage.
Example:
random()
colors. You convert three floating-point values to unsigned 8-bit values to generate a 24-bit pixel with red, green, and blue channels respectively. Depending on the interval output by random()
you may end up with near-white
(254,254,254) or white
(255,255,255). +--------+-----+
|random()|Byte |
|--------|-----|
|0.999...| 254 | <-- error introduced
|1.0 | 255 |
+--------+-----+
For more details about floating-point precision and robustness with intervals see Christer Ericson's Real-Time Collision Detection, Chapter 11 Numerical Robustness, Section 11.3 Robust Floating-Point Usage.
You have declared your Class as:
@Table( name = "foobar" )
public class FooBar {
You need to write the Class Name for the search.
from FooBar
Have you tried using basicHttpBinding instead of wsHttpBinding? If do not need any authentication and the Ws-* implementations are not required, you'd probably be better off with plain old basicHttpBinding. WsHttpBinding implements WS-Security for message security and authentication.
As answered elsewhere by several people, the Java program is being run on an older version of Java than the one it was compiled it for. It needs to be "crosscompiled" for backward compatibility. To put it another way, there is a mismatch between source and target Java versions.
Changing options in Eclipse menus don't answer the original poster, who said he/she is not using Eclipse. On OpenJDK javac version 1.7, you can crosscompile for 1.6 if you use parameters -source
and -target
, plus provide the rt.jar -file of the target version (that is, the older one) at compile time. If you actually install the 1.6 JRE, you can point to its installation (for example, /usr/lib/jvm/java-6-openjdk-i386/jre/lib/rt.jar on Ubuntu, /usr/jdk/jdk1.6.0_60/jre/lib/rt.jar on SunOS apparently. Sorry, I don't know where it is on a Windows system). Like so:
javac -source 1.6 -target 1.6 -bootclasspath /usr/lib/jvm/java-6-openjdk-i386/jre/lib/rt.jar HelloWorld.java
It looks like you can just download rt.jar from the Internet, and point to it. This is not too elegant though:
javac -source 1.6 -target 1.6 -bootclasspath ./rt.jar HelloWorld.java
With MS SQL 2008, we can list supported error messages in the table sys.messages
SELECT * FROM sys.messages
Try java.lang.Instrumentation.getObjectSize(Object). But please be aware that
It returns an implementation-specific approximation of the amount of storage consumed by the specified object. The result may include some or all of the object's overhead, and thus is useful for comparison within an implementation but not between implementations. The estimate may change during a single invocation of the JVM.
I would give your tds a specific class, e.g. data-cell, and then use something like this:
$("td.data-cell").each(function () {
// 'this' is now the raw td DOM element
var txt = $(this).html();
});
I found a solution for ajax issue noted by Lion_cl.
global.asax:
protected void Application_Error()
{
if (HttpContext.Current.Request.IsAjaxRequest())
{
HttpContext ctx = HttpContext.Current;
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
rc.RouteData.Values["action"] = "AjaxGlobalError";
// TODO: distinguish between 404 and other errors if needed
rc.RouteData.Values["newActionName"] = "WrongRequest";
rc.RouteData.Values["controller"] = "ErrorPages";
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, "ErrorPages");
controller.Execute(rc);
ctx.Server.ClearError();
}
}
ErrorPagesController
public ActionResult AjaxGlobalError(string newActionName)
{
return new AjaxRedirectResult(Url.Action(newActionName), this.ControllerContext);
}
AjaxRedirectResult
public class AjaxRedirectResult : RedirectResult
{
public AjaxRedirectResult(string url, ControllerContext controllerContext)
: base(url)
{
ExecuteResult(controllerContext);
}
public override void ExecuteResult(ControllerContext context)
{
if (context.RequestContext.HttpContext.Request.IsAjaxRequest())
{
JavaScriptResult result = new JavaScriptResult()
{
Script = "try{history.pushState(null,null,window.location.href);}catch(err){}window.location.replace('" + UrlHelper.GenerateContentUrl(this.Url, context.HttpContext) + "');"
};
result.ExecuteResult(context);
}
else
{
base.ExecuteResult(context);
}
}
}
AjaxRequestExtension
public static class AjaxRequestExtension
{
public static bool IsAjaxRequest(this HttpRequest request)
{
return (request.Headers["X-Requested-With"] != null && request.Headers["X-Requested-With"] == "XMLHttpRequest");
}
}
There are some cases where this is handy. I'll use it for a Modularized shell for instance. Each module defines it's own Configuration Dialog databinded to it's settings. I provide it with an ExpandoObject as it's Datacontext and save the values in my configuration Storage. This way the Configuration Dialog writer just has to Bind to a Value and it's automatically created and saved. (And provided to the module for using these settings of course)
It' simply easier to use than an Dictionary. But everyone should be aware that internally it is just a Dictionary.
It's like LINQ just syntactic sugar, but it makes things easier sometimes.
So to answer your question directly: It's easier to write and easier to read. But technically it essentially is a Dictionary<string,object>
(You can even cast it into one to list the values).
In python3 the following works:
>>> v=10.4
>>> print('% 6.2f' % v)
10.40
>>> print('% 12.1f' % v)
10.4
>>> print('%012.1f' % v)
0000000010.4
Try to use this command :
date | cut -d " " -f2-4 | tr " " "-"
The output would be like: 21-Feb-2021
There isn't any direct equivalent to the goto
concept in Java. There are a few constructs that allow you to do some of the things you can do with a classic goto
.
break
and continue
statements allow you to jump out of a block in a loop or switch statement.break <label>
allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).continue <label>
to continue with the next iteration of an outer loop from an inner loop.return
.None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from continue
) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code2.
1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the fillInStackTrace()
method. The downside is that the exception's printStackTrace()
methods won't give you useful information ... should you ever need to call them.
2 - The spaghetti code syndrome spawned the structured programming approach, where you limited in your use of the available language constructs. This could be applied to BASIC, Fortran and COBOL, but it required care and discipline. Getting rid of goto
entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.
There are two ways I know of
1) Console.ReadLine()
at the end of the program. Disadvantage, you have to change your code and have to remember to take it out
2) Run outside of the debugger CONTROL-F5
this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)
string input = "0.55";
var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
if (regex1.IsMatch(input))
{
string dp= regex1.Match(input ).Value;
}
Use custom validation of forms http://docs.angularjs.org/guide/forms Demo: http://plnkr.co/edit/NzeauIDVHlgeb6qF75hX?p=preview
Directive using formaters and parsers and MomentJS )
angModule.directive('moDateInput', function ($window) {
return {
require:'^ngModel',
restrict:'A',
link:function (scope, elm, attrs, ctrl) {
var moment = $window.moment;
var dateFormat = attrs.moDateInput;
attrs.$observe('moDateInput', function (newValue) {
if (dateFormat == newValue || !ctrl.$modelValue) return;
dateFormat = newValue;
ctrl.$modelValue = new Date(ctrl.$setViewValue);
});
ctrl.$formatters.unshift(function (modelValue) {
if (!dateFormat || !modelValue) return "";
var retVal = moment(modelValue).format(dateFormat);
return retVal;
});
ctrl.$parsers.unshift(function (viewValue) {
var date = moment(viewValue, dateFormat);
return (date && date.isValid() && date.year() > 1950 ) ? date.toDate() : "";
});
}
};
});
You need to query the data dictionary, specifically the USER_CONS_COLUMNS
view to see the table columns and corresponding constraints:
SELECT *
FROM user_cons_columns
WHERE table_name = '<your table name>';
FYI, unless you specifically created your table with a lower case name (using double quotes) then the table name will be defaulted to upper case so ensure it is so in your query.
If you then wish to see more information about the constraint itself query the USER_CONSTRAINTS
view:
SELECT *
FROM user_constraints
WHERE table_name = '<your table name>'
AND constraint_name = '<your constraint name>';
If the table is held in a schema that is not your default schema then you might need to replace the views with:
all_cons_columns
and
all_constraints
adding to the where clause:
AND owner = '<schema owner of the table>'
Well, obviously you are trying to send something which is not a string or buffer. :) It works with console, because console accepts anything. Simple example:
var obj = { test : "test" };
console.log( obj ); // works
res.write( obj ); // fails
One way to convert anything to string is to do that:
res.write( "" + obj );
whenever you are trying to send something. The other way is to call .toString()
method:
res.write( obj.toString( ) );
Note that it still might not be what you are looking for. You should always pass strings/buffers to .write
without such tricks.
As a side note: I assume that request
is a asynchronous operation. If that's the case, then res.end();
will be called before any writing, i.e. any writing will fail anyway ( because the connection will be closed at that point ). Move that line into the handler:
request({
uri: 'http://www.google.com',
method: 'GET',
maxRedirects:3
}, function(error, response, body) {
if (!error) {
res.write(response.statusCode);
} else {
//response.end(error);
res.write(error);
}
res.end( );
});
Use capitalize
. From the String documentation:
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
use below command to kill a process running at a certain port - 3000 in this example below
kill -9 $(lsof -t -i:3000)
I was having the same issue, which turned out to be caused by the Domain login that runs the SQL service being locked out in AD. The lockout was caused by an unrelated usage of the service account for another purpose with the wrong password.
The errors received from SQL Agent logs did not mention the service account's name, just the name of the user (job owner) that couldn't be authenticated (since it uses the service account to check with AD).
Use this below code to display pop-up box on page load:
$(document).ready(function() {
var id = '#dialog';
var maskHeight = $(document).height();
var maskWidth = $(window).width();
$('#mask').css({'width':maskWidth,'height':maskHeight});
$('#mask').fadeIn(500);
$('#mask').fadeTo("slow",0.9);
var winH = $(window).height();
var winW = $(window).width();
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
$(id).fadeIn(2000);
$('.window .close').click(function (e) {
e.preventDefault();
$('#mask').hide();
$('.window').hide();
});
$('#mask').click(function () {
$(this).hide();
$('.window').hide();
});
});
<div class="maintext">
<h2> Main text goes here...</h2>
</div>
<div id="boxes">
<div style="top: 50%; left: 50%; display: none;" id="dialog" class="window">
<div id="san">
<a href="#" class="close agree"><img src="close-icon.png" width="25" style="float:right; margin-right: -25px; margin-top: -20px;"></a>
<img src="san-web-corner.png" width="450">
</div>
</div>
<div style="width: 2478px; font-size: 32pt; color:white; height: 1202px; display: none; opacity: 0.4;" id="mask"></div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
I refereed this code from here Demo
Dimension table Dimension table is a table which contain attributes of measurements stored in fact tables. This table consists of hierarchies, categories and logic that can be used to traverse in nodes.
Fact table contains the measurement of business processes, and it contains foreign keys for the dimension tables.
Example – If the business process is manufacturing of bricks
Average number of bricks produced by one person/machine – measure of the business process
In my case junk files from editor caused the problem. I had a config as below:
#...
http {
# ...
include ../sites/*;
}
In the ../sites
directory initially I had a default.config
file.
However, by mistake I saved duplicate files as default.config.save
and default.config.save.1
.
Removing them resolved the issue.
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
If you're looking for a lot more granular control over the date formats, I thoroughly recommend checking out date-FNS. Terrific library - much smaller than moment.js and it's function based approach make it much faster then other class based libraries. Provide large number of operations needed over dates.
In python 3, a way of doing this would be
'{:.2f}'.format(number)
View -> Datasets (bottom of menu, above Refresh)
When you export you use the compatibility system set to MYSQL40
. Worked for me.
use this method:
private ArrayList<myClass> sortList(ArrayList<myClass> list) {
if (list != null && list.size() > 1) {
Collections.sort(list, new Comparator<myClass>() {
public int compare(myClass o1, myClass o2) {
if (o1.getsortnumber() == o2.getsortnumber()) return 0;
return o1.getsortnumber() < o2.getsortnumber() ? 1 : -1;
}
});
}
return list;
}
`
and use: mySortedlist = sortList(myList);
No need to implement comparator in your class.
If you want inverse order swap 1
and -1
str
in Python is represented in Unicode
.UTF-8
is an encoding standard to encode Unicode
string to bytes
. There are many encoding standards out there (e.g. UTF-16
, ASCII
, SHIFT-JIS
, etc.).When the client sends data to your server and they are using UTF-8
, they are sending a bunch of bytes
not str
.
You received a str
because the "library" or "framework" that you are using, has implicitly converted some random bytes
to str
.
Under the hood, there is just a bunch of bytes
. You just need ask the "library" to give you the request content in bytes
and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).
UTF-8
encoded bytes
to str
: bs.decode('utf-8')
str
to UTF-8
bytes
: s.encode('utf-8')
New syntax has been supported for a while by all modern browsers (starting from Chrome 26, Opera 12.1, IE 10 and Firefox 16): http://caniuse.com/#feat=css-gradients
background: linear-gradient(to bottom, rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
This renders a gradient, starting from solid black at the top, to fully transparent at the bottom.
If it worked the way you expected it to (resulting in "abc9"
), what would "9" + 9
deliver? 18
or "99"
?
To remove this ambiguity, you are required to make explicit what you want to convert in this case:
"abc" + str(9)
You could use an anonymous type:
.Select(i => new { i.name, i.category_name })
The compiler will generate the code for a class with name
and category_name
properties and returns instances of that class. You can also manually specify property names:
i => new { Id = i.category_id, Name = i.category_name }
You can have arbitrary number of properties.
You cannot directly change a form's validity. If all the descendant inputs are valid, the form is valid, if not, then it is not.
What you should do is to set the validity of the input element. Like so;
addItem.capabilities.$setValidity("youAreFat", false);
Now the input (and so the form) is invalid. You can also see which error causes invalidation.
addItem.capabilities.errors.youAreFat == true;
You can just use the ContentResult
to return a plain string:
public ActionResult Temp() {
return Content("Hi there!");
}
ContentResult
by default returns a text/plain
as its contentType. This is overloadable so you can also do:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
aspectRatio = width / height
if that is what you're after. You can then multiply it by one of the dimensions of the target space to find out the other (that maintains the ratio) e.g.
widthT = heightT * aspectRatio
heightT = widthT / aspectRatio
The standard Web Storage, does not say anything about the restoring any of these. So there won't be any standard way to do it. You have to go through the way the browsers implement these, or find a way to backup these before you delete them.
It seems like an IllegalArgumentException
is called for if you don't want null
to be an allowed value, and the NullPointerException
would be thrown if you were trying to use a variable that turns out to be null
.
User.Identity.GetUserId();
does not exist in asp.net identity core 2.0. in this regard, i have managed in different way. i have created a common class for use whole application, because of getting user information.
create a common class PCommon & interface IPCommon
adding reference using System.Security.Claims
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Common.Web.Helper
{
public class PCommon: IPCommon
{
private readonly IHttpContextAccessor _context;
public PayraCommon(IHttpContextAccessor context)
{
_context = context;
}
public int GetUserId()
{
return Convert.ToInt16(_context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
}
public string GetUserName()
{
return _context.HttpContext.User.Identity.Name;
}
}
public interface IPCommon
{
int GetUserId();
string GetUserName();
}
}
Here the implementation of common class
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Pay.DataManager.Concreate;
using Pay.DataManager.Helper;
using Pay.DataManager.Models;
using Pay.Web.Helper;
using Pay.Web.Models.GeneralViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Pay.Controllers
{
[Authorize]
public class BankController : Controller
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger _logger;
private readonly IPCommon _iPCommon;
public BankController(IUnitOfWork unitOfWork, IPCommon IPCommon, ILogger logger = null)
{
_unitOfWork = unitOfWork;
_iPCommon = IPCommon;
if (logger != null) { _logger = logger; }
}
public ActionResult Create()
{
BankViewModel _bank = new BankViewModel();
CountryLoad(_bank);
return View();
}
[HttpPost, ActionName("Create")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Insert(BankViewModel bankVM)
{
if (!ModelState.IsValid)
{
CountryLoad(bankVM);
//TempData["show-message"] = Notification.Show(CommonMessage.RequiredFieldError("bank"), "Warning", type: ToastType.Warning);
return View(bankVM);
}
try
{
bankVM.EntryBy = _iPCommon.GetUserId();
var userName = _iPCommon.GetUserName()();
//_unitOfWork.BankRepo.Add(ModelAdapter.ModelMap(new Bank(), bankVM));
//_unitOfWork.Save();
// TempData["show-message"] = Notification.Show(CommonMessage.SaveMessage(), "Success", type: ToastType.Success);
}
catch (Exception ex)
{
// TempData["show-message"] = Notification.Show(CommonMessage.SaveErrorMessage("bank"), "Error", type: ToastType.Error);
}
return RedirectToAction(nameof(Index));
}
}
}
get userId and name in insert action
_iPCommon.GetUserId();
Thanks, Maksud
Changing your lists to numpy
arrays will do the job!!
import matplotlib.pyplot as plt
from scipy import stats
import numpy as np
x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15
plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()
As others have said, there is no universally correct block size; what is optimal for one situation or one piece of hardware may be terribly inefficient for another. Also, depending on the health of the disks it may be preferable to use a different block size than what is "optimal".
One thing that is pretty reliable on modern hardware is that the default block size of 512 bytes tends to be almost an order of magnitude slower than a more optimal alternative. When in doubt, I've found that 64K is a pretty solid modern default. Though 64K usually isn't THE optimal block size, in my experience it tends to be a lot more efficient than the default. 64K also has a pretty solid history of being reliably performant: You can find a message from the Eug-Lug mailing list, circa 2002, recommending a block size of 64K here: http://www.mail-archive.com/[email protected]/msg12073.html
For determining THE optimal output block size, I've written the following script that tests writing a 128M test file with dd at a range of different block sizes, from the default of 512 bytes to a maximum of 64M. Be warned, this script uses dd internally, so use with caution.
dd_obs_test.sh:
#!/bin/bash
# Since we're dealing with dd, abort if any errors occur
set -e
TEST_FILE=${1:-dd_obs_testfile}
TEST_FILE_EXISTS=0
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=1; fi
TEST_FILE_SIZE=134217728
if [ $EUID -ne 0 ]; then
echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi
# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'
# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
# Calculate number of segments required to copy
COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))
if [ $COUNT -le 0 ]; then
echo "Block size of $BLOCK_SIZE estimated to require $COUNT blocks, aborting further tests."
break
fi
# Clear kernel cache to ensure more accurate test
[ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches
# Create a test file with the specified block size
DD_RESULT=$(dd if=/dev/zero of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync 2>&1 1>/dev/null)
# Extract the transfer rate from dd's STDERR output
TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')
# Clean up the test file if we created one
if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi
# Output the result
printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done
I've only tested this script on a Debian (Ubuntu) system and on OSX Yosemite, so it will probably take some tweaking to make work on other Unix flavors.
By default the command will create a test file named dd_obs_testfile in the current directory. Alternatively, you can provide a path to a custom test file by providing a path after the script name:
$ ./dd_obs_test.sh /path/to/disk/test_file
The output of the script is a list of the tested block sizes and their respective transfer rates like so:
$ ./dd_obs_test.sh
block size : transfer rate
512 : 11.3 MB/s
1024 : 22.1 MB/s
2048 : 42.3 MB/s
4096 : 75.2 MB/s
8192 : 90.7 MB/s
16384 : 101 MB/s
32768 : 104 MB/s
65536 : 108 MB/s
131072 : 113 MB/s
262144 : 112 MB/s
524288 : 133 MB/s
1048576 : 125 MB/s
2097152 : 113 MB/s
4194304 : 106 MB/s
8388608 : 107 MB/s
16777216 : 110 MB/s
33554432 : 119 MB/s
67108864 : 134 MB/s
(Note: The unit of the transfer rates will vary by OS)
To test optimal read block size, you could use more or less the same process, but instead of reading from /dev/zero and writing to the disk, you'd read from the disk and write to /dev/null. A script to do this might look like so:
dd_ibs_test.sh:
#!/bin/bash
# Since we're dealing with dd, abort if any errors occur
set -e
TEST_FILE=${1:-dd_ibs_testfile}
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=$?; fi
TEST_FILE_SIZE=134217728
# Exit if file exists
if [ -e $TEST_FILE ]; then
echo "Test file $TEST_FILE exists, aborting."
exit 1
fi
TEST_FILE_EXISTS=1
if [ $EUID -ne 0 ]; then
echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi
# Create test file
echo 'Generating test file...'
BLOCK_SIZE=65536
COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))
dd if=/dev/urandom of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync > /dev/null 2>&1
# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'
# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
# Clear kernel cache to ensure more accurate test
[ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches
# Read test file out to /dev/null with specified block size
DD_RESULT=$(dd if=$TEST_FILE of=/dev/null bs=$BLOCK_SIZE 2>&1 1>/dev/null)
# Extract transfer rate
TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')
printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done
# Clean up the test file if we created one
if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi
An important difference in this case is that the test file is a file that is written by the script. Do not point this command at an existing file or the existing file will be overwritten with zeroes!
For my particular hardware I found that 128K was the most optimal input block size on a HDD and 32K was most optimal on a SSD.
Though this answer covers most of my findings, I've run into this situation enough times that I wrote a blog post about it: http://blog.tdg5.com/tuning-dd-block-size/ You can find more specifics on the tests I performed there.
My very simple solution, which doesn't require any additional modules:
def addmonth(date):
if date.day < 20:
date2 = date+timedelta(32)
else :
date2 = date+timedelta(25)
date2.replace(date2.year, date2.month, day)
return date2
This is a way to see if any XML-files exists in that folder, yes.
To check for specific files use File.Exists(path)
, which will return a boolean indicating wheter the file at path
exists.
This should be faster than iterating and will work regardless of shape.
numpy.isnan(myarray).any()
Edit: 30x faster:
import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
'numpy.isnan(a).any()',
'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
print " %.2f s" % timeit.Timer(m, s).timeit(1000), m
Results:
0.11 s numpy.isnan(a).any()
3.75 s any(numpy.isnan(x) for x in a.flatten())
Bonus: it works fine for non-array NumPy types:
>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True
Numeric defines the TOTAL number of digits, and then the number after the decimal.
A numeric(3,2) can only hold up to 9.99.
Depending on which event you actually want to use (textbox change
, or button click
), you can try this:
HTML:
<input id="color" type="text" onchange="changeBackground(this);" />
<br />
<span id="coltext">This text should have the same color as you put in the text box</span>
JS:
function changeBackground(obj) {
document.getElementById("coltext").style.color = obj.value;
}
DEMO: http://jsfiddle.net/6pLUh/
One minor problem with the button was that it was a submit button, in a form. When clicked, that submits the form (which ends up just reloading the page) and any changes from JavaScript are reset. Just using the onchange
allows you to change the color based on the input.
I just tried the same in EF6 (code first entity rename). I simply renamed the class and added a migration using the package manager console and voila, a migration using RenameTable(...) was automatically generated for me. I have to admit that I made sure the only change to the entity was renaming it so no new columns or renamed columns so I cannot be certain if this is an EF6 thing or just that EF was (always) able to detect such simple migrations.
I have combined several sources to produce the code below, which I am currently using. I have also removed the Windows.Forms references so I can use it from console and WPF applications without additional references.
using System;
using System.Runtime.InteropServices;
public class MouseOperations
{
[Flags]
public enum MouseEventFlags
{
LeftDown = 0x00000002,
LeftUp = 0x00000004,
MiddleDown = 0x00000020,
MiddleUp = 0x00000040,
Move = 0x00000001,
Absolute = 0x00008000,
RightDown = 0x00000008,
RightUp = 0x00000010
}
[DllImport("user32.dll", EntryPoint = "SetCursorPos")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(out MousePoint lpMousePoint);
[DllImport("user32.dll")]
private static extern void mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
public static void SetCursorPosition(int x, int y)
{
SetCursorPos(x, y);
}
public static void SetCursorPosition(MousePoint point)
{
SetCursorPos(point.X, point.Y);
}
public static MousePoint GetCursorPosition()
{
MousePoint currentMousePoint;
var gotPoint = GetCursorPos(out currentMousePoint);
if (!gotPoint) { currentMousePoint = new MousePoint(0, 0); }
return currentMousePoint;
}
public static void MouseEvent(MouseEventFlags value)
{
MousePoint position = GetCursorPosition();
mouse_event
((int)value,
position.X,
position.Y,
0,
0)
;
}
[StructLayout(LayoutKind.Sequential)]
public struct MousePoint
{
public int X;
public int Y;
public MousePoint(int x, int y)
{
X = x;
Y = y;
}
}
}
From http://www.sqlite.org/lang_createtable.html:
CREATE TABLE IF NOT EXISTS some_table (id INTEGER PRIMARY KEY AUTOINCREMENT, ...);
For your question :
SELECT id,
IF(qty_1 <= '23', price,
IF(('23' > qty_1 && qty_2 <= '23'), price_2,
IF(('23' > qty_2 && qty_3 <= '23'), price_3,
IF(('23' > qty_2 && qty_3<='23'), price_3,
IF('23' > qty_3, price_4, 1))))) as total
FROM product;
You can use the if - else
control structure or the IF
function in MySQL.
Reference:
http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/
here's how:
import pygame
screen=pygame.display.set_mode([640, 480])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=90
height=90
filled=0
pygame.draw.rect(screen, [red, blue, green], [left, top, width, height], filled)
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
pygame.quit()
Plenty of good solutions here.
One challenge not really addressed in any of them is how to visually identify certain hard-to-spot non-ASCII characters that resemble other plain ASCII ones. For example, en dashes can appear almost exactly like hyphens and curly quotes look a lot like straight quotes, depending on your text editor's font.
This one-liner, which should work on Mac or Linux, will strip characters not in the ASCII printable range and show you the differences side-by-side:
# assumes Bash shell; for Bourne shell (sh), rearrange as a pipe and
# give '-' as second argument to 'sdiff' instead
sdiff --suppress-common-lines script.py <(tr -cd '\11\12\15\40-\176' <script.py)
The characters \11
, \12
, and \15
are tab, newline, and carriage return, respectively, in octal; the remaining range is the visible ASCII characters. (hat tip)
Another tip gleaned from this SO thread uses an inverse character class consisting of anything not in the ASCII visible range, and highlights it:
grep --color '[^ -~]' script.py
This should also work fine with the macOS / BSD version of grep.
Subquery is the name.
At times it's required, but good/bad depends on how it's applied.
here's another alternative using vector::assign
:
theVector.assign(theSet.begin(), theSet.end());
AFAIK, You have to use image function imagecreatefromstring, imagejpeg to create the images.
$imageData = base64_decode($imageData);
$source = imagecreatefromstring($imageData);
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
Hope this will help.
PHP CODE WITH IMAGE DATA
$imageDataEncoded = base64_encode(file_get_contents('sample.png'));
$imageData = base64_decode($imageDataEncoded);
$source = imagecreatefromstring($imageData);
$angle = 90;
$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
$imageName = "hello1.png";
$imageSave = imagejpeg($rotate,$imageName,100);
imagedestroy($source);
So Following is the php part of your program .. NOTE
the change with comment Change is here
$uploadedPhotos = array('photo_1','photo_2','photo_3','photo_4');
foreach ($uploadedPhotos as $file) {
if($this->input->post($file)){
$imageData = base64_decode($this->input->post($file)); // <-- **Change is here for variable name only**
$photo = imagecreatefromstring($imageData); // <-- **Change is here**
/* Set name of the photo for show in the form */
$this->session->set_userdata('upload_'.$file,'ant');
/*set time of the upload*/
if(!$this->session->userdata('uploading_on_datetime')){
$this->session->set_userdata('uploading_on_datetime',time());
}
$datetime_upload = $this->session->userdata('uploading_on_datetime',true);
/* create temp dir with time and user id */
$new_dir = 'temp/user_'.$this->session->userdata('user_id',true).'_on_'.$datetime_upload.'/';
if(!is_dir($new_dir)){
@mkdir($new_dir);
}
/* move uploaded file with new name */
// @file_put_contents( $new_dir.$file.'.jpg',imagejpeg($photo));
imagejpeg($photo,$new_dir.$file.'.jpg',100); // <-- **Change is here**
}
}
I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile
:
env=~/.ssh/agent.env
agent_load_env () { test -f "$env" && . "$env" >| /dev/null ; }
agent_start () {
(umask 077; ssh-agent >| "$env")
. "$env" >| /dev/null ; }
agent_load_env
# agent_run_state: 0=agent running w/ key; 1=agent w/o key; 2= agent not running
agent_run_state=$(ssh-add -l >| /dev/null 2>&1; echo $?)
if [ ! "$SSH_AUTH_SOCK" ] || [ $agent_run_state = 2 ]; then
agent_start
ssh-add
elif [ "$SSH_AUTH_SOCK" ] && [ $agent_run_state = 1 ]; then
ssh-add
fi
unset env
I probably have something configured weird, but was not successful when I added it to my .profile
or .bashrc
. The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.
You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.
int digits=1;
while (x>=10){
x/=10;
digits++;
}
return digits;
This can be done in one line with lodash _.tail
:
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
The way I fixed similar issue was by adding Month to my SELECT portion
Month DATEADD(day,Created_Date,'1971/12/31') As Month
and than I added WHERE statement
Month DATEADD(day,Created_Date,'1971/12/31') = month(getdate())-1
A single quote is the start and end of a string. A semicolon is the end of a statement. So if they were doing a select like this:
Select *
From Students
Where (Name = '<NameGetsInsertedHere>')
The SQL would become:
Select *
From Students
Where (Name = 'Robert'); DROP TABLE STUDENTS; --')
-- ^-------------------------------^
On some systems, the select
would get ran first followed by the drop
statement! The message is: DONT EMBED VALUES INTO YOUR SQL. Instead use parameters!
If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use), multiprocessing.cpu_count()
is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python:
import os
import re
import subprocess
def available_cpu_count():
""" Number of available virtual or physical CPUs on this system, i.e.
user/real as output by time(1) when called with an optimally scaling
userspace-only program"""
# cpuset
# cpuset may restrict the number of *available* processors
try:
m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
open('/proc/self/status').read())
if m:
res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
if res > 0:
return res
except IOError:
pass
# Python 2.6+
try:
import multiprocessing
return multiprocessing.cpu_count()
except (ImportError, NotImplementedError):
pass
# https://github.com/giampaolo/psutil
try:
import psutil
return psutil.cpu_count() # psutil.NUM_CPUS on old versions
except (ImportError, AttributeError):
pass
# POSIX
try:
res = int(os.sysconf('SC_NPROCESSORS_ONLN'))
if res > 0:
return res
except (AttributeError, ValueError):
pass
# Windows
try:
res = int(os.environ['NUMBER_OF_PROCESSORS'])
if res > 0:
return res
except (KeyError, ValueError):
pass
# jython
try:
from java.lang import Runtime
runtime = Runtime.getRuntime()
res = runtime.availableProcessors()
if res > 0:
return res
except ImportError:
pass
# BSD
try:
sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
stdout=subprocess.PIPE)
scStdout = sysctl.communicate()[0]
res = int(scStdout)
if res > 0:
return res
except (OSError, ValueError):
pass
# Linux
try:
res = open('/proc/cpuinfo').read().count('processor\t:')
if res > 0:
return res
except IOError:
pass
# Solaris
try:
pseudoDevices = os.listdir('/devices/pseudo/')
res = 0
for pd in pseudoDevices:
if re.match(r'^cpuid@[0-9]+$', pd):
res += 1
if res > 0:
return res
except OSError:
pass
# Other UNIXes (heuristic)
try:
try:
dmesg = open('/var/run/dmesg.boot').read()
except IOError:
dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
dmesg = dmesgProcess.communicate()[0]
res = 0
while '\ncpu' + str(res) + ':' in dmesg:
res += 1
if res > 0:
return res
except OSError:
pass
raise Exception('Can not determine number of CPUs on this system')
Change RadioGroup group
with CompoundButton buttonView
and then press Ctrl+Shift+O to fix your imports.
Found a perfect solution for the problem 100% working on mobile as well as desktop
https://codepen.io/mrinaljain/pen/YObgEP
.jpx-is-wrapper {_x000D_
display: block;_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
z-index: 314749261;_x000D_
width: 100vw;_x000D_
height: 300px_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container {_x000D_
background-color: transparent;_x000D_
border: 0;_x000D_
box-sizing: content-box;_x000D_
clip: rect(auto auto auto auto);_x000D_
color: black;_x000D_
left: 0;_x000D_
margin: 0 auto;_x000D_
overflow: visible;_x000D_
position: absolute;_x000D_
text-align: left;_x000D_
top: 0;_x000D_
visibility: visible;_x000D_
width: 100%;_x000D_
z-index: auto;_x000D_
height: 300px_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container>.jpx-is-content {_x000D_
left: 0;_x000D_
overflow: hidden;_x000D_
right: 0;_x000D_
top: 0;_x000D_
visibility: visible;_x000D_
width: 100%;_x000D_
position: relative;_x000D_
height: 300px;_x000D_
display: block_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container>.jpx-is-content>.jpx-is-ad {_x000D_
-webkit-box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;_x000D_
-moz-box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;_x000D_
box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;_x000D_
bottom: 26px;_x000D_
left: 0;_x000D_
margin: 0 auto;_x000D_
right: 0;_x000D_
text-align: center;_x000D_
height: 588px;_x000D_
top: 49px;_x000D_
bottom: auto;_x000D_
-webkit-transform: translateZ(0);_x000D_
-moz-transform: translateZ(0);_x000D_
-ms-transform: translateZ(0);_x000D_
-o-transform: translateZ(0);_x000D_
transform: translateZ(0)_x000D_
}_x000D_
_x000D_
.jpx-position-fixed {_x000D_
position: fixed_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container>.jpx-is-content>.jpx-is-ad>.jpx-is-ad-frame {_x000D_
width: 100%;_x000D_
height: 100%_x000D_
}_x000D_
_x000D_
.black-fader {_x000D_
position: absolute;_x000D_
z-index: 1;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
opacity: 0.75_x000D_
}_x000D_
_x000D_
.video-containers {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
bottom: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
overflow: hidden;_x000D_
z-index: 0_x000D_
}_x000D_
_x000D_
.video-containers video,.video-containers img {_x000D_
min-width: 100%;_x000D_
min-height: 100%;_x000D_
width: auto;_x000D_
height: auto;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%)_x000D_
}
_x000D_
<p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p>_x000D_
_x000D_
<div class="jpx-is-wrapper">_x000D_
<div class="jpx-is-container">_x000D_
<div class="jpx-is-content">_x000D_
<div class="jpx-is-ad jpx-position-fixed">_x000D_
<div scrolling="no" width="100%" height="100%" class="jcl-wrapper" style="border: 0px; display: block; width: 100%; height: 100%;">_x000D_
<div class="video-containers" id="video-container">_x000D_
<img src="https://via.placeholder.com/350x150" alt="" class="">_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p>
_x000D_
try:
ALTER TABLE `user` CHANGE `id` `id` INT( 11 ) COMMENT 'id of user'
Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.
Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.
Although System.Collections.Generic.Dictionary matches the tag "hashmap" and will work well in your example, it is not an exact equivalent of C++'s std::map - std::map is an ordered collection.
If ordering is important you should use SortedDictionary.
/* Working method */_x000D_
.tinted-image {_x000D_
background: _x000D_
/* top, transparent red, faked with gradient */ _x000D_
linear-gradient(_x000D_
rgba(255, 0, 0, 0.45), _x000D_
rgba(255, 0, 0, 0.45)_x000D_
),_x000D_
/* bottom, image */_x000D_
url(https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg);_x000D_
height: 1280px;_x000D_
width: 960px;_x000D_
background-size: cover;_x000D_
}_x000D_
_x000D_
.tinted-image p {_x000D_
color: #fff;_x000D_
padding: 100px;_x000D_
}
_x000D_
<div class="tinted-image">_x000D_
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam distinctio, temporibus tempora a eveniet quas qui veritatis sunt perferendis harum!</p>_x000D_
_x000D_
</div>
_x000D_
source: https://css-tricks.com/tinted-images-multiple-backgrounds/
If you are using opencv3, you can print Mat like python numpy style
:
Mat xTrainData = (Mat_<float>(5,2) << 1, 1, 1, 1, 2, 2, 2, 2, 2, 2);
cout << "xTrainData (python) = " << endl << format(xTrainData, Formatter::FMT_PYTHON) << endl << endl;
Output as below, you can see it'e more readable, see here for more information.
But in most case, there is no need to output all the data in Mat, you can output by row range like 0 ~ 2 row:
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <iomanip>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
//row: 6, column: 3,unsigned one channel
Mat image1(6, 3, CV_8UC1, 5);
// output row: 0 ~ 2
cout << "image1 row: 0~2 = "<< endl << " " << image1.rowRange(0, 2) << endl << endl;
//row: 8, column: 2,unsigned three channel
Mat image2(8, 2, CV_8UC3, Scalar(1, 2, 3));
// output row: 0 ~ 2
cout << "image2 row: 0~2 = "<< endl << " " << image2.rowRange(0, 2) << endl << endl;
return 0;
}
Output as below:
Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.
char c[2];
int i=1;
sprintf(c, "%d", i);
For this type error: UnexpectedTypeException ERROR: We are trying to use incorrect Hibernate validator annotation on any bean property. For this same issue for my Springboot project( validating type 'java.lang.Integer')
The solution that worked for me is using @NotNull
for Integer.
If you are using windows and are interested in clearing the screen before running the program, you can compile the file call it from a .bat file. for example:
cls
java "what ever the name of the compiles class is"
Save as "etc".bat and then running by calling it in the command prompt or double clicking the file
The difference between
import java.util.*;
and
import java.util.*;
import java.util.List;
import java.util.Arrays;
becomes apparent when the code refers to some other List
or Arrays
(for example, in the same package, or also imported generally). In the first case, the compiler will assume that the Arrays
declared in the same package is the one to use, in the latter, since it is declared specifically, the more specific java.util.Arrays
will be used.
if ($("#cartContent").children().length == 0)
{
// no child
}
Modify the_script.php like this.
<script>
the_function() {
alert("You win");
}
</script>
Using iTextSharp.dll
protected void Page_Load(object sender, EventArgs e)
{
String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
if (System.IO.File.Exists(destinationFile))
System.IO.File.Delete(destinationFile);
string[] sSrcFile;
sSrcFile = new string[2];
string[] arr = new string[2];
for (int i = 0; i <= sourceFiles.Length - 1; i++)
{
if (sourceFiles[i] != null)
{
if (sourceFiles[i].Trim() != "")
arr[i] = sourceFiles[i].ToString();
}
}
if (arr != null)
{
sSrcFile = new string[2];
for (int ic = 0; ic <= arr.Length - 1; ic++)
{
sSrcFile[ic] = arr[ic].ToString();
}
}
try
{
int f = 0;
PdfReader reader = new PdfReader(sSrcFile[f]);
int n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
int rotation;
while (f < sSrcFile.Length)
{
int i = 0;
while (i < n)
{
i++;
document.SetPageSize(PageSize.A4);
document.NewPage();
page = writer.GetImportedPage(reader, i);
rotation = reader.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
Response.Write("\n Processed page " + i);
}
f++;
if (f < sSrcFile.Length)
{
reader = new PdfReader(sSrcFile[f]);
n = reader.NumberOfPages;
Response.Write("There are " + n + " pages in the original file.");
}
}
Response.Write("Success");
document.Close();
}
catch (Exception e)
{
Response.Write(e.Message);
}
}
It solves to me, for my purposes:
.select-container {
position:relative;
width:200px;
height:18px;
overflow:hidden;
border:1px solid white !important
}
.select-container select {
position:relative;
left:-2px;
top:-2px
}
To put more style will be necessary to use nested divs .
In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
You should write in this way
public function up()
{
Schema::create('transactions', function (Blueprint $table) {
$table->bigIncrements('id');
$table->float('amount', 11, 2);
$table->enum('transaction type', ['debit', 'credit']);
$table->bigInteger('customer_id')->unsigned();
$table->timestamps();
});
Schema::table('transactions', function($table) {
$table->foreign('customer_id')
->references('id')->on('customers')
->onDelete('cascade');
});
}
The foreign key field should be unsigned, hope it helps!!
Just add http://download.eclipse.org/egit/updates to your Eclipse update manager.
You can useflatten()
from the numpy package.
import numpy as np
a = np.array([[1, 2],
[3, 4],
[5, 6]])
a_flat = a.flatten()
print(f"original array: {a} \nflattened array = {a_flat}")
Output:
original array: [[1 2]
[3 4]
[5 6]]
flattened array = [1 2 3 4 5 6]
There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:
ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");
That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource
methods.
ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");
or alternatively if you just want the input stream:
InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");
The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.
EDIT:
The getContext() method is obviously something you would have to implement. JSP pages make it available as the context
field. In a servlet you get it from your ServletConfig
which is passed into the servlet's init()
method. If you store it at that time, you can get your ServletContext any time you want after that.
The one major thing I think people are leaving out is that Build and Clean are both tasks that are performed based on Visual Studio's knowledge of your Project/Solution. I see a lot of complaining that Clean doesn't work or leaves leftover files or is not trustworthy, when in fact, the reasons you say it isn't trustworthy actually makes it more trustworthy.
Clean will only remove (clean) files and/or directories that Visual Studio or the compiler themselves have in fact created. If you copy your own files or files/folder structures get created from an outside tool or source, then Visual Studio doesn't "know they exist" and therefore, should not touch them.
Can you imagine if the Clean operation basically performed a "del *.*" ? This could be catastrophic.
Build performs a compile on changed or necessary projects.
Rebuild performs a compile regardless of change or what's necessary.
Clean removes files/folders it has created in the past, but leaves anything that it didn't have anything to do with, initially.
I hope this elaborates a bit and helps.
Maybe you could try this? I use this in my programs.
Data= open ('data.txt', 'r')
data = Data.readlines()
for i in range(len(data)):
data[i] = data[i].strip()+ ' '
data = ''.join(data).strip()
Agree with @Tillito, however in most cases it will foul SQL optimizer and it will not use right indexes.
It may be obvious for somebody, but I burned hours solving performance issues using Tillito solution. Lets say you have the table:
Create table OrderDetail
(
Id int primary key,
CustomerId int references Customer(Id),
Amount decimal default(0)
);
Create index ix_customer on OrderDetail(CustomerId);
and your view is something like this
Create view CustomerView
As
Select
IsNull(CustomerId, -1) as CustomerId, -- forcing EF to use it as key
Sum(Amount) as Amount
From OrderDetail
Group by CustomerId
Sql optimizer will not use index ix_customer and it will perform table scan on primary index, but if instead of:
Group by CustomerId
you use
Group by IsNull(CustomerId, -1)
it will make MS SQL (at least 2008) include right index into plan.
If
These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".
The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.
ffmpeg
vs the fake oneFor a while both Libav and FFmpeg separately developed their own version of ffmpeg
.
Libav then renamed their bizarro ffmpeg
to avconv
to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv
instead of their counterfeit version of ffmpeg
. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.
This message was removed upstream when the fake "ffmpeg
" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.
In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1
. Unfortunately the new "deprecated" message has caused additional user confusion.
Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg
is back in the repositories again.
To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.
If you are using avconv
then you are using Libav. If you are using ffmpeg
you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.
Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h
header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg
or avconv
and viewing the console output.
ffmpeg
The real ffmpeg
is in the repository, so you can install it with:
apt-get install ffmpeg
Your options are:
ffmpeg
,ffmpeg
,These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.
Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg
from the repository.
For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.
#include<iostream>
using namespace std;
template<class t>
class base {
protected:
t a;
public:
base(t aa){
a = aa;
cout<<"base "<<a<<endl;
}
};
template <class t>
class derived: public base<t>{
public:
derived(t a): base<t>(a) {
}
//Here is the method in derived class
void sampleMethod() {
cout<<"In sample Method"<<endl;
}
};
int main() {
derived<int> q(1);
// calling the methods
q.sampleMethod();
}
Add toString()
method to your address
class then do
System.out.println(Arrays.toString(houseAddress));
Please post your Model Class.
To check the errors in your ModelState
use the following code:
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
OR: You can also use
var errors = ModelState.Values.SelectMany(v => v.Errors);
Place a break point at the above line and see what are the errors in your ModelState
.
var table = $('#myTableId').DataTable();
var a= [];
$.each(table.rows('.myClassName').data(), function() {
a.push(this["productId"]);
});
console.log(a[0]);
From Firefox 34 onwards you now have an option for Storage Inspector, which you can enable it from developer tools settings
Once there, you can enable the Storage
options under Default Firefox Developer tools
Updated 27-3-16
Firefox 48.0a1 now supports Cookies editing.
Updated 3-4-16
Firefox 48.0a1 now supports localStorage and sessionStorage editing.
Updated 02-08-16
Firefox 48 (stable release) and onward supports editing of all storage types, except IndexedDB
If listOfIds
is a list, this will work, but, List.Contains() is a linear search, so this isn't terribly efficient.
You're better off storing the ids you want to look up into a container that is suited for searching, like Set.
List<int> listOfIds = new List(GetListOfIds());
lists.Where(r=>listOfIds.Contains(r.Id));
static const size_t npos = -1;
Maximum value for size_t
npos is a static member constant value with the greatest possible value for an element of type size_t.
This value, when used as the value for a len (or sublen) parameter in string's member functions, means "until the end of the string".
As a return value, it is usually used to indicate no matches.
This constant is defined with a value of -1, which because size_t is an unsigned integral type, it is the largest possible representable value for this type.
Use a single backspace after each character
printf("hello wor\bl\bd\n");
Try the export function of phpMyAdmin.
I think there is also a possibility to copy the database files from one server to another, but I do not have a server available at the moment so I can't test it.
Below is another way by which we can JSON data with JSON.stringify() function
var Utils = {};
Utils.MyClass1 = function (id, member) {
this.id = id;
this.member = member;
}
var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") };
alert(JSON.stringify(myobject));
Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU
Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.
ggplot(mpg, aes(cty, hwy)) +
geom_point() +
xlab("\nYour_x_Label") + ylab("Your_y_Label\n")
Hope that helps!
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:
input[type=text]::-ms-clear { display: none; }
One can even get less specific by using just:
::-ms-clear { display: none; }
I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.
SELECT * FROM table ORDER BY id DESC LIMIT 50
save resources make one query, there is no need to make nested queries
Java conveniently has the instanceof
operator (JLS 15.20.2) to test if a given object is of a given type.
if (x instanceof List<?>) {
List<?> list = (List<?>) x;
// do something with list
} else if (x instanceof Collection<?>) {
Collection<?> col = (Collection<?>) x;
// do something with col
}
One thing should be mentioned here: it's important in these kinds of constructs to check in the right order. You will find that if you had swapped the order of the check in the above snippet, the code will still compile, but it will no longer work. That is the following code doesn't work:
// DOESN'T WORK! Wrong order!
if (x instanceof Collection<?>) {
Collection<?> col = (Collection<?>) x;
// do something with col
} else if (x instanceof List<?>) { // this will never be reached!
List<?> list = (List<?>) x;
// do something with list
}
The problem is that a List<?>
is-a Collection<?>
, so it will pass the first test, and the else
means that it will never reach the second test. You have to test from the most specific to the most general type.
just use \r\n for endline if you are using windows operating system.
I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.
(MUST switch to the Database you want to observe to get object_id)
SELECT
TL.resource_type,
TL.resource_database_id,
TL.resource_associated_entity_id,
TL.request_mode,
TL.request_session_id,
WT.blocking_session_id,
O.name AS [object name],
O.type_desc AS [object descr],
P.partition_id AS [partition id],
P.rows AS [partition/page rows],
AU.type_desc AS [index descr],
AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT
ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O
ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P
ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU
ON AU.allocation_unit_id = TL.resource_associated_entity_id;
Just use Kotlin!
val list = listOf(user1, user2, user3)
val maxDate = list.maxBy { it.date }?.date
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php
. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
Prior to Java 8:
The static variables were stored in the permgen space(also called the method area).
PermGen Space is also known as Method Area
PermGen Space used to store 3 things
From Java 8 onwards
The static variables are stored in the Heap itself.From Java 8 onwards the PermGen Space have been removed and new space named as MetaSpace is introduced which is not the part of Heap any more unlike the previous Permgen Space. Meta-Space is present on the native memory (memory provided by the OS to a particular Application for its own usage) and it now only stores the class meta-data.
The interned strings and static variables are moved into the heap itself.
For official information refer : JEP 122:Remove the Permanent Gen Space
Building on alko's answer that almost worked for me, except for the filtering step (where I get: ValueError: cannot reindex from a duplicate axis
), here is the final solution I used:
# join the dataframes
united_data = pd.concat([data1, data2, data3, ...])
# group the data by the whole row to find duplicates
united_data_grouped = united_data.groupby(list(united_data.columns))
# detect the row indices of unique rows
uniq_data_idx = [x[0] for x in united_data_grouped.indices.values() if len(x) == 1]
# extract those unique values
uniq_data = united_data.iloc[uniq_data_idx]
Not exactly for this OP, but for those who encountered 404 and cannot set response content-type
to "application/json"
(any content-type
). One possibility is a server actually responds 406 but explorer (e.g., chrome) prints it as 404.
If you do not customize message converter, spring would use AbstractMessageConverterMethodProcessor.java
. It would run:
List<MediaType> requestedMediaTypes = getAcceptableMediaTypes(request);
List<MediaType> producibleMediaTypes = getProducibleMediaTypes(request, valueType, declaredType);
and if they do not have any overlapping (the same item), it would throw HttpMediaTypeNotAcceptableException
and this finally causes 406. No matter if it is an ajax, or GET/POST, or form action, if the request uri ends with a .html
or any suffix, the requestedMediaTypes
would be "text/[that suffix]", and this conflicts with producibleMediaTypes
, which is usually:
"application/json"
"application/xml"
"text/xml"
"application/*+xml"
"application/json"
"application/*+json"
"application/json"
"application/*+json"
"application/xml"
"text/xml"
"application/*+xml"
"application/xml"
"text/xml"
"application/*+xml"
The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.
Since version 1.0.0
you define optional parameters with:
<Route path="to/page(/:pathParam)" component={MyPage} />
and for multiple optional parameters:
<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />
You use parenthesis (
)
to wrap the optional parts of route, including the leading slash (/
). Check out the Route Matching Guide page of the official documentation.
Note: The :paramName
parameter matches a URL segment up to the next /
, ?
, or #
. For more about paths and params specifically, read more here.
React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.
Instead, you are instructed to define a path
parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?
).
As such, to define an optional parameter, you do:
<Route path="/to/page/:pathParam?" component={MyPage} />
and for multiple optional parameters:
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />
Note: React Router v4 is incompatible with react-router-relay (read more here). Use version v3 or earlier (v2 recommended) instead.
This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:
var values = ["Red", "Green"],
colors = document.getElementById("colors");
_.each(colors.options, function (option) {
option.selected = ~_.indexOf(values, option.text);
});
If you're using jQuery, it could be even more terse:
var values = ["Red", "Green"];
$("#colors option").prop("selected", function () {
return ~$.inArray(this.text, values);
});
If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:
var color, i, j,
values = ["Red", "Green"],
options = document.getElementById("colors").options;
for ( i = 0; i < values.length; i++ ) {
for ( j = 0, color = values[i]; j < options.length; j++ ) {
options[j].selected = options[j].selected || color === options[j].text;
}
}
In my case adding following lines to lambda.js {my deployed is on AWS Lambda} fixed the issue.
'font/opentype',
'font/sfnt',
'font/ttf',
'font/woff',
'font/woff2'
The best colors I've found --which aside from being so beautiful, are very easy to look at too and do not boil my eyes-- are the ones I've found listed in this GitHub repository: VSCode Snazzy
Very Easy Installation:
Copy the contents of snazzy.json into your VS Code "settings.json" file.
(In case you don't know how to open the "settings.json" file, first hit Ctrl+Shift+P and then write Preferences: open settings(JSON) and hit enter).
Notice: For those who have tried ColorTool and it works outside VSCode but not inside VSCode, you've made no mistakes in implementing it, that's just a decision of VSCode developers for the VSCode's terminal to be colored independently.
Sounds like you want:
var movies = _db.Movies.Where(p => p.Genres.Intersect(listOfGenres).Any());
char *line = strdup("user name"); // don't do char *line = "user name"; see Note
char *first_part = strtok(line, " "); //first_part points to "user"
char *sec_part = strtok(NULL, " "); //sec_part points to "name"
Note: strtok
modifies the string, so don't hand it a pointer to string literal.