If you need use it as a default configuration, just place min: 0
inside the node defaults.scale.ticks
, as follows:
defaults: {
global: {...},
scale: {
...
ticks: { min: 0 },
}
},
Reference: https://www.chartjs.org/docs/latest/axes/
In Chart.js version 2.0, it is possible to set labels for axes:
options = {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
See Labelling documentation for more details.
(this question is a duplicate of In chart.js, Is it possible to hide x-axis label/text of bar chart if accessing from mobile?) They added the option, 2.1.4 (and maybe a little earlier) has it
var myLineChart = new Chart(ctx, {
type: 'line',
data: data,
options: {
scales: {
xAxes: [{
ticks: {
display: false
}
}]
}
}
}
you can use console.log()
to print object
console.log(my_object_array);
in case you have big object and want to print some of its values then you can use this custom function to print array in console
this.print = function (data,bpoint=0) {
var c = 0;
for(var k=0; k<data.length; k++){
c++;
console.log(c+' '+data[k]);
if(k!=0 && bpoint === k)break;
}
}
usage
print(array); // to print entire obj array
or
print(array,50); // 50 value to print only
In my case setting the referenced object to NULL in my object before the merge o save method solve the problem, in my case the referenced object was catalog, that doesn't need to be saved, because in some cases I don't have it even.
fisEntryEB.setCatStatesEB(null);
(fisEntryEB) getSession().merge(fisEntryEB);
On Windows (with Cygwin) try
cat /dev/clipboard
or echo "foo" > /dev/clipboard
as mentioned in this article.
None of that worked for me, so here is a working solution...
In Info.plist
, add a row:
UIViewControllerBasedStatusBarAppearance
, and set the value NO
.
Then in AppDelegate in didFinishLaunchingWithOptions
, add these rows:
[application setStatusBarHidden:NO];
[application setStatusBarStyle:UIStatusBarStyleLightContent];
package all.is.well;_x000D_
import java.io.IOException;_x000D_
import java.io.RandomAccessFile;_x000D_
import java.util.concurrent.ExecutorService;_x000D_
import java.util.concurrent.Executors;_x000D_
import junit.framework.TestCase;_x000D_
_x000D_
/**_x000D_
* @author Naresh Bhabat_x000D_
* _x000D_
Following implementation helps to deal with extra large files in java._x000D_
This program is tested for dealing with 2GB input file._x000D_
There are some points where extra logic can be added in future._x000D_
_x000D_
_x000D_
Pleasenote: if we want to deal with binary input file, then instead of reading line,we need to read bytes from read file object._x000D_
_x000D_
_x000D_
_x000D_
It uses random access file,which is almost like streaming API._x000D_
_x000D_
_x000D_
* ****************************************_x000D_
Notes regarding executor framework and its readings._x000D_
Please note :ExecutorService executor = Executors.newFixedThreadPool(10);_x000D_
_x000D_
* for 10 threads:Total time required for reading and writing the text in_x000D_
* :seconds 349.317_x000D_
* _x000D_
* For 100:Total time required for reading the text and writing : seconds 464.042_x000D_
* _x000D_
* For 1000 : Total time required for reading and writing text :466.538 _x000D_
* For 10000 Total time required for reading and writing in seconds 479.701_x000D_
*_x000D_
* _x000D_
*/_x000D_
public class DealWithHugeRecordsinFile extends TestCase {_x000D_
_x000D_
static final String FILEPATH = "C:\\springbatch\\bigfile1.txt.txt";_x000D_
static final String FILEPATH_WRITE = "C:\\springbatch\\writinghere.txt";_x000D_
static volatile RandomAccessFile fileToWrite;_x000D_
static volatile RandomAccessFile file;_x000D_
static volatile String fileContentsIter;_x000D_
static volatile int position = 0;_x000D_
_x000D_
public static void main(String[] args) throws IOException, InterruptedException {_x000D_
long currentTimeMillis = System.currentTimeMillis();_x000D_
_x000D_
try {_x000D_
fileToWrite = new RandomAccessFile(FILEPATH_WRITE, "rw");//for random write,independent of thread obstacles _x000D_
file = new RandomAccessFile(FILEPATH, "r");//for random read,independent of thread obstacles _x000D_
seriouslyReadProcessAndWriteAsynch();_x000D_
_x000D_
} catch (IOException e) {_x000D_
// TODO Auto-generated catch block_x000D_
e.printStackTrace();_x000D_
}_x000D_
Thread currentThread = Thread.currentThread();_x000D_
System.out.println(currentThread.getName());_x000D_
long currentTimeMillis2 = System.currentTimeMillis();_x000D_
double time_seconds = (currentTimeMillis2 - currentTimeMillis) / 1000.0;_x000D_
System.out.println("Total time required for reading the text in seconds " + time_seconds);_x000D_
_x000D_
}_x000D_
_x000D_
/**_x000D_
* @throws IOException_x000D_
* Something asynchronously serious_x000D_
*/_x000D_
public static void seriouslyReadProcessAndWriteAsynch() throws IOException {_x000D_
ExecutorService executor = Executors.newFixedThreadPool(10);//pls see for explanation in comments section of the class_x000D_
while (true) {_x000D_
String readLine = file.readLine();_x000D_
if (readLine == null) {_x000D_
break;_x000D_
}_x000D_
Runnable genuineWorker = new Runnable() {_x000D_
@Override_x000D_
public void run() {_x000D_
// do hard processing here in this thread,i have consumed_x000D_
// some time and ignore some exception in write method._x000D_
writeToFile(FILEPATH_WRITE, readLine);_x000D_
// System.out.println(" :" +_x000D_
// Thread.currentThread().getName());_x000D_
_x000D_
}_x000D_
};_x000D_
executor.execute(genuineWorker);_x000D_
}_x000D_
executor.shutdown();_x000D_
while (!executor.isTerminated()) {_x000D_
}_x000D_
System.out.println("Finished all threads");_x000D_
file.close();_x000D_
fileToWrite.close();_x000D_
}_x000D_
_x000D_
/**_x000D_
* @param filePath_x000D_
* @param data_x000D_
* @param position_x000D_
*/_x000D_
private static void writeToFile(String filePath, String data) {_x000D_
try {_x000D_
// fileToWrite.seek(position);_x000D_
data = "\n" + data;_x000D_
if (!data.contains("Randomization")) {_x000D_
return;_x000D_
}_x000D_
System.out.println("Let us do something time consuming to make this thread busy"+(position++) + " :" + data);_x000D_
System.out.println("Lets consume through this loop");_x000D_
int i=1000;_x000D_
while(i>0){_x000D_
_x000D_
i--;_x000D_
}_x000D_
fileToWrite.write(data.getBytes());_x000D_
throw new Exception();_x000D_
} catch (Exception exception) {_x000D_
System.out.println("exception was thrown but still we are able to proceeed further"_x000D_
+ " \n This can be used for marking failure of the records");_x000D_
//exception.printStackTrace();_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
You can use this jquery plugin:
http://digitalbush.com/projects/masked-input-plugin/
Refer to demo tab, phone option.
This is not possible (as @JaredPar already mentioned). Trying to put logic to work around this is a bad practice. In case you have a base class
that have an enum
, you should list of all possible enum-values
there, and the implementation of class should work with the values that it knows.
E.g. Supposed you have a base class BaseCatalog
, and it has an enum ProductFormats
(Digital
, Physical
). Then you can have a MusicCatalog
or BookCatalog
that could contains both Digital
and Physical
products, But if the class is ClothingCatalog
, it should only contains Physical
products.
Interesting that these answers utilize printf
like it is a given.
printf
converts the integer to a Hexadecimal string value.
//*************************************************************
// void prntnum(unsigned long n, int base, char sign, char *outbuf)
// unsigned long num = number to be printed
// int base = number base for conversion; decimal=10,hex=16
// char sign = signed or unsigned output
// char *outbuf = buffer to hold the output number
//*************************************************************
void prntnum(unsigned long n, int base, char sign, char *outbuf)
{
int i = 12;
int j = 0;
do{
outbuf[i] = "0123456789ABCDEF"[num % base];
i--;
n = num/base;
}while( num > 0);
if(sign != ' '){
outbuf[0] = sign;
++j;
}
while( ++i < 13){
outbuf[j++] = outbuf[i];
}
outbuf[j] = 0;
}
You may connect to Oracle database using sqlplus:
sqlplus "/as sysdba"
Then create new users and assign privileges.
grant all privileges to dac;
I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:
var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();
your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if
as a top-level step in declarative, so you need to wrap it in a script
step. here's a working declarative version:
pipeline {
agent any
stages {
stage('test') {
steps {
sh 'echo hello'
}
}
stage('test1') {
steps {
sh 'echo $TEST'
}
}
stage('test3') {
steps {
script {
if (env.BRANCH_NAME == 'master') {
echo 'I only execute on the master branch'
} else {
echo 'I execute elsewhere'
}
}
}
}
}
}
you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!
Here is a highly simplified but hopefully relevant view of what happens when you build your code in C++.
C++ splits the load of generating machine executable code in following different phases -
Preprocessing - This is where any macros - #define
s etc you might be using get expanded.
Compiling - Each cpp file along with all the #include
d files in that file directly or indirectly (together called a compilation unit) is converted into machine readable object code.
This is where C++ also checks that all functions defined (i.e. containing a body in {
}
e.g.
void Foo( int x){ return Boo(x); })
are referring to other functions in a valid manner.
The way it does that is by insisting that you provide at least a declaration of these other functions (e.g. void Boo(int);
) before you call it so it can check that you are calling it properly among other things. This can be done either directly in the cpp file where it is called or usually in an included header file.
Note that only the machine code that corresponds to functions defined in this cpp and included files gets built as the object (binary) version of this compilation unit (e.g. Foo) and not the ones that are merely declared (e.g. Boo).
Linking - This is the stage where C++ goes hunting for stuff declared and called in each compilation unit and links it to the places where it is getting called. Now if there was no definition found of this function the linker gives up and errors out. Similarly if it finds multiple definitions of the same function signature (essentially the name and parameter types it takes) it also errors out as it considers it ambiguous and doesn't want to pick one arbitrarily.
The latter is what is happening in your case. By doing a #include
of the fun.cpp
file, both fun.cpp
and mainfile.cpp
have a definition of funct()
and the linker doesn't know which one to use in your program and is complaining about it.
The fix as Vaughn mentioned above is to not include the cpp file with the definition of funct()
in mainfile.cpp
and instead move the declaration of funct()
in a separate header file and include that in mainline.cpp
. This way the compiler will get the declaration of funct()
to work with and the linker would get just one definition of funct()
from fun.cpp
and will use it with confidence.
Faced the same problem, although I am using yarn.
The following worked for me:
yarn install
yarn start
Will it work for you ?
class MyClass;
typedef std::pair<int,MyClass> MyPair;
class MyClass
{
private:
void foo() const{};
public:
static void Method(MyPair const& p)
{
//......
p.second.foo();
};
};
// ...
std::map<int, MyClass> Map;
//.....
std::for_each(Map.begin(), Map.end(), (&MyClass::Method));
Your loading of the JSON data is a little fragile. Instead of:
json_raw= raw.readlines()
json_object = json.loads(json_raw[0])
you should really just do:
json_object = json.load(raw)
You shouldn't think of what you get as a "JSON object". What you have is a list. The list contains two dicts. The dicts contain various key/value pairs, all strings. When you do json_object[0]
, you're asking for the first dict in the list. When you iterate over that, with for song in json_object[0]:
, you iterate over the keys of the dict. Because that's what you get when you iterate over the dict. If you want to access the value associated with the key in that dict, you would use, for example, json_object[0][song]
.
None of this is specific to JSON. It's just basic Python types, with their basic operations as covered in any tutorial.
This is not an error, it is a warning from your Microsoft compiler.
Select your project and click "Properties" in the context menu.
In the dialog, chose Configuration Properties
-> C/C++
-> Preprocessor
In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS
to turn those warnings off.
As error shows that path can not be imported.
So here we will use the url instead of path as shown below:-
first import the url package then replace the path with url
from django.conf.urls import url
urlpatterns = [
url('admin/', admin.site.urls),
]
for more information you can take the reference of this link.
This is the simplest solution working for me.
$('#your_modal_id').clone().prop("id", "new_modal_id").appendTo("target_container");
Here I have tried this CSS for all major browser & tested: Custom color are working fine on scrollbar.
Yes, there are limitations on several versions of different browsers.
/* Only Chrome */
html::-webkit-scrollbar {width: 17px;}
html::-webkit-scrollbar-thumb {background-color: #0064a7; background-clip: padding-box; border: 1px solid #8ea5b5;}
html::-webkit-scrollbar-track {background-color: #8ea5b5; }
::-webkit-scrollbar-button {background-color: #8ea5b5;}
/* Only IE */
html {scrollbar-face-color: #0064a7; scrollbar-shadow-color: #8ea5b5; scrollbar-highlight-color: #8ea5b5;}
/* Only FireFox */
html {scrollbar-color: #0064a7 #8ea5b5;}
/* View Scrollbar */
html {overflow-y: scroll;overflow-x: hidden;}
_x000D_
<!doctype html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<header>
<div id="logo"><img src="/logo.png">HTML5 Layout</div>
<nav>
<ul>
<li><a href="/">Home</a>
<li><a href="https://html-css-js.com/">HTML</a>
<li><a href="https://html-css-js.com/css/code/">CSS</a>
<li><a href="https://htmlcheatsheet.com/js/">JS</a>
</ul>
</nav>
</header>
<section>
<strong>Demonstration of a simple page layout using HTML5 tags: header, nav, section, main, article, aside, footer, address.</strong>
</section>
<section id="pageContent">
<main role="main">
<article>
<h2>Stet facilis ius te</h2>
<p>Lorem ipsum dolor sit amet, nonumes voluptatum mel ea, cu case ceteros cum. Novum commodo malorum vix ut. Dolores consequuntur in ius, sale electram dissentiunt quo te. Cu duo omnes invidunt, eos eu mucius fabellas. Stet facilis ius te, quando voluptatibus eos in. Ad vix mundi alterum, integre urbanitas intellegam vix in.</p>
</article>
<article>
<h2>Illud mollis moderatius</h2>
<p>Eum facete intellegat ei, ut mazim melius usu. Has elit simul primis ne, regione minimum id cum. Sea deleniti dissentiet ea. Illud mollis moderatius ut per, at qui ubique populo. Eum ad cibo legimus, vim ei quidam fastidii.</p>
</article>
<article>
<h2>Ex ignota epicurei quo</h2>
<p>Quo debet vivendo ex. Qui ut admodum senserit partiendo. Id adipiscing disputando eam, sea id magna pertinax concludaturque. Ex ignota epicurei quo, his ex doctus delenit fabellas, erat timeam cotidieque sit in. Vel eu soleat voluptatibus, cum cu exerci mediocritatem. Malis legere at per, has brute putant animal et, in consul utamur usu.</p>
</article>
<article>
<h2>His at autem inani volutpat</h2>
<p>Te has amet modo perfecto, te eum mucius conclusionemque, mel te erat deterruisset. Duo ceteros phaedrum id, ornatus postulant in sea. His at autem inani volutpat. Tollit possit in pri, platonem persecuti ad vix, vel nisl albucius gloriatur no.</p>
</article>
</main>
<aside>
<div>Sidebar 1</div>
<div>Sidebar 2</div>
<div>Sidebar 3</div>
</aside>
</section>
<footer>
<p>© You can copy, edit and publish this template but please leave a link to our website | <a href="https://html5-templates.com/" target="_blank" rel="nofollow">HTML5 Templates</a></p>
<address>
Contact: <a href="mailto:[email protected]">Mail me</a>
</address>
</footer>
</body>
</html>
_x000D_
For Asp.Net core you better use
<partial name="_MyPartialView" model="MyModel" />
So for example
@foreach (var item in Model)
{
<partial name="_MyItemView" model="item" />
}
There is a supported API for accomplishing this! Add something like this to your NSURLConnection
delegate:
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])
if ([trustedHosts containsObject:challenge.protectionSpace.host])
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
Note that connection:didReceiveAuthenticationChallenge:
can send its message to challenge.sender (much) later, after presenting a dialog box to the user if necessary, etc.
In rails 4, you need to put
require File.expand_path('../../lib', __FILE__) + '/ext/string'
in your config/application.rb
Use Application.GetSaveAsFilename()
in the same way that you used Application.GetOpenFilename()
Another place this error can happen in is assigning a value that has a comma outside of a string. For example:
SET totalvalue = (IFNULL(i.subtotal,0) + IFNULL(i.tax,0),0)
What I did:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
and
xsi:schemaLocation="
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd">
works perfectlly. More Baeldung
My understanding is that this question is better answered over in this post.
But briefly, the answer to the OP with this method is simply:
s1 = pd.merge(df1, df2, how='inner', on=['user_id'])
Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.
I've been looking for better way of doing it recently. Associative array sounded like overkill for me. Look what I found:
suffix=bzz
declare prefix_$suffix=mystr
...and then...
varname=prefix_$suffix
echo ${!varname}
tf.keras.backend.eval
is useful for evaluating small expressions.
tf.keras.backend.eval(op)
TF 1.x and TF 2.0 compatible.
Minimal Verifiable Example
from tensorflow.keras.backend import eval
m1 = tf.constant([[3., 3.]])
m2 = tf.constant([[2.],[2.]])
eval(tf.matmul(m1, m2))
# array([[12.]], dtype=float32)
This is useful because you do not have to explicitly create a Session
or InteractiveSession
.
Guys found the perfect way to monitor ALL traffic that is flowing locally between requests from my machine to my machine:
Install Wireshark
When you need to capture traffic that is flowing from a localhost to a localhost then you will struggle to use wireshark as this only monitors incoming traffic on the network card. The way to do this is to add a route to windows that will force all traffic through a gateway and this be captured on the network interface.
To do this, add a route with <ip address>
<gateway>
:
cmd> route add 192.168.20.30 192.168.20.1
Then run a capture on wireshark (make sure you select the interface that has bytes flowing through it) Then filter.
The newly added routes will come up in black. (as they are local addresses)
You could translate spaces to newlines and then grep, e.g.:
cat * | tr ' ' '\n' | grep th
Invoke the windows port of md5sum.exe. It's about two times as fast as the .NET implementation (at least on my machine using a 1.2 GB file)
public static string Md5SumByProcess(string file) {
var p = new Process ();
p.StartInfo.FileName = "md5sum.exe";
p.StartInfo.Arguments = file;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
string output = p.StandardOutput.ReadToEnd();
return output.Split(' ')[0].Substring(1).ToUpper ();
}
When you execute the flutter doctor
command it checks your environment and displays a report to the terminal window. In your case it seems that you did not install the dart and flutter plugin to be able to use them in Android Studio.
To install a plugin, click on Files>Settings>Plugins>install jetbrain plugins
The plugins will add new functionalities to android studio related to flutter. Example it will add the flutter inspector, outliner.
The SDK that you added to the path, will be needed when creating a new flutter project.
following links might help
http://labe.felk.cvut.cz/~xfaigl/mep/xml/java-xml.htm
One of the easy way is:
<input type="hidden" id="SaleDateValue" value="@ViewBag.SaleDate" />
<input type="hidden" id="VoidItem" value="@Model.SecurityControl["VoidItem"].ToString()" />
And then get the value in javascript:
var SaleDate = document.getElementById('SaleDateValue').value;
var Item = document.getElementById('VoidItem').value;
by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.
example as below http://jsfiddle.net/BfLAh/1/
$(document).mousemove(function(e) {
$("#follow").css({
left: e.pageX,
top: e.pageY
});
});
_x000D_
#follow {
position: absolute;
text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
updated to follow slowly
for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
for the speed , you can set the jquery .animation duration to certain amount.
It's often clearer to separate the two actions git pull
does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch
. The second is that it then merges in changes, which can of course be done with git merge
, though other options such as git rebase
are occasionally useful.
$('input[name=myradiobutton]:radio:checked')
will get you the selected radio button
$('input[name=myradiobutton]:radio:not(:checked)')
will get you the unselected radio buttons
Using this you can do this
$('input[name=myradiobutton]:radio:not(:checked)').val("0");
Update: After reading your Update I think I understand You will want to do something like this
var myRadioValue;
function radioValue(jqRadioButton){
if (jqRadioButton.length) {
myRadioValue = jqRadioButton.val();
}
else {
myRadioValue = 0;
}
}
$(document).ready(function () {
$('input[name=myradiobutton]:radio').click(function () { //Hook the click event for selected elements
radioValue($('input[name=myradiobutton]:radio:checked'));
});
radioValue($('input[name=myradiobutton]:radio:checked')); //check for value on page load
});
Try this:
def word(string, num)
string = 'Smith'
string[0..(num-1)]
end
Contrary to what is commonly believed, named parameters can be implemented in standard, old-school JavaScript (for boolean parameters only) by means of a simple, neat coding convention, as shown below.
function f(p1=true, p2=false) {
...
}
f(!!"p1"==false, !!"p2"==true); // call f(p1=false, p2=true)
Caveats:
Ordering of arguments must be preserved - but the pattern is still useful, since it makes it obvious which actual argument is meant for which formal parameter without having to grep for the function signature or use an IDE.
This only works for booleans. However, I'm sure a similar pattern could be developed for other types using JavaScript's unique type coercion semantics.
I believe that is just how the browser renders their standard input. If you set a border on the input:
<input type="text" style="width: 10px; padding: 2px; border: 1px solid black"/>
<div style="width: 10px; border: solid 1px black; padding: 2px"> </div>
Then both are the same width, at least in FF.
Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing
#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()
<%= f.select :email_provider, ["gmail","yahoo","msn"]%>
You can also do this as well (shorter cut) instead of having to do instance declaration. You do this in JSON instead.
class Book {
public BookId: number;
public Title: string;
public Author: string;
public Price: number;
public Description: string;
}
var bks: Book[] = [];
bks.push({BookId: 1, Title:"foo", Author:"foo", Price: 5, Description: "foo"}); //This is all done in JSON.
In order to change the label size you can select an appropriate size policy for the label like expanding or minimum expanding.
You can scale the pixmap by keeping its aspect ratio every time it changes:
QPixmap p; // load pixmap
// get label dimensions
int w = label->width();
int h = label->height();
// set a scaled pixmap to a w x h window keeping its aspect ratio
label->setPixmap(p.scaled(w,h,Qt::KeepAspectRatio));
There are two places where you should add this code:
resizeEvent
of the widget that contains the labelIn modern, supported browsers, you can simply do that in CSS with -
header{
position: sticky;
top: 0;
}
Note: The HTML structure is important while using position: sticky
, since it's make the element sticky relative to the parent. And the sticky positioning might not work with a single element made sticky within a parent.
Run the snippet below to check a sample implementation.
main{_x000D_
padding: 0;_x000D_
}_x000D_
header{_x000D_
position: sticky;_x000D_
top:0;_x000D_
padding:40px;_x000D_
background: lightblue;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
content > div {_x000D_
height: 50px;_x000D_
}
_x000D_
<main>_x000D_
<header>_x000D_
This is my header_x000D_
</header>_x000D_
<content>_x000D_
<div>Some content 1</div>_x000D_
<div>Some content 2</div>_x000D_
<div>Some content 3</div>_x000D_
<div>Some content 4</div>_x000D_
<div>Some content 5</div>_x000D_
<div>Some content 6</div>_x000D_
<div>Some content 7</div>_x000D_
<div>Some content 8</div>_x000D_
</content>_x000D_
</main>
_x000D_
I'm sure someone can do better, but this works:
sapply(as.character(q.data$string), function(x, letter = "a"){
sum(unlist(strsplit(x, split = "")) == letter)
})
greatgreat magic not
2 1 0
or in a function:
countLetter <- function(charvec, letter){
sapply(charvec, function(x, letter){
sum(unlist(strsplit(x, split = "")) == letter)
}, letter = letter)
}
countLetter(as.character(q.data$string),"a")
I needed to remove any trailing zeros but keep at least 2 decimals, including any zeros.
The numbers I'm working with are 6 decimal number strings, generated by .toFixed(6).
Expected Result:
var numstra = 12345.000010 // should return 12345.00001
var numstrb = 12345.100000 // should return 12345.10
var numstrc = 12345.000000 // should return 12345.00
var numstrd = 12345.123000 // should return 12345.123
Solution:
var numstr = 12345.100000
while (numstr[numstr.length-1] === "0") {
numstr = numstr.slice(0, -1)
if (numstr[numstr.length-1] !== "0") {break;}
if (numstr[numstr.length-3] === ".") {break;}
}
console.log(numstr) // 12345.10
Logic:
Run loop function if string last character is a zero.
Remove the last character and update the string variable.
If updated string last character is not a zero, end loop.
If updated string third to last character is a floating point, end loop.
As long as you need to find it based on Count just more than 0, it is better to use EXISTS like this:
IF EXISTS (SELECT 1 FROM INCIDENTS WHERE [Some Column] = 'Target Data')
BEGIN
-- TRUE Procedure
END
ELSE BEGIN
-- FALSE Procedure
END
Install the extension "Code Runner". Check if you can compile your program with csc
(ex.: csc hello.cs
). The command csc
is shipped with Mono. Then add this to your VS Code user settings:
"code-runner.executorMap": {
"csharp": "echo '# calling mono\n' && cd $dir && csc /nologo $fileName && mono $dir$fileNameWithoutExt.exe",
// "csharp": "echo '# calling dotnet run\n' && dotnet run"
}
Open your C# file and use the execution key of Code Runner.
Edit: also added dotnet run
, so you can choose how you want to execute your program: with Mono, or with dotnet. If you choose dotnet, then first create the project (dotnet new console
, dotnet restore
).
You're trying to access a JSON, not JSONP.
Notice the difference between your source:
And actual JSONP (a wrapping function):
Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.
You can easily create your own serializer
var car = new Car() { Name = "Ford", Owner = "John Smith" };
string json = Serialize(car);
string Serialize<T>(T o)
{
var attr = o.GetType().GetCustomAttribute(typeof(JsonObjectAttribute)) as JsonObjectAttribute;
var jv = JValue.FromObject(o);
return new JObject(new JProperty(attr.Title, jv)).ToString();
}
is the character entity reference (meant to be easily parseable by humans). 
is the numeric entity reference (meant to be easily parseable by machines).They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.
You can read more about character entity references in the offical W3C documents.
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max
could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
I usually start mysql server by typing
$ mysql.server start
without sudo. But in error I type sudo before the command. Now I have to remove the error file to start the server.
$ sudo rm /usr/local/var/mysql/`hostname`.err
CentOS is Linux, so as in just about all other Unix/Linux systems, you have the find
command. To search for files within the current directory:
find -name "filename"
You can also have wildcards inside the quotes, and not just a strict filename. You can also explicitly specify a directory to start searching from as the first argument to find:
find / -name "filename"
will look for "filename" or all the files that match the regex expression in between the quotes, starting from the root directory. You can also use single quotes instead of double quotes, but in most cases you don't need either one, so the above commands will work without any quotes as well. Also, for example, if you're searching for java files and you know they are somewhere in your /home/username, do:
find /home/username -name *.java
There are many more options to the find command and you should do a:
man find
to learn more about it.
One more thing: if you start searching from / and are not root or are not sudo running the command, you might get warnings that you don't have permission to read certain directories. To ignore/remove those, do:
find / -name 'filename' 2>/dev/null
That just redirects the stderr to /dev/null.
Distance (km) = 10^((Free Space Path Loss – 92.45 – 20log10(f))/20)
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell setSelected:NO animated:NO];
[cell setHighlighted:NO animated:NO];
Happy coding !!!
encapsulation puts some things in a box and gives you a peephole; this keeps you from mucking with the gears.
abstraction flat-out ignores the details that don't matter, like whether the things have gears, ratchets, flywheels, or nuclear cores; they just "go"
examples of encapsulation:
examples of abstraction:
I had the same problem and thanks to this forum and some other found the answer. Initially I also thought of separate thread but it complicates the code a bit. So I tried to find an answer that aligns with my principle "elegance and simplicity".
Please have a look at such forum: https://sqa.stackexchange.com/questions/2606/what-is-seleniums-default-timeout-for-page-loading
#SOLUTION: In the code, before the line with 'get' method you can use for example:
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
#
One thing is that it throws timeoutException so you have to encapsulate it in the try catch block or wrap in some method.
I haven't found the getter for the pageLoadTimeout so I don't know what is the default value, but probably very high since my script was frozen for many hours and nothing moved forward.
#NOTICE: 'pageLoadTimeout' is NOT implemented for Chrome driver and thus causes exception. I saw by users comments that there are plans to make it.
I don't know, it works fine for me. Exact commands:
import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()
You should be able to choose the SQL Server Database file option to get the right kind of database (the system.data.SqlClient
provider), and then manually correct the connection string to point to your db.
I think the reasoning behind those db choices probably goes something like this:
However, this logic doesn't quite hold. Even if each of those 4 points is true 90% of the time, by the time you apply all four of them it only applies to ~65% of your audience, which means up to 35% of the express market might legitimately want to talk to a server-class db, and that's a significant group. And so, the simplified (greedy) version:
well I think the problem solved this below code works:
function sum() {
var result=0;
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
if (txtFirstNumberValue !="" && txtSecondNumberValue ==""){
result = parseInt(txtFirstNumberValue);
}else if(txtFirstNumberValue == "" && txtSecondNumberValue != ""){
result= parseInt(txtSecondNumberValue);
}else if (txtSecondNumberValue != "" && txtFirstNumberValue != ""){
result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
}
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
@MarcB mentioned that it is dirty to use regex to remove an url parameter. And yes it is, because it's not as easy as it looks:
$urls = array(
'example.com/?foo=bar',
'example.com/?bar=foo&foo=bar',
'example.com/?foo=bar&bar=foo',
);
echo 'Original' . PHP_EOL;
foreach ($urls as $url) {
echo $url . PHP_EOL;
}
echo PHP_EOL . '@AaronHathaway' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('#&?foo=[^&]*#', null, $url) . PHP_EOL;
}
echo PHP_EOL . '@SergeS' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace( "/&{2,}/", "&", preg_replace( "/foo=[^&]+/", "", $url)) . PHP_EOL;
}
echo PHP_EOL . '@Justin' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/([?&])foo=[^&]+(&|$)/', '$1', $url) . PHP_EOL;
}
echo PHP_EOL . '@kraftb' . PHP_EOL;
foreach ($urls as $url) {
echo preg_replace('/(&|\?)foo=[^&]*&/', '$1', preg_replace('/(&|\?)foo=[^&]*$/', '', $url)) . PHP_EOL;
}
echo PHP_EOL . 'My version' . PHP_EOL;
foreach ($urls as $url) {
echo str_replace('/&', '/?', preg_replace('#[&?]foo=[^&]*#', null, $url)) . PHP_EOL;
}
returns:
Original example.com/?foo=bar example.com/?bar=foo&foo=bar example.com/?foo=bar&bar=foo @AaronHathaway example.com/? example.com/?bar=foo example.com/?&bar=foo @SergeS example.com/? example.com/?bar=foo& example.com/?&bar=foo @Justin example.com/? example.com/?bar=foo& example.com/?bar=foo @kraftb example.com/ example.com/?bar=foo example.com/?bar=foo My version example.com/ example.com/?bar=foo example.com/?bar=foo
As you can see only @kraftb posted a correct answer using regex and my version is a little bit smaller.
You can achieve this using different ways but with different performance,
1. Using bracket notation:
var str = "Test";
var lastLetter = str[str.length - 1];
But it's not recommended to use brackets. Check the reasons here
2. charAt[index]:
var lastLetter = str.charAt(str.length - 1)
This is readable and fastest among others. It is most recommended way.
3. substring:
str.substring(str.length - 1);
4. slice:
str.slice(-1);
It's slightly faster than substring.
You can check the performance here
With ES6:
You can use str.endsWith("t");
But it is not supported in IE. Check more details about endsWith here
library(plyr)
ddply(data, .(MONTH-YEAR), nrow)
This will give you the answer, if "MONTH-YEAR" is a variable. First, try unique(data$MONTH-YEAR) and see if it returns unique values (no duplicates).
Then above simple split-apply-combine will return what you are looking for.
Also $( "#container" ).find( "div.robotarm" );
is equal to: $( "div.robotarm", "#container" )
Refining upon the answers found here I came up with the following:
getCurrentScript.js
var getCurrentScript = function () {
if (document.currentScript) {
return document.currentScript.src;
} else {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length-1].src;
}
};
module.exports = getCurrentScript;
getCurrentScriptPath.js
var getCurrentScript = require('./getCurrentScript');
var getCurrentScriptPath = function () {
var script = getCurrentScript();
var path = script.substring(0, script.lastIndexOf('/'));
return path;
};
module.exports = getCurrentScriptPath;
BTW: I'm using CommonJS module format and bundling with webpack.
Using sed:
T=$(printf "\t")
sed "s/[[:blank:]]\+/$T/g"
or
sed "s/[[:space:]]\+/$T/g"
You can do the following
Reload
It will add a reload button on your right hand at the bottom of the vs code.
"How do I for example read a 3 bit integer value starting at the second bit?"
int number = // whatever;
uint8_t val; // uint8_t is the smallest data type capable of holding 3 bits
val = (number & (1 << 2 | 1 << 3 | 1 << 4)) >> 2;
(I assumed that "second bit" is bit #2, i. e. the third bit really.)
Try this:
var extension = fileString.substring(fileString.lastIndexOf('.') + 1);
Using CSS only, no. You need to use jQuery to add it.
Click the left side dropdown menu "android" and choose "project" to see libs folders
*after choosing project you will see the libs directory
check this out, works on firefox and IE
<style>
html, body
{
height: 100%;
}
.content
{
min-height: 100%;
}
.footer
{
position: relative;
clear: both;
}
</style>
<body>
<div class="content">Page content
</div>
<div class="footer">this is my footer
</div>
</body>
If you're using jQuery, use .data()
:
div.data('myval', 20);
You can store arbitrary data with .data()
, but you're restricted to just strings when using .attr()
.
For mocking static functions i was able to do it that way:
wrapper code snippet (not really functional, just for illustration)
class myWrapperClass ...
def myWrapperFunction (...) {
return theOriginalFunction (...)
}
of course having multiple such functions accumulated in a single wrapper class might be beneficial in terms of code reuse.
I spent over 5 hours trying to get rid of this message under Windows 8.1. So I would like to share my case and save someones time. I was not behind the proxy... but setting proxy helped to resolve the problem. So I go deep and found that issue was caused by Comodo Firewall... which blocked cmd since I was installing packages too fast (turning off and even closing Firewall did not help, which caused me so long to find the issue... seems like there was some other process of Firewall running in background). You may have same issue with any other firewall/antivirus installed so make sure that cmd is not blocked by them. Good luck!
The below regex will help to validate hh:mm format
^([0-1][0-9]|2[0-3]):[0-5][0-9]$
#!/path/to/R
won't work because R is itself a script, so execve
is unhappy.
I use R --slave -f script
To refer to a set variable in command line you would need to use %a%
so for example:
set a=100
echo %a%
rem output = 100
Note: This works for Windows 7 pro.
short answer, partial
gives default values to the parameters of a function that would otherwise not have default values.
from functools import partial
def foo(a,b):
return a+b
bar = partial(foo, a=1) # equivalent to: foo(a=1, b)
bar(b=10)
#11 = 1+10
bar(a=101, b=10)
#111=101+10
line=$((${RANDOM} % $(wc -l < /etc/passwd)))
sed -n "${line}p" /etc/passwd
just with your file instead.
In this example I used the file /etc/password, using the special variable ${RANDOM}
(about which I learned here), and the sed
expression you had, only difference is that I am using double quotes instead of single to allow the variable expansion.
✗
✗
✘
✘
✕
✕
✖
✖
Different ways to create a Rounded button are as follows
FlatButton Button with Shape RoundedRectangleBorder
FlatButton(
minWidth: 260,
height: 60,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(18.0),
side: BorderSide(color: Colors.red)),
color: Colors.white,
textColor: Colors.red,
padding: EdgeInsets.all(8.0),
onPressed: () {},
child: Text(
"Add to Cart".toUpperCase(),
style: TextStyle(
fontSize: 14.0,
),
),
),
RaisedButton Button with Shape RoundedRectangleBorder
RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(28.0),
side: BorderSide(color: Colors.red)),
onPressed: () {},
color: Colors.red,
textColor: Colors.white,
child: Text("Buy now".toUpperCase(),
style: TextStyle(fontSize: 14)),
),
RaisedButton Button with Shape StadiumBorder()
RaisedButton(
padding:
EdgeInsets.only(left: 100, right: 100, top: 20, bottom: 20),
shape: StadiumBorder(),
onPressed: () {},
child: Text("Button"),
)
RaisedButton Button with ClipRRect
ClipRRect(
borderRadius: BorderRadius.circular(40),
child: RaisedButton(
padding: EdgeInsets.only(
left: 100, right: 100, top: 20, bottom: 20),
onPressed: () {},
child: Text("Button"),
),
)
RaisedButton Button with ClipOval
ClipOval(
child: RaisedButton(
onPressed: () {},
child: Text("Button"),
),
),
RaisedButton Button with ButtonTheme
ButtonTheme(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20)),
child: RaisedButton(
onPressed: () {},
child: Text("Button"),
),
)
practical demonstration of a round button can be found in below dartpad link
if none of the above is working you can use this->
idAssignedToEntryWidget.delete(first = 0, last = UpperLimitAssignedToEntryWidget)
for e.g. ->
id assigned is = en then
en.delete(first =0, last =100)
From remote repo:
svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/
Remove the line:
('com.android.support:support-v4:22.0.0')
From dependencies (in build.gradle
):
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:support-v4:22.0.0'
}
SELECT date_created
FROM your_table
WHERE DATENAME(dw, date_created) NOT IN ('Saturday', 'Sunday')
The following is equivalent to your second code block:
var f = function () {
//Some logic here...
};
var fr = f;
fr(pars);
If you want to actually pass a reference to a function to some other function, you can do something like this:
function fiz(x, y, z) {
return x + y + z;
}
// elsewhere...
function foo(fn, p, q, r) {
return function () {
return fn(p, q, r);
}
}
// finally...
f = foo(fiz, 1, 2, 3);
f(); // returns 6
You're almost certainly better off using a framework for this sort of thing, though.
I think cURL would be a good solution. This is not tested, but you can try something like this:
$body = '{
"kind": "blogger#post",
"blog": {
"id": "8070105920543249955"
},
"title": "A new post",
"content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);
You can return to the same existing instance of Activity with
android:launchMode="singleInstance"
in the manifest.
When you return to A
from B
, may be needed finish()
to destroy B
.
I tried some of the script here, but they didn't work for me, as I have my tables in schemas. So I put together the following. Note that this script takes a list of schemas, and drops then in sequence. You need to make sure that you have a complete ordering in your schemas. If there are any circular dependencies, then it will fail.
PRINT 'Dropping whole database'
GO
------------------------------------------
-- Drop constraints
------------------------------------------
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT DISTINCT sql = 'ALTER TABLE ['+tc2.CONSTRAINT_SCHEMA+'].[' + tc2.TABLE_NAME + '] DROP [' + rc1.CONSTRAINT_NAME + ']'
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc1
LEFT JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc2 ON tc2.CONSTRAINT_NAME =rc1.CONSTRAINT_NAME
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
Exec (@Sql)
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
------------------------------------------
-- Drop views
------------------------------------------
DECLARE @sql VARCHAR(MAX) = ''
, @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT @sql = @sql + 'DROP VIEW ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME(v.name) +';' + @crlf
FROM sys.views v
PRINT @sql;
EXEC(@sql);
GO
------------------------------------------
-- Drop procs
------------------------------------------
PRINT 'Dropping all procs ...'
GO
DECLARE @sql VARCHAR(MAX) = ''
, @crlf VARCHAR(2) = CHAR(13) + CHAR(10) ;
SELECT @sql = @sql + 'DROP PROC ' + QUOTENAME(SCHEMA_NAME(p.schema_id)) + '.' + QUOTENAME(p.name) +';' + @crlf
FROM [sys].[procedures] p
PRINT @sql;
EXEC(@sql);
GO
------------------------------------------
-- Drop tables
------------------------------------------
PRINT 'Dropping all tables ...'
GO
EXEC sp_MSForEachTable 'DROP TABLE ?'
GO
------------------------------------------
-- Drop sequences
------------------------------------------
PRINT 'Dropping all sequences ...'
GO
DECLARE @DropSeqSql varchar(1024)
DECLARE DropSeqCursor CURSOR FOR
SELECT DISTINCT 'DROP SEQUENCE ' + s.SEQUENCE_SCHEMA + '.' + s.SEQUENCE_NAME
FROM INFORMATION_SCHEMA.SEQUENCES s
OPEN DropSeqCursor
FETCH NEXT FROM DropSeqCursor INTO @DropSeqSql
WHILE ( @@FETCH_STATUS <> -1 )
BEGIN
PRINT @DropSeqSql
EXECUTE( @DropSeqSql )
FETCH NEXT FROM DropSeqCursor INTO @DropSeqSql
END
CLOSE DropSeqCursor
DEALLOCATE DropSeqCursor
GO
------------------------------------------
-- Drop Schemas
------------------------------------------
DECLARE @schemas as varchar(1000) = 'StaticData,Ird,DataImport,Collateral,Report,Cds,CommonTrade,MarketData,TypeCode'
DECLARE @schemasXml as xml = cast(('<schema>'+replace(@schemas,',' ,'</schema><schema>')+'</schema>') as xml)
DECLARE @Sql NVARCHAR(500) DECLARE @Cursor CURSOR
SET @Cursor = CURSOR FAST_FORWARD FOR
SELECT sql = 'DROP SCHEMA ['+schemaName+']' FROM
(SELECT CAST(T.schemaName.query('text()') as VARCHAR(200)) as schemaName FROM @schemasXml.nodes('/schema') T(schemaName)) as X
JOIN information_schema.schemata S on S.schema_name = X.schemaName
OPEN @Cursor FETCH NEXT FROM @Cursor INTO @Sql
WHILE (@@FETCH_STATUS = 0)
BEGIN
PRINT @Sql
Exec (@Sql)
FETCH NEXT FROM @Cursor INTO @Sql
END
CLOSE @Cursor DEALLOCATE @Cursor
GO
I don't remember in which version of ASP.NET MVC (ASP.NET MVC 3+ I believe) / Razor the parameterlabeldeclaration or whatever it's called (parameter: x) feature was introduced, but to me this is definitely the proper way to build a link with an anchor in ASP.NET MVC.
@Html.ActionLink("Some link text", "MyAction", "MyController", protocol: null, hostName: null, fragment: "MyAnchor", routeValues: null, htmlAttributes: null)
Not even Ed Blackburns antipattern argument from this answer can compete with that.
this may work for you :
document.addEventListener('DOMContentLoaded', function() {
// your code here
}, false);
or if your comfort with jquery,
$(document).ready(function(){
// your code
});
$(document).ready()
fires on DOMContentLoaded, but this event is not being fired consistently among browsers. This is why jQuery will most probably implement some heavy workarounds to support all the browsers. And this will make it very difficult to "exactly" simulate the behavior using plain Javascript (but not impossible of course).
as Jeffrey Sweeney and J Torres suggested, i think its better to have a setTimeout
function, before firing the function like below :
setTimeout(function(){
//your code here
}, 3000);
From the Oracle documentation page about multiple inheritance type,we can find the accurate answer here. Here we should first know the type of multiple inheritance in java:-
Java "doesn't support the multiple inheritance of state, but it support multiple inheritance of implementation with default methods since java 8 release and multiple inheritance of type with interfaces.
Then here the question arises for "diamond problem" and how Java deal with that:-
In case of multiple inheritance of implementation java compiler gives compilation error and asks the user to fix it by specifying the interface name. Example here:-
interface A {
void method();
}
interface B extends A {
@Override
default void method() {
System.out.println("B");
}
}
interface C extends A {
@Override
default void method() {
System.out.println("C");
}
}
interface D extends B, C {
}
So here we will get error as:- interface D inherits unrelated defaults for method() from types B and C interface D extends B, C
You can fix it like:-
interface D extends B, C {
@Override
default void method() {
B.super.method();
}
}
In Conclusion we can say that java doesn't support multiple inheritance of state but it does support multiple inheritance of implementation and multiple inheritance of type.
The explicit
-keyword can be used to enforce a constructor to be called explicitly.
class C{
public:
explicit C(void) = default;
};
int main(void){
C c();
return 0;
}
the explicit
-keyword in front of the constructor C(void)
tells the compiler that only explicit call to this constructor is allowed.
The explicit
-keyword can also be used in user-defined type cast operators:
class C{
public:
explicit inline operator bool(void) const{
return true;
}
};
int main(void){
C c;
bool b = static_cast<bool>(c);
return 0;
}
Here, explicit
-keyword enforces only explicit casts to be valid, so bool b = c;
would be an invalid cast in this case. In situations like these explicit
-keyword can help programmer to avoid implicit, unintended casts. This usage has been standardized in C++11.
Similar to my answer here: Linux shell scripting: hex number to binary string
You can do it with the same tool like this (using ascii printable character instead of 5a
):
echo -n 616263 | cryptocli dd -decoders hex
Will produce the following result:
abcd
here's a in-space rotate method, by java, only for square. for non-square 2d array, you will have to create new array anyway.
private void rotateInSpace(int[][] arr) {
int z = arr.length;
for (int i = 0; i < z / 2; i++) {
for (int j = 0; j < (z / 2 + z % 2); j++) {
int x = i, y = j;
int temp = arr[x][y];
for (int k = 0; k < 4; k++) {
int temptemp = arr[y][z - x - 1];
arr[y][z - x - 1] = temp;
temp = temptemp;
int tempX = y;
y = z - x - 1;
x = tempX;
}
}
}
}
code to rotate any size 2d array by creating new array:
private int[][] rotate(int[][] arr) {
int width = arr[0].length;
int depth = arr.length;
int[][] re = new int[width][depth];
for (int i = 0; i < depth; i++) {
for (int j = 0; j < width; j++) {
re[j][depth - i - 1] = arr[i][j];
}
}
return re;
}
(TO_DATE(:P_comapre_date_1, 'dd-mm-yyyy hh24:mi') - TO_DATE(:P_comapre_date_2, 'dd-mm-yyyy hh24:mi'))*60*60*24 sum_seconds,
(TO_DATE(:P_comapre_date_1, 'dd-mm-yyyy hh24:mi') - TO_DATE(:P_comapre_date_2, 'dd-mm-yyyy hh24:mi'))*60*24 sum_minutes,
(TO_DATE(:P_comapre_date_1, 'dd-mm-yyyy hh24:mi') - TO_DATE(:P_comapre_date_2, 'dd-mm-yyyy hh24:mi'))*24 sum_hours,
(TO_DATE(:P_comapre_date_1, 'dd-mm-yyyy hh24:mi') - TO_DATE(:P_comapre_date_2, 'dd-mm-yyyy hh24:mi')) sum_days
Alternatively, you can just do:
import matplotlib as mpl
label_size = 8
mpl.rcParams['xtick.labelsize'] = label_size
Answers so far haven't addressed the "entire stream" part of the question. I think the good way to do this is ioutil.ReadAll
. With your io.ReaderCloser
named rc
, I would write,
Go >= v1.16
if b, err := io.ReadAll(rc); err == nil {
return string(b)
} ...
Go <= v1.15
if b, err := ioutil.ReadAll(rc); err == nil {
return string(b)
} ...
In JDK 8 source can be found in /src.zip. Now in some intermediate releases this zip was missing but again it is available.
make sure that you select source as well from installation wizard.
For an iBeacon with ProximityUUID E2C56DB5-DFFB-48D2-B060-D0F5A71096E0
, major 0
, minor 0
, and calibrated Tx Power of -59
RSSI, the transmitted BLE advertisement packet looks like this:
d6 be 89 8e 40 24 05 a2 17 6e 3d 71 02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 52 ab 8d 38 a5
This packet can be broken down as follows:
d6 be 89 8e # Access address for advertising data (this is always the same fixed value)
40 # Advertising Channel PDU Header byte 0. Contains: (type = 0), (tx add = 1), (rx add = 0)
24 # Advertising Channel PDU Header byte 1. Contains: (length = total bytes of the advertising payload + 6 bytes for the BLE mac address.)
05 a2 17 6e 3d 71 # Bluetooth Mac address (note this is a spoofed address)
02 01 1a 1a ff 4c 00 02 15 e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 00 00 00 00 c5 # Bluetooth advertisement
52 ab 8d 38 a5 # checksum
The key part of that packet is the Bluetooth Advertisement, which can be broken down like this:
02 # Number of bytes that follow in first AD structure
01 # Flags AD type
1A # Flags value 0x1A = 000011010
bit 0 (OFF) LE Limited Discoverable Mode
bit 1 (ON) LE General Discoverable Mode
bit 2 (OFF) BR/EDR Not Supported
bit 3 (ON) Simultaneous LE and BR/EDR to Same Device Capable (controller)
bit 4 (ON) Simultaneous LE and BR/EDR to Same Device Capable (Host)
1A # Number of bytes that follow in second (and last) AD structure
FF # Manufacturer specific data AD type
4C 00 # Company identifier code (0x004C == Apple)
02 # Byte 0 of iBeacon advertisement indicator
15 # Byte 1 of iBeacon advertisement indicator
e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon proximity uuid
00 00 # major
00 00 # minor
c5 # The 2's complement of the calibrated Tx Power
Any Bluetooth LE device that can be configured to send a specific advertisement can generate the above packet. I have configured a Linux computer using Bluez to send this advertisement, and iOS7 devices running Apple's AirLocate test code pick it up as an iBeacon with the fields specified above. See: Use BlueZ Stack As A Peripheral (Advertiser)
This blog has full details about the reverse engineering process.
Simply removing libstdc++-6.dll.a \ libstdc++.dll.a from the mingw directory fixes this.
I tried using the flag -static-libstdc++ but this did not work for me. I found the solution in: http://ghc.haskell.org/trac/ghc/ticket/4468#
For those who use Postgre 9.5+(I believe most of you do), there is a quite simple and clean solution
ALTER TABLE if exists <tablename> add if not exists <columnname> <columntype>
I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:
width: 100%
I had to add the CSS class into the asp:DropDownList element
You can use this(more efficient) too. (https://softwareengineering.stackexchange.com/questions/304445/why-is-s-better-than-for-concatenation)
s += "%s" %(stringfromelsewhere)
The component type of containers like vectors must be assignable. References are not assignable (you can only initialize them once when they are declared, and you cannot make them reference something else later). Other non-assignable types are also not allowed as components of containers, e.g. vector<const int>
is not allowed.
To pass get variables as well use $args
:
location / {
try_files $uri $uri/ /index.php?$args;
}
From MSDN:
Top-level types, which are not nested in other types, can only have internal
or public
accessibility. The default accessibility for these types is internal
.
Source: Accessibility Levels (C# Reference) (December 6th, 2017)
If you have a built-in command of GridView like insert, update or delete, on row command you can use the following code to get the index:
int index = Convert.ToInt32(e.CommandArgument);
In a custom command, you can set the command argument to yourRow.RowIndex.ToString()
and then get it back in the RowCommand event handler. Unless, of course, you need the command argument for another purpose.
Be careful of difference between 'c'
and "c"
'c'
is a char suitable for formatting with %c
"c"
is a char* pointing to a memory block with a length of 2 (with the null terminator).
$("#DDLID").val( $("#DDLID option:first-child").val() );
select max(Emp_Sal)
from Employee a
where 1 = ( select count(*)
from Employee b
where b.Emp_Sal > a.Emp_Sal)
Yes running man.
We could do it with jQuery:
$(window).resize(function(){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
});
Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when the scope is destroyed. If you don't do this, everytime when the scope is recreated (the controller is rerun), there will be 1 more handler added causing unexpected behavior and leaking.
In this case, you may need to identify your attached handler:
$(window).on("resize.doResize", function (){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
});
$scope.$on("$destroy",function (){
$(window).off("resize.doResize"); //remove the handler added earlier
});
In this example, I'm using event namespace from jQuery. You could do it differently according to your requirements.
Improvement: If your event handler takes a bit long time to process, to avoid the problem that the user may keep resizing the window, causing the event handlers to be run many times, we could consider throttling the function. If you use underscore, you can try:
$(window).on("resize.doResize", _.throttle(function (){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
},100));
or debouncing the function:
$(window).on("resize.doResize", _.debounce(function (){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
},100));
or this example, just to make it more visible:
public class CustomerListList : List<CustomerList> { }
public class CustomerList : List<Customer> { }
public class Customer
{
public int ID { get; set; }
public string SomethingWithText { get; set; }
}
and you can keep it going. to the infinity and beyond !
There are lots of explanation of Jmeter Summary, I have been using this tool from quite some time for generating performance testing report with relevant data. The explanation available on below link is right from the field experience:
Jmeter:Understanding Summary Report
This is one of the most useful report generated by Jmeter to undertstand the load test result.
# Label: Name of HTTP sample request send to server
# Samples : This Captures the total number of samples pushed to server. Suppose you put a Loop Controller to run it 5 times this particular request and then 2 iteration(Called Loop Count in Thread Group)is set and load test is run for 100 users, then the count that will be displayed here .... 1*5*2 * 100 =1000. Total = total number of samples send to server during entire run.
# Average : It's an average response time for a particular http request. This response time is in millisecond, and an average for 5 loops in two iteration for 100 users. Total = Average of total average of samples, means add all averages for all samples and divide by number of samples
# Min : Minmum time spend by sample requests send for this label. The total equals to the minimum time across all samples.
# Max : Maximum tie spend by sample requests send for this label The total equals to the maxmimum time across all samples.
# Std. Dev. : Knowing the standard deviation of your data set tells you how densely the data points are clustered around the mean. The smaller the standard deviation, the more consistent the data. Standard deviation should be less than or equal to half of the average time for a label. If it is more than that, then it means that something is wrong. you need to figure out the problem and fix it. https://en.wikipedia.org/wiki/Standard_deviation Total is euqals to highest deviation across all samples.
# Error: Total percentage of erros found for a particular sample request. 0.0% shows that all requests completed successfully. Total equals to percentage of errors samples in all samples (Total Samples)
# Throughput: Hits/sec, or total number of request per unit of time(sec, mins, hr) send to server during test.
endTime = lastSampleStartTime + lastSampleLoadTime startTime = firstSampleStartTime converstion = unit time conversion value Throughput = Numrequests / ((endTime - startTime)*conversion)
# KB/sec : Its mesuring throughput rate in Kilobytes per second.
# Avg. Bytes: Avegare of total bytes of data downloaded from server. Totals is average bytes across all samples.
This exception may also occur if you are using Socket
s on one side and SSLSocket
s on the other. Consistency is important.
You would use aggregate function MAX and GROUP BY
SELECT username, MAX(date), value FROM tablename GROUP BY username, value
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
On the Server, to Serialize/Deserialize json to custom objects:
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
Microsoft Office has 'InfoPath', which takes an XSD as an import and lets you quickly and easily define a form-based editor for creating XML files. It has two modes - one where you define the form, and another mode where you create the XML file by filling out the form. I believe it first came with Office 2003, and most people never install it. It shocks me at how much I like it.
pyspark version:
df = <source data>
df.printSchema()
from pyspark.sql.types import *
# Change column type
df_new = df.withColumn("myColumn", df["myColumn"].cast(IntegerType()))
df_new.printSchema()
df_new.select("myColumn").show()
I know it's not exactly what you're asking, but, for replacing a comma with a newline, this works great:
tr , '\n' < file
Another alternative:
:call cursor('.',strwidth(getline('.')))
This is may be useful if you're writing a function. Another situation would be when I need to open a specific template and jump to end of first line, I can do:
vi +"call cursor('.',strwidth(getline(1)))" notetaking_template.txt
The above could also be done with
vi +"execute ':normal! $'" notetaking_template.txt
See also:
On declaration you can do the following.
float[] values = {0.1f, 0.2f, 0.3f};
When the field is already defined, try this.
values = new float[] {0.1f, 0.2f, 0.3f};
Be aware that also the second version creates a new array.
If values
was the only reference to an already existing field, it becomes eligible for garbage collection.
If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount
property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).
If you cannot find it this way, try the menu: View/Properties Window.
Or try the F4 key.
result = initial number + (6 - initial number % 6)
updated from Mojave to Big Sur and got the same error : the command
xcode-select --install
worked like a charm
If you want to see the changes including the # of lines that changed between your branch and another branch,
git diff the_other_branch_name --stat
You could also delegate
like so...
ThreadStart ts = delegate
{
bool moreWork = DoWork("param1", "param2", "param3");
if (moreWork)
{
DoMoreWork("param1", "param2");
}
};
new Thread(ts).Start();
A couple things I think you could try:
Put the literal value of the version in the child pom
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
<scope>runtime</scope>
</dependency>
Clear your .m2 cache normally located C:\Users\user.m2\repository. I would say I do this pretty frequently when I'm working in maven. Especially before committing so that I can be more confident CI will run. You don't have to nuke the folder every time, sometimes just your project packages and the .cache folder are enough.
Add a relativePath tag to your parent pom declaration
<parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
It looks like you have 8 total errors in your poms. I would try to get some basic compilation running before adding the parent pom and properties.
You should use npm run-script build
or npm build <project_folder>
. More info here: https://docs.npmjs.com/cli/build.
To declare an array of ArrayLists statically for, say, sprite positions as Points:
ArrayList<Point>[] positionList = new ArrayList[2];
public Main(---) {
positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
positionList[1] = new ArrayList<Point>();
}
dynamically:
ArrayList<Point>[] positionList;
int numberOfLists;
public Main(---) {
numberOfLists = 2;
positionList = new ArrayList[numberOfLists];
for(int i = 0; i < numberOfLists; i++) {
positionList[i] = new ArrayList<Point>();
}
}
Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.
Spinlock and Mutex synchronization mechanisms are very common today to be seen.
Let's think about Spinlock first.
Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?
Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:
In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)
In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).
Your last for
statement is missing a body.
Python expects an indented block to follow the line with the for, or to have content after the colon.
The first style is more common, so it says it expects some indented code to follow it. You have an elif
at the same indent level.
What if you've got array of fieldsets?
<fieldset>
<input type="text" name="item[1]" />
<input type="text" name="item[2]" />
<input type="hidden" name="fset[]"/>
</fieldset>
<fieldset>
<input type="text" name="item[3]" />
<input type="text" name="item[4]" />
<input type="hidden" name="fset[]"/>
</fieldset>
I added a hidden field to count the number of the fieldsets. The user can add or delete the fields and then save it.
Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
You will have to alter the collation type to utf8_unicode_ci
and the problem will be fixed.
mingw32 exists as a package for Linux. You can cross-compile and -link Windows applications with it. There's a tutorial here at the Code::Blocks forum. Mind that the command changes to x86_64-w64-mingw32-gcc-win32
, for example.
Ubuntu, for example, has MinGW in its repositories:
$ apt-cache search mingw
[...]
g++-mingw-w64 - GNU C++ compiler for MinGW-w64
gcc-mingw-w64 - GNU C compiler for MinGW-w64
mingw-w64 - Development environment targeting 32- and 64-bit Windows
[...]
If you really want to prune your history of .gitignore
d files, first save .gitignore
outside the repo, e.g. as /tmp/.gitignore
, then run
git filter-branch --force --index-filter \
"git ls-files -i -X /tmp/.gitignore | xargs -r git rm --cached --ignore-unmatch -rf" \
--prune-empty --tag-name-filter cat -- --all
Notes:
git filter-branch --index-filter
runs in the .git
directory I think, i.e. if you want to use a relative path you have to prepend one more ../
first. And apparently you cannot use ../.gitignore
, the actual .gitignore
file, that yields a "fatal: cannot use ../.gitignore as an exclude file" for some reason (maybe during a git filter-branch --index-filter
the working directory is (considered) empty?)git ls-files -iX <(git show $(git hash-object -w .gitignore))
instead to avoid copying .gitignore
somewhere else, but that alone already returns an empty string (whereas cat <(git show $(git hash-object -w .gitignore))
indeed prints .gitignore
's contents as expected), so I cannot use <(git show $GITIGNORE_HASH)
in git filter-branch
....gitignore
-clean a specific branch, replace --all
in the last line with its name. The --tag-name-filter cat
might not work properly then, i.e. you'll probably not be able to directly transfer a single branch's tags properlyTry to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.
List<string> L = new List<string> ( new string[10] );
You are getting AttributeError
because you're calling groups
on None
, which hasn't any methods.
regex.search
returning None
means the regex couldn't find anything matching the pattern from supplied string.
when using regex, it is nice to check whether a match has been made:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
changing:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: 100%;
}
to:
.ui-menu .ui-menu-item {
margin: 0;
padding: 0;
zoom: 1;
width: auto;
float:left;
}
should start you off.
In Chrome, window.onload is different from <body onload="">
, whereas they are the same in both Firefox(version 35.0) and IE (version 11).
You could explore that by the following snippet:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--import css here-->
<!--import js scripts here-->
<script language="javascript">
function bodyOnloadHandler() {
console.log("body onload");
}
window.onload = function(e) {
console.log("window loaded");
};
</script>
</head>
<body onload="bodyOnloadHandler()">
Page contents go here.
</body>
</html>
And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()
" in the consoles of IE & FF, you will see:
"function onload(event) { bodyOnloadHandler() }"
which means that the assignment "window.onload = function(e)..." is overwritten.
Use the quotemeta
function:
$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";
print "wee" if ($text_to_search =~ /$search_string/);
I've had this problem too, I had just forgotten to type workon myproject in the terminal before executing my program.
Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:
seems ok... though I'd think a rudimentary indication of success/failure/time posted/# bytes received/etc. would be preferable.
edit: I was thinking along the lines of data integrity and/or record-keeping; metadata such as an MD5 hash or timestamp for time received may be helpful for large datafiles.
<div>{{modal.title | slice: 0: 20}}</div>
By 'the same' I mean that there are is no item in array1 that is not contained in array2.
You could use flatten() and difference() for this, which works well if you don't care if there are items in array2
that aren't in array1
. It sounds like you're asking is array1 a subset of array2?
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
function isSubset(source, target) {
return !_.difference(_.flatten(source), _.flatten(target)).length;
}
isSubset(array1, array2); // ? true
array1.push('d');
isSubset(array1, array2); // ? false
isSubset(array2, array1); // ? true
Hmm, you could also just make a 1 pixel wide line with a length of 1 pixel and make it's direction move along a single axis.
ctx.beginPath();
ctx.lineWidth = 1; // one pixel wide
ctx.strokeStyle = rgba(...);
ctx.moveTo(50,25); // positioned at 50,25
ctx.lineTo(51,25); // one pixel long
ctx.stroke();
Here is a solution written in golang. The method is similar to some other answers posted here, but not quite the same. It is easy to implement, and has been tested. Here are the steps:
The values for A, B, and C for the quadratic are derived here, where (n-et) and (m-dt) are the equations for the line's x and y coordinates, respectively. r is the radius of the circle.
(n-et)(n-et) + (m-dt)(m-dt) = rr
nn - 2etn + etet + mm - 2mdt + dtdt = rr
(ee+dd)tt - 2(en + dm)t + nn + mm - rr = 0
Therefore A = ee+dd, B = - 2(en + dm), and C = nn + mm - rr.
Here is the golang code for the function:
package geom
import (
"math"
)
// SegmentCircleIntersection return points of intersection between a circle and
// a line segment. The Boolean intersects returns true if one or
// more solutions exist. If only one solution exists,
// x1 == x2 and y1 == y2.
// s1x and s1y are coordinates for one end point of the segment, and
// s2x and s2y are coordinates for the other end of the segment.
// cx and cy are the coordinates of the center of the circle and
// r is the radius of the circle.
func SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r float64) (x1, y1, x2, y2 float64, intersects bool) {
// (n-et) and (m-dt) are expressions for the x and y coordinates
// of a parameterized line in coordinates whose origin is the
// center of the circle.
// When t = 0, (n-et) == s1x - cx and (m-dt) == s1y - cy
// When t = 1, (n-et) == s2x - cx and (m-dt) == s2y - cy.
n := s2x - cx
m := s2y - cy
e := s2x - s1x
d := s2y - s1y
// lineFunc checks if the t parameter is in the segment and if so
// calculates the line point in the unshifted coordinates (adds back
// cx and cy.
lineFunc := func(t float64) (x, y float64, inBounds bool) {
inBounds = t >= 0 && t <= 1 // Check bounds on closed segment
// To check bounds for an open segment use t > 0 && t < 1
if inBounds { // Calc coords for point in segment
x = n - e*t + cx
y = m - d*t + cy
}
return
}
// Since we want the points on the line distance r from the origin,
// (n-et)(n-et) + (m-dt)(m-dt) = rr.
// Expanding and collecting terms yeilds the following quadratic equation:
A, B, C := e*e+d*d, -2*(e*n+m*d), n*n+m*m-r*r
D := B*B - 4*A*C // discriminant of quadratic
if D < 0 {
return // No solution
}
D = math.Sqrt(D)
var p1In, p2In bool
x1, y1, p1In = lineFunc((-B + D) / (2 * A)) // First root
if D == 0.0 {
intersects = p1In
x2, y2 = x1, y1
return // Only possible solution, quadratic has one root.
}
x2, y2, p2In = lineFunc((-B - D) / (2 * A)) // Second root
intersects = p1In || p2In
if p1In == false { // Only x2, y2 may be valid solutions
x1, y1 = x2, y2
} else if p2In == false { // Only x1, y1 are valid solutions
x2, y2 = x1, y1
}
return
}
I tested it with this function, which confirms that solution points are within the line segment and on the circle. It makes a test segment and sweeps it around the given circle:
package geom_test
import (
"testing"
. "**put your package path here**"
)
func CheckEpsilon(t *testing.T, v, epsilon float64, message string) {
if v > epsilon || v < -epsilon {
t.Error(message, v, epsilon)
t.FailNow()
}
}
func TestSegmentCircleIntersection(t *testing.T) {
epsilon := 1e-10 // Something smallish
x1, y1 := 5.0, 2.0 // segment end point 1
x2, y2 := 50.0, 30.0 // segment end point 2
cx, cy := 100.0, 90.0 // center of circle
r := 80.0
segx, segy := x2-x1, y2-y1
testCntr, solutionCntr := 0, 0
for i := -100; i < 100; i++ {
for j := -100; j < 100; j++ {
testCntr++
s1x, s2x := x1+float64(i), x2+float64(i)
s1y, s2y := y1+float64(j), y2+float64(j)
sc1x, sc1y := s1x-cx, s1y-cy
seg1Inside := sc1x*sc1x+sc1y*sc1y < r*r
sc2x, sc2y := s2x-cx, s2y-cy
seg2Inside := sc2x*sc2x+sc2y*sc2y < r*r
p1x, p1y, p2x, p2y, intersects := SegmentCircleIntersection(s1x, s1y, s2x, s2y, cx, cy, r)
if intersects {
solutionCntr++
//Check if points are on circle
c1x, c1y := p1x-cx, p1y-cy
deltaLen1 := (c1x*c1x + c1y*c1y) - r*r
CheckEpsilon(t, deltaLen1, epsilon, "p1 not on circle")
c2x, c2y := p2x-cx, p2y-cy
deltaLen2 := (c2x*c2x + c2y*c2y) - r*r
CheckEpsilon(t, deltaLen2, epsilon, "p2 not on circle")
// Check if points are on the line through the line segment
// "cross product" of vector from a segment point to the point
// and the vector for the segment should be near zero
vp1x, vp1y := p1x-s1x, p1y-s1y
crossProd1 := vp1x*segy - vp1y*segx
CheckEpsilon(t, crossProd1, epsilon, "p1 not on line ")
vp2x, vp2y := p2x-s1x, p2y-s1y
crossProd2 := vp2x*segy - vp2y*segx
CheckEpsilon(t, crossProd2, epsilon, "p2 not on line ")
// Check if point is between points s1 and s2 on line
// This means the sign of the dot prod of the segment vector
// and point to segment end point vectors are opposite for
// either end.
wp1x, wp1y := p1x-s2x, p1y-s2y
dp1v := vp1x*segx + vp1y*segy
dp1w := wp1x*segx + wp1y*segy
if (dp1v < 0 && dp1w < 0) || (dp1v > 0 && dp1w > 0) {
t.Error("point not contained in segment ", dp1v, dp1w)
t.FailNow()
}
wp2x, wp2y := p2x-s2x, p2y-s2y
dp2v := vp2x*segx + vp2y*segy
dp2w := wp2x*segx + wp2y*segy
if (dp2v < 0 && dp2w < 0) || (dp2v > 0 && dp2w > 0) {
t.Error("point not contained in segment ", dp2v, dp2w)
t.FailNow()
}
if s1x == s2x && s2y == s1y { //Only one solution
// Test that one end of the segment is withing the radius of the circle
// and one is not
if seg1Inside && seg2Inside {
t.Error("Only one solution but both line segment ends inside")
t.FailNow()
}
if !seg1Inside && !seg2Inside {
t.Error("Only one solution but both line segment ends outside")
t.FailNow()
}
}
} else { // No intersection, check if both points outside or inside
if (seg1Inside && !seg2Inside) || (!seg1Inside && seg2Inside) {
t.Error("No solution but only one point in radius of circle")
t.FailNow()
}
}
}
}
t.Log("Tested ", testCntr, " examples and found ", solutionCntr, " solutions.")
}
Here is the output of the test:
=== RUN TestSegmentCircleIntersection
--- PASS: TestSegmentCircleIntersection (0.00s)
geom_test.go:105: Tested 40000 examples and found 7343 solutions.
Finally, the method is easily extendable to the case of a ray starting at one point, going through the other and extending to infinity, by only testing if t > 0 or t < 1 but not both.
I'd extend the Array class with a pick_and_remove()
function, like so:
var ArrayInstanceExtensions = {
pick_and_remove: function(index){
var picked_element = this[index];
this.splice(index,1);
return picked_element;
}
};
$.extend(Array.prototype, ArrayInstanceExtensions);
While it may seem a bit verbose, you can now call pick_and_remove()
on any array you possibly want!
Usage:
array = [4,5,6] //=> [4,5,6]
array.pick_and_remove(1); //=> 5
array; //=> [4,6]
You can see all of this in pokemon-themed action here.
It is possible to do this, but most likely your host implemented mod_security
for a reason. Be sure they approve of you disabling it for your own site.
That said, this should do it;
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
Comprehensions are usually faster, and this has the advantage of not editing mydict
during the iteration:
mydict = dict((k, v if v else '') for k, v in mydict.items())
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
AskTom is probably the single most helpful resource on best practices on Oracle DBs. (I usually just type "asktom" as the first word of a google query on a particular topic)
I don't think it's really appropriate to speak of design patterns with relational databases. Relational databases are already the application of a "design pattern" to a problem (the problem being "how to represent, store and work with data while maintaining its integrity", and the design being the relational model). Other approches (generally considered obsolete) are the Navigational and Hierarchical models (and I'm nure many others exist).
Having said that, you might consider "Data Warehousing" as a somewhat separate "pattern" or approach in database design. In particular, you might be interested in reading about the Star schema.
If you're using Python 3, raw_input
has changed to input
Python 3 example:
line = input('Enter a sentence:')
If a variable is defined as an object e.g. Dim myfldr As Folder, it is assigned a value by using the keyword, "Set".
Try .live()
or .delegate()
http://api.jquery.com/delegate/
Your .test
element was added after the .click()
method, so it didn't have the event attached to it. Live and Delegate give that event trigger to parent elements which check their children, so anything added afterwards still works. I think Live will check the entire document body, while Delegate can be given to an element, so Delegate is more efficient.
More info:
http://www.alfajango.com/blog/the-difference-between-jquerys-bind-live-and-delegate/
Try to use this xPath expression:
//book/title[@lang='it']/..
That should give you all book nodes in "it" lang
Arrays.sort(numArray);
return (numArray[size/2] + numArray[(size-1)/2]) / 2;
Based on top voted answer, updated for C# 8. Following can be used out of the box. Added explicit System.Drawing
before Image
as one might be using that class from other namespace defaultly.
public static string ImagePathToBase64(string path)
{
using System.Drawing.Image image = System.Drawing.Image.FromFile(path);
using MemoryStream m = new MemoryStream();
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
tring base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
Override the property isDefaultPrevented
like this:
$('a').click(function(evt){
evt.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
IMHO, this is most complete way of retriggering the event with the exactly same data.
In SQL 2012+, you can use THROW.
THROW 51000, 'Stopping execution because validation failed.', 0;
PRINT 'Still Executing'; -- This doesn't execute with THROW
From MSDN:
Raises an exception and transfers execution to a CATCH block of a TRY…CATCH construct ... If a TRY…CATCH construct is not available, the session is ended. The line number and procedure where the exception is raised are set. The severity is set to 16.
This would be work very fine
<a href="<%:Url.Action("Edit","Account",new { id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>
If you use first answer, there is a problem with thumb. In chrome if you want the thumb to be larger than the track, then the box shadow overlaps the track with the height of the thumb.
Just sumup all these answers and wrote normally working slider with larger slider thumb: jsfiddle
const slider = document.getElementById("myinput")
const min = slider.min
const max = slider.max
const value = slider.value
slider.style.background = `linear-gradient(to right, red 0%, red ${(value-min)/(max-min)*100}%, #DEE2E6 ${(value-min)/(max-min)*100}%, #DEE2E6 100%)`
slider.oninput = function() {
this.style.background = `linear-gradient(to right, red 0%, red ${(this.value-this.min)/(this.max-this.min)*100}%, #DEE2E6 ${(this.value-this.min)/(this.max-this.min)*100}%, #DEE2E6 100%)`
};
_x000D_
#myinput {
border-radius: 8px;
height: 4px;
width: 150px;
outline: none;
-webkit-appearance: none;
}
input[type='range']::-webkit-slider-thumb {
width: 6px;
-webkit-appearance: none;
height: 12px;
background: black;
border-radius: 2px;
}
_x000D_
<div class="chrome">
<input id="myinput" type="range" min="0" value="25" max="200" />
</div>
_x000D_
Simple, one liner:
import datetime as dt
previous_month = (dt.date.today().replace(day=1) - dt.timedelta(days=1)).month
I once was called upon to look at a mysql that had "stopped working". I discovered that the DB files were residing on a Network Appliance filer mounted with NFS2 and with a maximum file size of 2GB. And sure enough, the table that had stopped accepting transactions was exactly 2GB on disk. But with regards to the performance curve I'm told that it was working like a champ right up until it didn't work at all! This experience always serves for me as a nice reminder that there're always dimensions above and below the one you naturally suspect.
You would need to have an instance of ClassA within ClassB or have ClassB inherit ClassA
class ClassA {
public function getName() {
echo $this->name;
}
}
class ClassB extends ClassA {
public function getName() {
parent::getName();
}
}
Without inheritance or an instance method, you'd need ClassA to have a static method
class ClassA {
public static function getName() {
echo "Rawkode";
}
}
--- other file ---
echo ClassA::getName();
If you're just looking to call the method from an instance of the class:
class ClassA {
public function getName() {
echo "Rawkode";
}
}
--- other file ---
$a = new ClassA();
echo $a->getName();
Regardless of the solution you choose, require 'ClassA.php
is needed.
For me for this issue worked to:
After eclipse restart everything worked well.
Better late than never! I made mine a class:
.map
{
position:absolute;
top:64px;
width:1100px;
height:735px;
overflow:hidden;
border:1px solid rgb(211,211,211);
border-radius:3px;
}
and then
<div id="map" class="map"></div>
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@uu$`a"
iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// PHP Notice: iconv(): Detected an illegal character
iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@u$`a"
iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate('é@ùµ$`à'))
// "e@uu$`a" -> same as PHP 7.2
Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)
Dim StrSelection As String
Private Sub ListBox1_Change()
If ListBox1.Selected(ListBox1.ListIndex) Then
If StrSelection = "" Then
StrSelection = ListBox1.List(ListBox1.ListIndex)
Else
StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
End If
Else
StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
End If
End Sub
gcloud config set project my-project
You may also set the environment variable $CLOUDSDK_CORE_PROJECT
.
Like This:
<?= $form->field($model, 'hidden')->hiddenInput(['class' => 'form-control', 'maxlength' => true,])->label(false) ?>
You can simply make it by REGEX:
Form:
<form method="post" action="" enctype="multipart/form-data">
<div class="uploadExtensionError" style="display: none">Only PDF allowed!</div>
<input type="file" name="item_file" />
<input type="submit" id='submit' value="submit"/>
</form>
And java script validation:
<script>
$('#submit').click(function(event) {
var val = $('input[type=file]').val().toLowerCase();
var regex = new RegExp("(.*?)\.(pdf|docx|doc)$");
if(!(regex.test(val))) {
$('.uploadExtensionError').show();
event.preventDefault();
}
});
</script>
Cheers!
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
If you want a single value for all rows:
df.insert(0,'name_of_column','')
df['name_of_column'] = value
Edit:
You can also:
df.insert(0,'name_of_column',value)
After heavy testing we came to the conclusion that GROUP BY is faster
SELECT sql_no_cache
opnamegroep_intern
FROM telwerken
WHERE opnemergroep
IN (7,8,9,10,11,12,13) group by opnamegroep_intern
635 totaal 0.0944 seconds Weergave van records 0 - 29 ( 635 totaal, query duurde 0.0484 sec)
SELECT sql_no_cache
distinct (opnamegroep_intern)
FROM telwerken
WHERE opnemergroep
IN (7,8,9,10,11,12,13)
635 totaal 0.2117 seconds ( almost 100% slower ) Weergave van records 0 - 29 ( 635 totaal, query duurde 0.3468 sec)
There is a difference, but there is no difference in that example.
Using the more verbose method: new Array()
does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:
x = new Array(5);
alert(x.length); // 5
To illustrate the different ways to create an array:
var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
Another difference is that when using new Array()
you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array()
because you can prevent the overflow from happening.
As pointed out in this answer, new Array(5)
will not actually add five undefined
items to the array. It simply adds space for five items. Be aware that using Array
this way makes it difficult to rely on array.length
for calculations.
The OOM exception could be avoided by following the official guide to load large bitmap.
Don't run your code on the UI Thread. Use AsyncTask instead and you should be fine.
This is a working example of making ZIPs in PHP:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));
}
else{
echo"file does not exist";
}
}
$zip->close();
The simplest fix is to make the comparator function be static:
static int comparator (const Bar & first, const Bar & second);
^^^^^^
When invoking it in Count
, its name will be Foo::comparator
.
The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo
.
Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo
.
Simplest way, get a launchpad account and use: ssh-import-id
It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.
In your case you will find the four nodes that you want using this expression:
XmlDocument doc = new XmlDocument();
doc.Load(fileName);
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");
You should never use the unidirectional @OneToMany
annotation because:
Now, in your first example, both sides are owning the association, and this is bad.
While the @JoinColumn
would let the @OneToMany
side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy
attribute on the @OneToMany
side.
public class User{
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<APost> aPosts;
@OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
public List<BPost> bPosts;
}
public class BPost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
public class APost extends Post {
@ManyToOne(fetch=FetchType.LAZY)
public User user;
}
Add an id attribute to a html tag
<ul class="nav nav-tabs">
<li><a href="#aaa" data-toggle="tab" id="tab_aaa">AAA</a></li>
<li><a href="#bbb" data-toggle="tab" id="tab_bbb">BBB</a></li>
<li><a href="#ccc" data-toggle="tab" id="tab_ccc">CCC</a></li>
</ul>
<div class="tab-content" id="tabs">
<div class="tab-pane" id="aaa">...Content...</div>
<div class="tab-pane" id="bbb">...Content...</div>
<div class="tab-pane" id="ccc">...Content...</div>
</div>
Then using JQuery
$("#tab_aaa").tab('show');
I would like to add a bit more to MadProgrammer's Answer.
In case of multiple line writing, when executing the command
writer.write(string);
one may notice that the newline characters are omitted or skipped in the written file even though they appear during debugging or if the same text is printed onto the terminal with,
System.out.println("\n");
Thus, the whole text comes as one big chunk of text which is undesirable in most cases. The newline character can be dependent on the platform, so it is better to get this character from the java system properties using
String newline = System.getProperty("line.separator");
and then using the newline variable instead of "\n". This will get the output in the way you want it.
This does it:
public static void main(String[] args) {
final String uuid = UUID.randomUUID().toString().replace("-", "");
System.out.println("uuid = " + uuid);
}
That should work:
>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
A
0 0
1 1
2 2
But the append
doesn't happen in-place, so you'll have to store the output if you want it:
>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
A
0 0
1 1
2 2
Use getCellType()
switch (cell.getCellType()) {
case BOOLEAN :
//To-do
break;
case NUMERIC:
//To-do
break;
case STRING:
//To-do
break;
}
You need to actually use the shortened array after you remove items from it. You are ignoring the shortened array.
You convert the cookie into an array. You reduce the length of the array and then you never use that shortened array. Instead, you just use the old cookie (the unshortened one).
You should convert the shortened array back to a string with .join(",")
and then use it for the new cookie instead of using old_cookie
which is not shortened.
You may also not be using .splice()
correctly, but I don't know exactly what your objective is for shortening the array. You can read about the exact function of .splice()
here.
That’s a typo. You’ve accidently set user.mail
with no e. Fix it by setting user.email
in the global configuration with
git config --global user.email "[email protected]"