Your rewrite rule looks almost ok.
First make sure that your .htaccess
file is in your document root (the same place as index.php
) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).
Next make a slight change to your rule so it looks something like:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]
At the moment you're just matching on .
which is one instance of any character, you need at least .*
to match any number of instances of any character.
The $_GET['path']
variable will contain the fake directory structure, so /mvc/module/test
for instance, which you can then use in index.php to determine the Controller and actions you want to perform.
If you want the whole shebang installed in a sub-directory, such as /mvc/
or /framework/
the least complicated way to do it is to change the rewrite rule slightly to take that into account.
RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]
And ensure that your index.php
is in that folder whilst the .htaccess
file is in the document root.
Alternative to $_GET['path']
(updated Feb '18 and Jan '19)
It's not actually necessary (nor even common now) to set the path as a $_GET
variable, many frameworks will rely on $_SERVER['REQUEST_URI']
to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.
This does simplify the RewriteRule
slightly as you don't need to create the path parameter (which means the OP's original RewriteRule
will now work):
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]
However, the rule about installing in a sub-directory still applies, e.g.
RewriteRule ^.*$ /mvc/index.php [L,QSA]
The flags:
NC
= No Case (not case sensitive, not really necessary since there are no characters in the pattern)
L
= Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)
QSA
= Query String Append, just in case you've got something like ?like=penguins
on the end which you want to keep and pass to index.php.
This is much simple way to do it.
Have a private int selectedPos = RecyclerView.NO_POSITION;
in the RecyclerView Adapter class, and under onBindViewHolder method try:
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
viewHolder.itemView.setSelected(selectedPos == position);
}
And in your OnClick event modify:
@Override
public void onClick(View view) {
notifyItemChanged(selectedPos);
selectedPos = getLayoutPosition();
notifyItemChanged(selectedPos);
}
Works like a charm for Navigtional Drawer and other RecyclerView Item Adapters.
Note: Be sure to use a background color in your layout using a selector like colabug clarified:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/pressed_color" android:state_pressed="true"/>
<item android:drawable="@color/selected_color" android:state_selected="true"/>
<item android:drawable="@color/focused_color" android:state_focused="true"/>
</selector>
Otherwise setSelected(..) will do nothing, rendering this solution useless.
I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.
FrameLayout
is not the better way to do this:
Use RelativeLayout
instead.
You can position the elements anywhere you like.
The element that comes after, has the higher z-index than the previous one (i.e. it comes over the previous one).
Example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorPrimary"
app:srcCompat="@drawable/ic_information"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a text."
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
android:layout_margin="8dp"
android:padding="5dp"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#A000"
android:textColor="@android:color/white"/>
</RelativeLayout>
No need of JQuery simply you can do
if(yourObject['email']){
// what if this property exists.
}
as with any value for email
will return you true
, if there is no such property or that property value is null
or undefined
will result to false
use the keyword break
instead of return
With Homebrew and jenv:
Assumption: Mac machine and you already have installed homebrew.
Install cask:
$ brew tap caskroom/cask
$ brew tap caskroom/versions
To install latest java:
$ brew cask install java
To install java 8:
$ brew cask install java8
To install java 9:
$ brew cask install java9
If you want to install/manage multiple version then you can use 'jenv':
Install and configure jenv:
$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
Add the installed java to jenv:
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.11.0_2.jdk/Contents/Home
To see all the installed java:
$ jenv versions
Above command will give the list of installed java:
* system (set by /Users/lyncean/.jenv/version)
1.8
1.8.0.202-ea
oracle64-1.8.0.202-ea
Configure the java version which you want to use:
$ jenv global oracle64-1.6.0.39
I have had this problem when using PHP5.4 and Plesk 11.5
Somehow, the error reporting and display error settings in the Plesk domain configuration page were completely overriding any local settings in .htaccess or the PHP scripts. I have not found a way to prevent this happening, so use the Plesk settings to turn error reporting on and off.
You may have settings in your php.ini that prevents the local site from overriding these settings, perhaps enforced by the control panel used on your server.
The quote PASV
command is not a command to the ftp.exe
program, it is a command to the FTP server requesting a high order port for data transfer. A passive transfer is one in which the FTP data over these high order ports while control is maintained in the lower ports.
The windows ftp.exe
program can be used to send the FTP server commands to make a passive data transfer between two FTP servers. A standard windows installation will not, and probably should not, have FTP server service running as an endpoint for passive transfers. So if passive transfers are needed with a standard windows box, a solution other than ftp.exe
is necessary as FTPing to localhost as one of the connections won't work in most windows environments.
You can effect a passive FTP transfer between two different hosts (but not two connections on the same host) as follows:
Open up two prompts, use one to ftp.exe
connect to your source FTP server and one to ftp.exe
connect to your destination FTP server.
Now establish a passive connection between the servers using the raw commands PASV and PORT. The quote PASV
command will respond with an IP/port in ellipsis. Use that data for the quote PORT <data>
command. Your passive link is now established assuming that firewalls haven't blocked one or more of the four ports (2 for FTP control, 2 for FTP data)
Next start receive of data with the quote STOR <filename>
command to the receiving FTP server then send the control command quote RETR <filename>
to the source FTP server.
so for me:
client 1
> ftp.exe server1
ftp> quote PASV
227 Entering Passive Mode (10,0,3,1,54,161)
client 2
> ftp.exe server2
ftp> quote PORT 10,0,3,1,54,54,161
ftp> quote STOR myFile
client 1
ftp> quote RETR myFile
Cavet: I'm connecting to some old FTP servers YMMV
if you set the onclick
via html
you need to removeAttr ($(this).removeAttr('onclick'))
if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))
If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period
public abstract class AsyncTaskWithTimer<Params, Progress, Result> extends
AsyncTask<Params, Progress, Result> {
private static final int HTTP_REQUEST_TIMEOUT = 30000;
@Override
protected Result doInBackground(Params... params) {
createTimeoutListener();
return doInBackgroundImpl(params);
}
private void createTimeoutListener() {
Thread timeout = new Thread() {
public void run() {
Looper.prepare();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (AsyncTaskWithTimer.this != null
&& AsyncTaskWithTimer.this.getStatus() != Status.FINISHED)
AsyncTaskWithTimer.this.cancel(true);
handler.removeCallbacks(this);
Looper.myLooper().quit();
}
}, HTTP_REQUEST_TIMEOUT);
Looper.loop();
}
};
timeout.start();
}
abstract protected Result doInBackgroundImpl(Params... params);
}
A Sample for this
public class AsyncTaskWithTimerSample extends AsyncTaskWithTimer<Void, Void, Void> {
@Override
protected void onCancelled(Void void) {
Log.d(TAG, "Async Task onCancelled With Result");
super.onCancelled(result);
}
@Override
protected void onCancelled() {
Log.d(TAG, "Async Task onCancelled");
super.onCancelled();
}
@Override
protected Void doInBackgroundImpl(Void... params) {
// Do background work
return null;
};
}
You can't, but you can use BETWEEN
SELECT job FROM mytable WHERE id BETWEEN 10 AND 15
Note that BETWEEN
is inclusive, and will include items with both id 10 and 15.
If you do not want inclusion, you'll have to fall back to using the >
and <
operators.
SELECT job FROM mytable WHERE id > 10 AND id < 15
This is very much implementation specific, but the general idea is to allow providers to issue short term access tokens with long term refresh tokens. Why?
Okay I fixed this thing. Had to first convert the projects to Maven Projects, then remove them from the Eclipse workspace, and then re-import them.
After Rebuild the project issue resolved..
The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).
And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
For me when i try to restore from remote host i used
psql -U username -p 5432 -h 10.10.10.1 -d database < db.dump
worked fine. And if not remote just following command worked.
psql -d database < db.dump
I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:
https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About
The only other thing that would likely be helpful is suppressing that code analysis warning... https://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017
There's no problem. I would even remove the CreateNewOrUpdateExisting
from the source and use map[key] = value
directly in your code, because this this is much more readable, because developers would usually know what map[key] = value
means.
I am using xampp. For me best option is to change environment variables. Environment variable changing window is shared by @Abu Bakr in this thread
I change the path value as C:\xampp\mysql\bin; and it is working nice
You can always find out the location of the tnsnames.ora file being used by running TNSPING to check connectivity (9i or later):
C:\>tnsping dev
TNS Ping Utility for 32-bit Windows: Version 10.2.0.1.0 - Production on 08-JAN-2009 12:48:38
Copyright (c) 1997, 2005, Oracle. All rights reserved.
Used parameter files:
C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\sqlnet.ora
Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = XXX)(PORT = 1521)) (CONNECT_DATA = (SERVICE_NAME = DEV)))
OK (30 msec)
C:\>
Sometimes, the problem is with the entry you made in tnsnames.ora, not that the system can't find it. That said, I agree that having a tns_admin environment variable set is a Good Thing, since it avoids the inevitable issues that arise with determining exactly which tnsnames file is being used in systems with multiple oracle homes.
One way to do it if the file is not very big is to load all the lines into an array:
string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);
Actually you have to Do Like below Example, which will help to Solve the Issue...
drop table ABC_table
create table ABC_table
(
names varchar(20),
age int
)
ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names
insert into ABC(age) values(10)
select * from ABC
System.Diagnostics.Stopwatch is designed for this task.
You're currently writing the binary data in the string
-object to your file. This binary data will probably only consist of a pointer to the actual data, and an integer representing the length of the string.
If you want to write to a text file, the best way to do this would probably be with an ofstream
, an "out-file-stream". It behaves exactly like std::cout
, but the output is written to a file.
The following example reads one string from stdin, and then writes this string to the file output.txt
.
#include <fstream>
#include <string>
#include <iostream>
int main()
{
std::string input;
std::cin >> input;
std::ofstream out("output.txt");
out << input;
out.close();
return 0;
}
Note that out.close()
isn't strictly neccessary here: the deconstructor of ofstream
can handle this for us as soon as out
goes out of scope.
For more information, see the C++-reference: http://cplusplus.com/reference/fstream/ofstream/ofstream/
Now if you need to write to a file in binary form, you should do this using the actual data in the string. The easiest way to acquire this data would be using string::c_str()
. So you could use:
write.write( studentPassword.c_str(), sizeof(char)*studentPassword.size() );
You can still use the Authorization header with OAuth 2.0. There is a Bearer type specified in the Authorization header for use with OAuth bearer tokens (meaning the client app simply has to present ("bear") the token). The value of the header is the access token the client received from the Authorization Server.
It's documented in this spec: https://tools.ietf.org/html/rfc6750#section-2.1
E.g.:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
Where mF_9.B5f-4.1JqM is your OAuth access token.
Did you try this simple solution? Only 2 clicks away!
At the query window,
You will get all the text you want to see in the file!!! I can see 130,556 characters for my result of a varchar(MAX) field
I ran into this issue. I had three folders in the same directory so I had to specify which folder. Ex: from Folder import script
If I understand the question correctly, you want to detect when the h_no
doesn't increase and then increment the class
. (I'm going to walk through how I solved this problem, there is a self-contained function at the end.)
We only care about the h_no
column for the moment, so we can extract that from the data frame:
> h_no <- data$h_no
We want to detect when h_no
doesn't go up, which we can do by working out when the difference between successive elements is either negative or zero. R provides the diff
function which gives us the vector of differences:
> d.h_no <- diff(h_no)
> d.h_no
[1] 1 1 1 -3 1 1 1 1 1 1 -6 1 1 1
Once we have that, it is a simple matter to find the ones that are non-positive:
> nonpos <- d.h_no <= 0
> nonpos
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
[13] FALSE FALSE
In R, TRUE
and FALSE
are basically the same as 1
and 0
, so if we get the cumulative sum of nonpos
, it will increase by 1 in (almost) the appropriate spots. The cumsum
function (which is basically the opposite of diff
) can do this.
> cumsum(nonpos)
[1] 0 0 0 1 1 1 1 1 1 1 2 2 2 2
But, there are two problems: the numbers are one too small; and, we are missing the first element (there should be four in the first class).
The first problem is simply solved: 1+cumsum(nonpos)
. And the second just requires adding a 1
to the front of the vector, since the first element is always in class 1
:
> classes <- c(1, 1 + cumsum(nonpos))
> classes
[1] 1 1 1 1 2 2 2 2 2 2 2 3 3 3 3
Now, we can attach it back onto our data frame with cbind
(by using the class=
syntax, we can give the column the class
heading):
> data_w_classes <- cbind(data, class=classes)
And data_w_classes
now contains the result.
We can compress the lines together and wrap it all up into a function to make it easier to use:
classify <- function(data) {
cbind(data, class=c(1, 1 + cumsum(diff(data$h_no) <= 0)))
}
Or, since it makes sense for the class
to be a factor:
classify <- function(data) {
cbind(data, class=factor(c(1, 1 + cumsum(diff(data$h_no) <= 0))))
}
You use either function like:
> classified <- classify(data) # doesn't overwrite data
> data <- classify(data) # data now has the "class" column
(This method of solving this problem is good because it avoids explicit iteration, which is generally recommend for R, and avoids generating lots of intermediate vectors and list etc. And also it's kinda neat how it can be written on one line :) )
Personally I'd go with AJAX.
If you cannot switch to @Ajax...
helpers, I suggest you to add a couple of properties in your model
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
Change your view to a strongly typed Model via
@using MyModel
Before returning the View, in case of successfull creation do something like
MyModel model = new MyModel();
model.TriggerOnLoad = true;
model.TriggerOnLoadMessage = "Object successfully created!";
return View ("Add", model);
then in your view, add this
@{
if (model.TriggerOnLoad) {
<text>
<script type="text/javascript">
alert('@Model.TriggerOnLoadMessage');
</script>
</text>
}
}
Of course inside the tag you can choose to do anything you want, event declare a jQuery ready function:
$(document).ready(function () {
alert('@Model.TriggerOnLoadMessage');
});
Please remember to reset the Model properties upon successfully alert emission.
Another nice thing about MVC is that you can actually define an EditorTemplate for all this, and then use it in your view via:
@Html.EditorFor (m => m.TriggerOnLoadMessage)
But in case you want to build up such a thing, maybe it's better to define your own C# class:
class ClientMessageNotification {
public bool TriggerOnLoad { get; set; }
public string TriggerOnLoadMessage { get; set: }
}
and add a ClientMessageNotification
property in your model. Then write EditorTemplate / DisplayTemplate for the ClientMessageNotification
class and you're done. Nice, clean, and reusable.
It should be like this
$(this).text($(this).text().replace('N/A, ', ''))
A good alternative to PuTTY is the Mintty terminal emulator. It has more configurable options than PuTTY.
In Windows 10 I browsed to *%APPDATA%\MySQL\Workbench* then deleted the workbench_user_data.dat file
Doing so lost my MySqlWorkbence settings but allowed MySqlWorkbence to open.
margin: 50%;
You can adjust the percentage as needed. It seems to work for me in responsive emails.
There's an option in the Simulator to open the console
Debug > Open System Log
or use the
keyboard shortcut: ?/
Spaces are used for separating Arguments. In your case C:\Program becomes argument. If your file path contains spaces then add Double quotation marks. Then cmd will recognize it as single argument.
To check if a folder contains at least one file
>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder or any of its descendents contain at least one file
>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)
To check if a folder contains at least one file or folder.
Note addition of /a
option to enable finding of hidden and system files/folders.
dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)
To check if a folder contains at least one folder
dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)
Not so hard:
#include <thread>
void Test::runMultiThread()
{
std::thread t1(&Test::calculate, this, 0, 10);
std::thread t2(&Test::calculate, this, 11, 20);
t1.join();
t2.join();
}
If the result of the computation is still needed, use a future instead:
#include <future>
void Test::runMultiThread()
{
auto f1 = std::async(&Test::calculate, this, 0, 10);
auto f2 = std::async(&Test::calculate, this, 11, 20);
auto res1 = f1.get();
auto res2 = f2.get();
}
Just as a reference, here is an example of how to convert between String
and char[]
with a dynamic length -
// Define
String str = "This is my string";
// Length (with one extra character for the null terminator)
int str_len = str.length() + 1;
// Prepare the character array (the buffer)
char char_array[str_len];
// Copy it over
str.toCharArray(char_array, str_len);
Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.
var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;
function changeIframe() {
$('#frame')[0].src = sites[index++];
index = index >= sites.length ? 0 : index;
}
Try this, you can parse nested JSON
public static String getJsonValue(String jsonReq, String key) {
JSONObject json = new JSONObject(jsonReq);
boolean exists = json.has(key);
Iterator<?> keys;
String nextKeys;
String val = "";
if (!exists) {
keys = json.keys();
while (keys.hasNext()) {
nextKeys = (String) keys.next();
try {
if (json.get(nextKeys) instanceof JSONObject) {
return getJsonValue(json.getJSONObject(nextKeys).toString(), key);
} else if (json.get(nextKeys) instanceof JSONArray) {
JSONArray jsonArray = json.getJSONArray(nextKeys);
int i = 0;
if (i < jsonArray.length()) do {
String jsonArrayString = jsonArray.get(i).toString();
JSONObject innerJson = new JSONObject(jsonArrayString);
return getJsonValue(innerJson.toString(),key);
} while (i < jsonArray.length());
}
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
val = json.get(key).toString();
}
return val;
}
I just figured out one method to avoid above errors.
Save to database
user.first_name = u'Rytis'.encode('unicode_escape')
user.last_name = u'Slatkevicius'.encode('unicode_escape')
user.save()
>>> SUCCEED
print user.last_name
>>> Slatkevi\u010dius
print user.last_name.decode('unicode_escape')
>>> Slatkevicius
Is this the only method to save strings like that into a MySQL table and decode it before rendering to templates for display?
<div id"content">
<div id"contentLeft"></div>
<div id"contentRight"></div>
</div>
#content {
clear: both;
width: 950px;
padding-bottom: 10px;
background:#fff;
overflow:hidden;
}
#contentLeft {
float: left;
display:inline;
width: 630px;
margin: 10px;
background:#fff;
}
#contentRight {
float: right;
width: 270px;
margin-top:25px;
margin-right:15px;
background:#d7e5f7;
}
Obviously you will need to adjust the size of the columns to suit your site as well as colours etc but that should do it. You also need to make sure that your ContentLeft and ContentRight widths do not exceed the Contents width (including margins).
This worked for me.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
btnSendSMS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendSMS("5556", "Hi You got a message!");
/*here i can send message to emulator 5556. In Real device
*you can change number*/
}
});
}
//Sends an SMS message to another device
private void sendSMS(String phoneNumber, String message) {
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}
You can add this line in AndroidManifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>
Take a look at this
This may be helpful for you.
When XML first came out, we were told it would solve all our problems: XML will be user-friendly, infinitely extensible, avoid strong-typing, and not require any programming skills. I learnt about DTD's and wrote my own XML parser. 15+ years later, I see that most XML is not user-friendly, and not very extensible (depending on its usage). As soon as some clever clogs hooked up XML to a database I knew that data types were all but inevitable. And, you should see the XSLT (transformation file) I had to work on the other day. If that isn't programming, I don't know what is! Nowadays it's not unusual to see all kinds of problems relating to XML data or interfaces gone bad. I love XML but, it has strayed far from its original altruistic starting point.
The short answer? DTD's have been deprecated in favor of XSD's because an XSD lets you define an XML structure with more precision.
The powerful command installs and replaces the last package.
I had a similar problem. I fixed it.
npm install -g @angular/cli@latest
and
npm install --save-dev @angular/cli@latest
You should do this using jQuery.ajaxStart
and jQuery.ajaxStop
.
jQuery.ajaxStart
jQuery.ajaxStop
<div id="loading" style="display:none">Your Image</div>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
$(function () {
var loading = $("#loading");
$(document).ajaxStart(function () {
loading.show();
});
$(document).ajaxStop(function () {
loading.hide();
});
$("#startAjaxRequest").click(function () {
$.ajax({
url: "http://www.google.com",
// ...
});
});
});
</script>
<button id="startAjaxRequest">Start</button>
On Android 6 with ADB version 1.0.32, you have to put / behind the folder you want to copy. E.g adb pull "/sdcard/".
in the example below I exclude
spring-boot-starter-tomcat
compile("org.springframework.boot:spring-boot-starter-web") {
//by both name and group
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
Something that I tried and work for me is simply you create a new virtual machine and you use the existing virtual hard disk file and everything is like you left it.
Nothing really helped me - I could not overwrite settings in a /etc/my.cnf file. So I searched like John suggested https://stackoverflow.com/a/7974114/717251
sudo /usr/libexec/locate.updatedb
# wait a few minutes for it to finish
locate my.cnf
It found another my.cnf in
/usr/local/Cellar/mysql/5.6.21/my.cnf
changing this file worked for me! Don't forget to restart the launch Agent:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
Update:
If you have a fairly recent installation of homebrew you should use the brew services commands to restart mysql (use your installed homebrew mysql version, i.e. mysql or [email protected]):
brew services stop mysql
brew services start mysql
Here is representation of screen eclipse to make hierarachical.
The Content hugging priority
is like a Rubber band that is placed around a view.
The higher the priority value, the stronger the rubber band and the more it wants to hug to its content size.
The priority value can be imagined like the "strength" of the rubber band
And the Content Compression Resistance
is, how much a view "resists" getting smaller
The View with higher resistance priority value is the one that will resist compression.
There are various ways to achieve this. Here are three.
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println();
System.out.println("using keySet");
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
System.out.println();
using entrySet and toString
key1=value1
key2=value2
key3=value3
using entrySet and manual string creation
key1=value1
key2=value2
key3=value3
using keySet
key1=value1
key2=value2
key3=value3
keytool -import -v -alias cacerts -keystore cacerts.jks -storepass changeit -file C:\cacerts.cer
Try "py" instead of "python" from command line:
C:\Users\Cpsa>py
Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
I am almost sure you are not actually getting it installed correctly. Since you are trying to install it globally, you will need to run it with sudo:
sudo npm install -g bower
For those who can't rely on Chronometer, I made a utility class out of one of the suggestions:
public class TimerTextHelper implements Runnable {
private final Handler handler = new Handler();
private final TextView textView;
private volatile long startTime;
private volatile long elapsedTime;
public TimerTextHelper(TextView textView) {
this.textView = textView;
}
@Override
public void run() {
long millis = System.currentTimeMillis() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
textView.setText(String.format("%d:%02d", minutes, seconds));
if (elapsedTime == -1) {
handler.postDelayed(this, 500);
}
}
public void start() {
this.startTime = System.currentTimeMillis();
this.elapsedTime = -1;
handler.post(this);
}
public void stop() {
this.elapsedTime = System.currentTimeMillis() - startTime;
handler.removeCallbacks(this);
}
public long getElapsedTime() {
return elapsedTime;
}
}
to use..just do:
TimerTextHelper timerTextHelper = new TimerTextHelper(textView);
timerTextHelper.start();
.....
timerTextHelper.stop();
long elapsedTime = timerTextHelper.getElapsedTime();
I have used Raleway Font for styling
To C:\User\UserName\.jupyter\custom\custom.css file
append the given styles, this is specifically for Dark Mode for jupyter notebook...
This should be your current custom.css file: -
/* This file contains any manual css for this page that needs to override the global styles.
This is only required when different pages style the same element differently. This is just
a hack to deal with our current css styles and no new styling should be added in this file.*/
#ipython-main-app {
position: relative;
}
#jupyter-main-app {
position: relative;
}
Content to be append starts now
.header-bar {
display: none;
}
#header-container img {
display: none;
}
#notebook_name {
margin-left: 0px !important;
}
#header-container {
padding-left: 0px !important
}
html,
body {
overflow: hidden;
font-family: OpenSans;
}
#header {
background-color: #212121 !important;
color: #fff;
padding-top: 20px;
padding-bottom: 50px;
}
.navbar-collapse {
background-color: #212121 !important;
color: #fff;
border: none !important
}
#menus {
border: none !important;
color: white !important;
}
#menus .dropdown-toggle {
color: white !important;
}
#filelink {
color: white !important;
text-align: centerimportant;
padding-left: 7px;
text-decoration: none !important;
}
.navbar-default .navbar-nav>.open>a,
.navbar-default .navbar-nav>.open>a:hover,
.navbar-default .navbar-nav>.open>a:focus {
background-color: #191919 !important;
color: #eee !important;
text-align: left !important;
}
.dropdown-menu,
.dropdown-menu a,
.dropdown-submenu a {
background-color: #191919;
color: #fff !important;
}
.dropdown-menu>li>a:hover,
.dropdown-menu>li>a:focus,
.dropdown-submenu>a:after {
background-color: #212121;
color: #fff !important;
}
.btn-default {
color: #fff !important;
background-color: #212121 !important;
border: none !important;
}
.dropdown {
text-align: left !important;
}
.form-control.select-xs {
background-color: #191919 !important;
color: #eee !important;
border: none;
outline: none;
}
#modal_indicator {
display: none;
}
#kernel_indicator {
color: #fff;
}
#notification_trusted,
#notification_notebook {
background-color: #212121;
color: #eee !important;
border: none;
border-bottom: 1px solid #eee;
}
#logout {
background-color: #191919;
color: #eee;
}
#maintoolbar-container {
padding-top: 0px !important;
}
.notebook_app {
background-color: #222222;
}
::-webkit-scrollbar {
display: none;
}
#notebook-container {
background-color: #212121;
}
div.cell.selected,
div.cell.selected.jupyter-soft-selected {
border: none !important;
}
.cm-keyword {
color: orange !important;
}
.input_area {
background-color: #212121 !important;
color: white !important;
border: 1px solid rgba(255, 255, 255, 0.1) !important;
}
.cm-def {
color: #5bc0de !important;
}
.cm-variable {
color: yellow !important;
}
.output_subarea.output_text.output_result pre,
.output_subarea.output_text.output_stream.output_stdout pre {
color: white !important;
}
.CodeMirror-line {
color: white !important;
}
.cm-operator {
color: white !important;
}
.cm-number {
color: lightblue !important;
}
.inner_cell {
border: 1px thin #eee;
border-radius: 50px !important;
}
.CodeMirror-lines {
border-radius: 20px;
}
.prompt.input_prompt {
color: #5cb85c !important;
}
.prompt.output_prompt {
color: lightblue;
}
.cm-string {
color: #6872ac !important;
}
.cm-builtin {
color: #f0ad4e !important;
}
.run_this_cell {
color: lightblue !important;
}
.input_area {
border-radius: 20px;
}
.output_png {
background-color: white;
}
.CodeMirror-cursor {
border-left: 1.4px solid white;
}
.box-flex1.output_subarea.raw_input_container {
color: white;
}
input.raw_input {
color: black !important;
}
div.output_area pre {
color: white
}
h1,
h2,
h3,
h4,
h5,
h6 {
color: white !important;
font-weight: bolder !important;
}
.CodeMirror-gutter.CodeMirror-linenumber,
.CodeMirror-gutters {
background-color: #212121 !important;
}
span.filename:hover {
color: #191919 !important;
height: auto !important;
}
#site {
background-color: #191919 !important;
color: white !important;
}
#tabs li.active a {
background-color: #212121 !important;
color: white !important;
}
#tabs li {
background-color: #191919 !important;
color: white !important;
border-top: 1px thin #eee;
}
#notebook_list_header {
background-color: #212121 !important;
color: white !important;
}
#running .panel-group .panel {
background-color: #212121 !important;
color: white !important;
}
#accordion.panel-heading {
background-color: #212121 !important;
}
#running .panel-group .panel .panel-heading {
background-color: #212121;
color: white
}
.item_name {
color: white !important;
cursor: pointer !important;
}
.list_item:hover {
background-color: #212121 !important;
}
.item_icon.icon-fixed-width {
color: white !important;
}
#texteditor-backdrop {
background-color: #191919 !important;
border-top: 1px solid #eee;
}
.CodeMirror {
background-color: #212121 !important;
}
#texteditor-backdrop #texteditor-container .CodeMirror-gutter,
#texteditor-backdrop #texteditor-container .CodeMirror-gutters {
background-color: #212121 !important;
}
.celltoolbar {
background-color: #212121 !important;
border: none !important;
}
+
means "one or more characters" and without the plus it means "one character." In your case both result in the same output.
There is an official Python receipe for the more generalized case of splitting an array into smaller arrays of size n
.
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
This code snippet is from the python itertools doc page.
A safe and long way:
git branch todelete
git checkout todelete
git add .
git commit -m "I did a bad thing, sorry"
git checkout develop
git branch -D todelete
you can use this..
<select name="select_name">
<option value="1"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='1')?' selected="selected"':'');?>>Yes</option>
<option value="2"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='2')?' selected="selected"':'');?>>No</option>
<option value="3"<?php echo(isset($_POST['select_name'])&&($_POST['select_name']=='3')?' selected="selected"':'');?>>Fine</option>
</select>
Can also see here on how to turn on MSDTC from the Control Panel's services.msc.
On the server where the trigger resides, you need to turn the MSDTC service on. You can this by clicking START > SETTINGS > CONTROL PANEL > ADMINISTRATIVE TOOLS > SERVICES. Find the service called 'Distributed Transaction Coordinator' and RIGHT CLICK (on it and select) > Start.
I solve the problem the following way (MySQL only)
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
function get_client_ip()
{
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
The following works how you want it, but it is not ideal.
public class Tester extends Activity {
String[] vals = { "here", "are", "some", "values" };
Spinner spinner;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner) findViewById(R.id.spin);
ArrayAdapter<String> ad = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, vals);
spinner.setAdapter(ad);
Log.i("", "" + spinner.getChildCount());
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
int a = spinner.getCount();
int b = spinner.getChildCount();
System.out.println("Count =" + a);
System.out.println("ChildCount =" + b);
for (int i = 0; i < b; i++) {
View v = spinner.getChildAt(i);
if (v == null) {
System.out.println("View not found");
} else {
v.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("","click");
}
});
}
}
}
}, 500);
}
}
Let me know exactly how you need the spinner to behave, and we can work out a better solution.
What worked for me was:
<div style='display: inline-flex; width: 80px; height: 80px;'>
<img style='max-width: 100%; max-height: 100%' src='image file'>
</div>
inline-flex was required to keep the images from going outside of the div.
Note that there is a very simple solution.
Download the software from http://www.microsoft.com/en-us/download/details.aspx?id=44266 and install it.
Find the installing directory, it is something like "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python"
Change the directory name "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0" to "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC"
Add a new environment variable "VS90COMNTOOLS" and its value is "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC\VC"
Now everything is OK.
Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js
node_modules/
app/
index.html
server.js
After printing out the __dirname
path, I realized that the __dirname
path was where my server was running (app/
).
So, the answer to your question is this:
If your server.js
file is in the same folder as the files you are trying to render, then
app.use( express.static( path.join( application_root, 'site') ) );
should actually be
app.use(express.static(application_root));
The only time you would want to use the original syntax that you had would be if you had a folder tree like so:
app/
index.html
node_modules
server.js
where index.html
is in the app/
directory, whereas server.js
is in the root directory (i.e. the same level as the app/
directory).
Side note: Intead of calling the path
utility, you can use the syntax application_root + 'site'
to join a path.
Overall, your code could look like:
// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration
//Create server
var app = express();
// Configure server
app.configure( function() {
//Don't change anything here...
//Where to serve static content
app.use( express.static( application_root ) );
//Nothing changes here either...
});
//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
If you specify 'localhost' the client libs default to using the filesystem system socket on a Unix system - trying the mysql_default_socket value from php.ini (if set) then the my.cnf value.
If you connect using a different tool, try issuing the command "show variables like '%socket%'"
If you want to use a network port (which is a wee bit slower) then try specifying 127.0.0.1 or a physical interface asociated with the machine.
In case you want to work with the original MNIST files, here is how you can deserialize them.
If you haven't downloaded the files yet, do that first by running the following in the terminal:
wget http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz
wget http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz
Then save the following as deserialize.py
and run it.
import numpy as np
import gzip
IMG_DIM = 28
def decode_image_file(fname):
result = []
n_bytes_per_img = IMG_DIM*IMG_DIM
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[16:]
if len(data) % n_bytes_per_img != 0:
raise Exception('Something wrong with the file')
result = np.frombuffer(data, dtype=np.uint8).reshape(
len(bytes_)//n_bytes_per_img, n_bytes_per_img)
return result
def decode_label_file(fname):
result = []
with gzip.open(fname, 'rb') as f:
bytes_ = f.read()
data = bytes_[8:]
result = np.frombuffer(data, dtype=np.uint8)
return result
train_images = decode_image_file('train-images-idx3-ubyte.gz')
train_labels = decode_label_file('train-labels-idx1-ubyte.gz')
test_images = decode_image_file('t10k-images-idx3-ubyte.gz')
test_labels = decode_label_file('t10k-labels-idx1-ubyte.gz')
The script doesn't normalize the pixel values like in the pickled file. To do that, all you have to do is
train_images = train_images/255
test_images = test_images/255
I had an issue with node.exe
programs like test output with mocha
.
In my case, I solved it by removing some default "node.exe" alias.
I'm using Git Bash for Windows(2.29.2) and some default aliases are set from /etc/profile.d/aliases.sh
,
# show me alias related to 'node'
$ alias|grep node
alias node='winpty node.exe'`
To remove the alias, update aliases.sh
or simply do
unalias node
I don't know why winpty
has this side effect on console.info
buffered output but with a direct node.exe
use, I've no more stdout issue.
I am also having This Error!
Then i change this
$("#from").datepicker('disable');
to This
$("#from").datepicker("disable");
mistake : single and double quotes..
Now its Work fine for me..
You can use the standard Python idiom, vars()
:
for attr, value in vars(k).items():
print(attr, '=', value)
Don't know what platform you're on but in .NET there's the System.Version class that will parse "n.n.n.n" version numbers for you.
It is a shortcut to expose data members as public so that you don't need to explicitly create a private data members. C# will creates a private data member for you.
You could just make your data members public without using this shortcut but then if you decided to change the implementation of the data member to have some logic then you would need to break the interface. So in short it is a shortcut to create more flexible code.
I would caution that GUIDs are not random numbers. They should not be used as the basis to generate anything that you expect to be totally random (see http://en.wikipedia.org/wiki/Globally_Unique_Identifier):
Cryptanalysis of the WinAPI GUID generator shows that, since the sequence of V4 GUIDs is pseudo-random, given the initial state one can predict up to next 250 000 GUIDs returned by the function UuidCreate. This is why GUIDs should not be used in cryptography, e. g., as random keys.
Instead, just use the C# Random method. Something like this (code found here):
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch ;
for(int i=0; i<size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))) ;
builder.Append(ch);
}
return builder.ToString();
}
GUIDs are fine if you want something unique (like a unique filename or key in a database), but they are not good for something you want to be random (like a password or encryption key). So it depends on your application.
Edit. Microsoft says that Random is not that great either (http://msdn.microsoft.com/en-us/library/system.random(VS.71).aspx):
To generate a cryptographically secure random number suitable for creating a random password, for example, use a class derived from System.Security.Cryptography.RandomNumberGenerator such as System.Security.Cryptography.RNGCryptoServiceProvider.
// In form 1
public static string Username = Me;
// In form 2's load block
string _UserName = Form1.Username;
One word: Don't.
OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?
You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).
I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)
If you are using JSP 2.0 and above It will come with the EL support:
so that you can write in plain english and use and
with empty
operators to write your test:
<c:if test="${(empty object_1.attribute_A) and (empty object_2.attribute_B)}">
To push up through a given commit, you can write:
git push <remotename> <commit SHA>:<remotebranchname>
provided <remotebranchname>
already exists on the remote. (If it doesn't, you can use git push <remotename> <commit SHA>:refs/heads/<remotebranchname>
to autocreate it.)
If you want to push a commit without pushing previous commits, you should first use git rebase -i
to re-order the commits.
copy your certificates inside
/etc/pki/ca-trust/source/anchors/
then run the following command
update-ca-trust
There's a really good paper by Microsoft Research called To Blob or Not To Blob.
Their conclusion after a large number of performance tests and analysis is this:
if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient
if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)
in between those two, it's a bit of a toss-up depending on your use
If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.
For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".
Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:
CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
Check out the MSDN intro on filegroups, and play around with it!
you should use the EnumWindow API.
there are plenty of examples on how to use it from C#, I found something here:
Create two partial indexes:
CREATE UNIQUE INDEX favo_3col_uni_idx ON favorites (user_id, menu_id, recipe_id)
WHERE menu_id IS NOT NULL;
CREATE UNIQUE INDEX favo_2col_uni_idx ON favorites (user_id, recipe_id)
WHERE menu_id IS NULL;
This way, there can only be one combination of (user_id, recipe_id)
where menu_id IS NULL
, effectively implementing the desired constraint.
Possible drawbacks: you cannot have a foreign key referencing (user_id, menu_id, recipe_id)
, you cannot base CLUSTER
on a partial index, and queries without a matching WHERE
condition cannot use the partial index. (It seems unlikely you'd want a FK reference three columns wide - use the PK column instead).
If you need a complete index, you can alternatively drop the WHERE
condition from favo_3col_uni_idx
and your requirements are still enforced.
The index, now comprising the whole table, overlaps with the other one and gets bigger. Depending on typical queries and the percentage of NULL
values, this may or may not be useful. In extreme situations it might even help to maintain all three indexes (the two partial ones and a total on top).
Aside: I advise not to use mixed case identifiers in PostgreSQL.
1,1:
select 1 from dual
union all select 1 from dual
1:
select 1 from dual
union select 1 from dual
If you have JQuery loaded already, you can just do this:
$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
EDIT:
First load JQuery in the head tag:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
Then call the Javascript to change the background image when something happens on the page, like when it finishes loading:
<script type="text/javascript">
$(document).ready(function() {
$('body').css('background-image', 'url(../images/backgrounds/header-top.jpg)');
});
</script>
If you press CTRL + I it will just format tabs/whitespaces in code and pressing CTRL + SHIFT + F format all code that is format tabs/whitespaces and also divide code lines in a way that it is visible without horizontal scroll.
Easiest way for me is to use Unicode Characters and then style them with span tags. I'm going to use inline css for the sake of the example, but you can do it whatever way you prefer.
eg. When I want to use a square bullet and control its color and size:
<li style="list-style:none;"><a href=""><span style="font-size:x-small;vertical-align:middle;">█</span> HOME</a></li>
You can find lots of unicode bullets here:
I do this because linking images for bullets seems a little unnecessary to me.
I just upgrade my old XAMPP portable with PHP 5.3.X(Include Mercury & FileZilla & Tomcat) to XAMPP portable with PHP 5.6.X ( Include previous versions ) ...
My way:
max_upload_size
and etc on php.ini and also in /apache/conf/extra/httpd-xampp.conf
D
to drive C
NOTE
On Export database tab on phpmyadmin, select UTF-8 Character and check Disable foreign key checks
checkbox
and on import tab uncheck Enable foreign key checks
.
This is occurring due to how PHP treats overloaded properties in that they are not modifiable or passed by reference.
See the manual for more information regarding overloading.
To work around this problem you can either use a __set
function or create a createObject
method.
Below is a __get
and __set
that provides a workaround to a similar situation to yours, you can simply modify the __set
to suite your needs.
Note the __get
never actually returns a variable. and rather once you have set a variable in your object it no longer is overloaded.
/**
* Get a variable in the event.
*
* @param mixed $key Variable name.
*
* @return mixed|null
*/
public function __get($key)
{
throw new \LogicException(sprintf(
"Call to undefined event property %s",
$key
));
}
/**
* Set a variable in the event.
*
* @param string $key Name of variable
*
* @param mixed $value Value to variable
*
* @return boolean True
*/
public function __set($key, $value)
{
if (stripos($key, '_') === 0 && isset($this->$key)) {
throw new \LogicException(sprintf(
"%s is a read-only event property",
$key
));
}
$this->$key = $value;
return true;
}
Which will allow for:
$object = new obj();
$object->a = array();
$object->a[] = "b";
$object->v = new obj();
$object->v->a = "b";
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
CGI essentially passes the request off to any interpreter that is configured with the web server - This could be Perl, Python, PHP, Ruby, C pretty much anything. Perl was the most common back in the day thats why you often see it in reference to CGI.
CGI is not dead. In fact most large hosting companies run PHP as CGI as opposed to mod_php because it offers user level config and some other things while it is slower than mod_php. Ruby and Python are also typically run as CGI. they key difference here is that a server module runs as part of the actual server software - where as with CGI its totally outside the server The server just uses the CGI module to determine how to pass and recieve data to the outside interpreter.
HTML is in no way a programming language.
Programming languages deals with ''proccessing functions'', etc. HTML just deals with the visual interface of a web page, where the actual programming handles the proccessing. PHP for example.
If anyone really knows programming, I really can't see how people can mistake HTML for an actual programming language.
I'm not a fan of any of these solutions. I use this instead:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
} else {
// failure
}
I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify
I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.
Wouldn't Collections.disjoint(A, B)
work? From the documentation:
Returns
true
if the two specified collections have no elements in common.
Thus, the method returns false
if the collections contains any common elements.
You should only need to do one of:
inline
(or inline-block
)float
left or rightYou should be able to adjust the height
, padding
, or margin
properties of the smaller heading to compensate for its positioning. I recommend setting both headings to have the same height
.
See this live jsFiddle for an example.
(code of the jsFiddle):
CSS
h2 {
font-size: 50px;
}
h3 {
font-size: 30px;
}
h2, h3 {
width: 50%;
height: 60px;
margin: 0;
padding: 0;
display: inline;
}?
HTML
<h2>Big Heading</h2>
<h3>Small(er) Heading</h3>
<hr />?
It's because of the way NOT IN works.
To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:
SELECT *
FROM Table1 t1
WHERE NOT EXISTS (
SELECT *
FROM Table2 t2
WHERE t1.MAKE = t2.MAKE
AND t1.MODEL = t2.MODEL
AND t1.[Serial Number] = t2.[serial number]);
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Have you verified that there is in fact a row where Staff_Id = @PersonID? What you've posted works fine in a test script, assuming the row exists. If you comment out the insert statement, then the error is raised.
set nocount on
create table Timesheet_Hours (Staff_Id int, BookedHours int, Posted_Flag bit)
insert into Timesheet_Hours (Staff_Id, BookedHours, Posted_Flag) values (1, 5.5, 0)
declare @PersonID int
set @PersonID = 1
IF EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Posted_Flag = 1
AND Staff_Id = @PersonID
)
BEGIN
RAISERROR('Timesheets have already been posted!', 16, 1)
ROLLBACK TRAN
END
ELSE
IF NOT EXISTS
(
SELECT 1
FROM Timesheet_Hours
WHERE Staff_Id = @PersonID
)
BEGIN
RAISERROR('Default list has not been loaded!', 16, 1)
ROLLBACK TRAN
END
ELSE
print 'No problems here'
drop table Timesheet_Hours
final String url = "some/url";
instead of:
final JSONObject jsonBody = "{\"type\":\"example\"}";
you can use:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("type", "my type");
} catch (JSONException e) {
e.printStackTrace();
}
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.
Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.
In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py
However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.
For example, you might run: C:\Python2.5.2\python.exe mymodule
Yet, the environment variables may point to the wrong version as such:
PYTHONPATH = D:\Python27
PYTHONLIB = D:\Python27\lib
Loads of horrible fun!
So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.
Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py
import sys
import subprocess
if sys.argv[2] == '272':
env272 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)
if sys.argv[1] == '252'
env252 = {
'PYTHONPATH': 'blabla',
'PYTHONLIB': 'blabla', }
launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)
I have not tested this.
The approach you've been using indeed does jar file with a string 'testing' in its name, as you specified, but the default install command sends it to your ~/.m2/repository directory, as seen in this output line:
/tmp/mvn_test/my-app/target/my-app-testing.jar to /home/maxim/.m2/repository/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.jar
It seems to me that you're trying to generate a jar with such name and then copy it to a directory of your choice.
Try using outputDirectory property as described here: http://maven.apache.org/plugins/maven-jar-plugin/jar-mojo.html
int strLength = 0;
NSString *urlStr = @"http://www";
NSLog(@" urlStr : %@", urlStr );
NSMutableString *mutableUrlStr = [urlStr mutableCopy];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@":" withString:@"%3A" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
strLength = [mutableUrlStr length];
[mutableUrlStr replaceOccurrencesOfString:@"/" withString:@"%2F" options:NSCaseInsensitiveSearch range:NSMakeRange(0, strLength)];
NSLog(@" mutableUrlStr : %@", mutableUrlStr );
Issues were:
Here is how I fixed it:
IPV6 Disabling
su
and enter to log in as the super usercd /etc/modprobe.d/
to change directory to /etc/modprobe.d/
vi disableipv6.conf
to create a new file thereEsc + i
to insert data to fileinstall ipv6 /bin/true
on the file to avoid loading IPV6 related modulesEsc + :
and then wq
for save and exitreboot
to restart fedoralsmod | grep ipv6
Add Google DNS server
su
and enter to log in as the super usercat /etc/resolv.conf
to check what DNS server your Fedora using. Mostly this will be your Modem IP address.8.8.8.8
and 8.8.4.4
. But in future those may change.vi /etc/resolv.conf
to edit the resolv.conf
fileEsc + i
for insert data to fileType below two lines in the file
nameserver 8.8.8.8
nameserver 8.8.4.4
-Type Esc + :
and then wq
for save and exit
Here is my blog post about this: http://codeketchup.blogspot.sg/2014/07/how-to-fix-curl-6-could-not-resolve.html
If everything else fails, in addition to increasing the max heap size try also increasing the swap size. For Linux, as of now, relevant instructions can be found in https://linuxize.com/post/create-a-linux-swap-file/.
This can help if you're e.g. compiling something big in an embedded platform.
Please Follow this process
First of all install git bash and create a repository on git
1) Go to working directory where the file exist which you want to push on remote and create .git folder by
$ git init
2) Add the files in your new local repository.
$ git add .
Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity
3) Commit the files that you've staged in your local repository.
$ git commit -m "First commit"**
4) after this go to git repository and copy remote URL
$ git remote add origin *remote repository URL
5)
$ git remote -v
Note: this will ask for user.email and user.name just put it as per config
6)
$ git push origin master
this will push whole committed code to FILE.git on repository
And I think we done
How about:
foreach(var s in listBox1.Items.ToArray())
{
MessageBox.Show(s);
//do stuff with (s);
listBox1.Items.Remove(s);
}
The ToArray makes a copy of the list, so you don't need to worry about it changing the list while you are processing it.
ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;
If it is a list of parameters from existing SQL table, for example ID list from existing Table1, then you can try this:
select distinct ID
FROM Table1
where
ID in (1, 1, 1, 2, 5, 1, 6)
ORDER BY ID;
Or, if you need List of parameters as a SQL Table constant(variable), try this:
WITH Id_list AS (
select ID
FROM Table1
where
ID in (1, 1, 1, 2, 5, 1, 6)
)
SELECT distinct * FROM Id_list
ORDER BY ID;
In your controller action rendering the view you could set the As
property of your model to true:
model.As = true;
return View(model);
and in your view simply:
@Html.CheckBoxFor(model => model.As);
Now since the As property of the model is set to true, the CheckBoxFor helper will generate a checked checkbox.
I had the same issue. I used Worksheet
instead of Worksheets
and it was resolved. Not sure what the difference is between them.
It escapes a string that cannot be passed to XML as usual:
Example:
The string contains "&" in it.
You can not:
<FL val="Company Name">Dolce & Gabbana</FL>
Therefore, you must use CDATA:
<FL val="Company Name"> <![CDATA["Dolce & Gabbana"]]> </FL>
For anyone trying to set this for Rails projects, add
set directory=tmp,/tmp
into your
~/.vimrc
So the .swp files will be in their natural location - the tmp directory (per project).
Use Date.Now
instead of DateTime.Now
Probably the simplest way would be to pull the XXX stuff into a branch in YYY and then merge it into master:
In YYY:
git remote add other /path/to/XXX
git fetch other
git checkout -b ZZZ other/master
mkdir ZZZ
git mv stuff ZZZ/stuff # repeat as necessary for each file/dir
git commit -m "Moved stuff to ZZZ"
git checkout master
git merge ZZZ --allow-unrelated-histories # should add ZZZ/ to master
git commit
git remote rm other
git branch -d ZZZ # to get rid of the extra branch before pushing
git push # if you have a remote, that is
I actually just tried this with a couple of my repos and it works. Unlike Jörg's answer it won't let you continue to use the other repo, but I don't think you specified that anyway.
Note: Since this was originally written in 2009, git has added the subtree merge mentioned in the answer below. I would probably use that method today, although of course this method does still work.
I think you should do it the other way round.
Define your Div
s and have your a href
within each Div
, pointing to different links
Enabling Fractions/Cents/Decimals for Number Input
In order to allow fractions (cents) on an HTML5 number input, you need to specify the "step" attribute to = "any":
<input type="number" min="1" step="any" />
This will specifically keep Chrome from displaying an error when a decimal/fractional currency is entered into the input. Mozilla, IE, etc... don't error out if you forget to specify step="any"
. W3C spec states that step="any" should, indeed, be needed to allow for decimals. So, you should definitely use it. https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#step
Note that if you want the up/down buttons to do a specific granularity, then you must specify a numeric step such as ".01".
Also, the number input is now pretty widely supported (>90% of users).
What Input Options are there for Money/Currency?
The title of the question has since changed and takes on a slightly different meaning. One could use both number or text input in order to accept money/decimals.
For an input field for currency/money, it is recommended to use input type of number and specify appropriate attributes as outlined above. As of 2020, there is not a W3C spec for an actual input type of currency or money.
Main reason being it automatically coerces the users into entering a valid standard currency format and disallows any alphanumeric text. With that said, you could certainly use the regular text input and do some post processing to only grab the numeric/decimal value (there should be server side validation on this at some point as well).
The OP detailed a requirement of currency symbols and commas. If you want fancier logic/formatting like that, (as of 2020) you'll need to create custom JS logic for a text input or find a plugin.
Try this code. it worked for me.
function getInvoiceID(url, invoiceId) {
return $.ajax({
type: 'POST',
url: url,
data: { invoiceId: invoiceId },
async: false,
});
}
function isInvoiceIdExists(url, invoiceId) {
$.when(getInvoiceID(url, invoiceId)).done(function (data) {
if (!data) {
}
});
}
You can do this in a number of ways. You can use databinding (typical initialized after InitializeComponent();)
textBox1.DataBindings.Add(new Binding("Text", yourBindingSource,
"TableName.ColumnName", true, DataSourceUpdateMode.OnPropertyChanged));
or use a DataLayoutControl (if you are going to use textbox for editing, I really recommend spending some time to learn how to use this component.
or in FocusedRowChanged by assigning from one of these methods:
textBox1.Text = gridView1.GetDataRow(e.FocusedRowHandle)["Name"].ToString();
textBox1.Text = gridView1.GetFocusedDataRow()["Name"].ToString();
textBox1.Text = (gridView1.GetFocusedRow() as DataRowView).Row["Name"].ToString();
textBox1.Text = gridView1.GetFocusedRowCellValue("Name").ToString();
The best way to understand what the jar file contains is by executing this :
Go to command line and execute jar tvf jarfilename.jar
You can simply use
<a href="directry/filename.html#section5" >click me</a>
to link to a section/id of another page by
If you're on Debian:
1) remove all installed package through Virtualbox Guest Additions ISO file:
sh /media/cdrom/VBoxLinuxAdditions.run uninstall
2) install Virtualbox packages:
apt-get install build-essential module-assistant virtualbox-guest-dkms virtualbox-guest-utils
Note that even with modprobe vboxsf
returning nothing (so the module is correctly loaded), the vboxsf.so
will call an executable named mount.vboxsf
, which is provided by virtualbox-guest-utils
. Ignoring this one will prevent you from understanding the real cause of the error.
strace mount /your-directory
was a great help (No such file or directory on /sbin/mount.vboxsf
).
The "braces" are making an object literal, i.e. they create an object. It is one argument.
Example:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide - Working with Objects.
public class ProductList
{
public string product{get;set;}
public List<ProductList> objList{get;set;}
}
ProductList obj=new ProductList();
obj.objList=new List<ProductList>();
obj.objList.add(new ProductList{product="Football"});
now assign obj to session
Session["Product"]=obj;
for retrieval of session.
ProductList objLst = (ProductList)Session["Product"];
In regards to @bmasterswizzle
's BRILLIANT answer - more specifically - to @DanRamos
' question about how to force the new interface's link-state to "up".. I use this script, of whose origin I cannot recall, but which works fabulously (in coordination with @bmasterswizzles "Mona Lisa" of answers)...
#!/bin/zsh
[[ "$UID" -ne "0" ]] && echo "You must be root. Goodbye..." && exit 1
echo "starting"
exec 4<>/dev/tap0
ifconfig tap0 10.10.10.1 10.10.10.255
ifconfig tap0 up
ping -c1 10.10.10.1
echo "ending"
export PS1="tap interface>"
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null
I am NOT quite sure I understand the alteration to the prompt at the end, or...
dd of=/dev/null <&4 & # continuously reads from buffer and dumps to null
but WHATEVER. it works. link light: green?. loves it.
I've improved a bit the solution written by PaulL. First of all I fixed the code to be compatible with the last Protractor API. And then I declare the function in 'onPrepare' section of a Protractor config file as a member of the browser instance, so it can be referenced form any e2e spec.
onPrepare: function() {
browser._selectDropdownbyNum = function (element, optionNum) {
/* A helper function to select in a dropdown control an option
* with specified number.
*/
return element.all(by.tagName('option')).then(
function(options) {
options[optionNum].click();
});
};
},
Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.
Look here for permanently changing the heap size.
Run this command to show ip4 and ip6:
ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1
As Phoenix said, use jQuery .bind method, but for more browser compatibility you should return a String,
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return "Do you really want to close?";
});
});
more details can be found at : developer.mozilla.org
Also consider java.text.MessageFormat
, which uses a related syntax having numeric argument indexes. For example,
String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);
results in string
containing the following:
A string of ponies.
More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart
label formatting is described here; the class RCInfo
formats a game's status pane.
In Mac OSX, do the following steps:
cd
into the directory of the target file.ls "`pwd`/file.txt"
echo $(pwd)/file.txt
file.txt
with your actual file name.The obligatory answer using XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly
and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.
This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.
To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.
cc -DDISPLAY_STRING demo.c
If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.
#define TERMINAL "/dev/ttyUSB0"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
int set_interface_attribs(int fd, int speed)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetospeed(&tty, (speed_t)speed);
cfsetispeed(&tty, (speed_t)speed);
tty.c_cflag |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~PARENB; /* no parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
/* setup for non-canonical mode */
tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
tty.c_oflag &= ~OPOST;
/* fetch bytes as they become available */
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 1;
if (tcsetattr(fd, TCSANOW, &tty) != 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
return 0;
}
void set_mincount(int fd, int mcount)
{
struct termios tty;
if (tcgetattr(fd, &tty) < 0) {
printf("Error tcgetattr: %s\n", strerror(errno));
return;
}
tty.c_cc[VMIN] = mcount ? 1 : 0;
tty.c_cc[VTIME] = 5; /* half second timer */
if (tcsetattr(fd, TCSANOW, &tty) < 0)
printf("Error tcsetattr: %s\n", strerror(errno));
}
int main()
{
char *portname = TERMINAL;
int fd;
int wlen;
char *xstr = "Hello!\n";
int xlen = strlen(xstr);
fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0) {
printf("Error opening %s: %s\n", portname, strerror(errno));
return -1;
}
/*baudrate 115200, 8 bits, no parity, 1 stop bit */
set_interface_attribs(fd, B115200);
//set_mincount(fd, 0); /* set to pure timed read */
/* simple output */
wlen = write(fd, xstr, xlen);
if (wlen != xlen) {
printf("Error from write: %d, %d\n", wlen, errno);
}
tcdrain(fd); /* delay for output */
/* simple noncanonical input */
do {
unsigned char buf[80];
int rdlen;
rdlen = read(fd, buf, sizeof(buf) - 1);
if (rdlen > 0) {
#ifdef DISPLAY_STRING
buf[rdlen] = 0;
printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
unsigned char *p;
printf("Read %d:", rdlen);
for (p = buf; rdlen-- > 0; p++)
printf(" 0x%x", *p);
printf("\n");
#endif
} else if (rdlen < 0) {
printf("Error from read: %d: %s\n", rdlen, strerror(errno));
} else { /* rdlen == 0 */
printf("Timeout from read\n");
}
/* repeat read to get full message */
} while (1);
}
For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.
You can also try to get the column names from panda data frame that returns columnn name as well dtype. here i'll read csv file from https://mlearn.ics.uci.edu/databases/autos/imports-85.data but you have define header that contain columns names.
import pandas as pd
url="https://mlearn.ics.uci.edu/databases/autos/imports-85.data"
df=pd.read_csv(url,header = None)
headers=["symboling","normalized-losses","make","fuel-type","aspiration","num-of-doors","body-style",
"drive-wheels","engine-location","wheel-base","length","width","height","curb-weight","engine-type",
"num-of-cylinders","engine-size","fuel-system","bore","stroke","compression-ratio","horsepower","peak-rpm"
,"city-mpg","highway-mpg","price"]
df.columns=headers
print df.columns
Follow these steps :
Note: SOAPUI will remove all relative paths and will save all XSDs to the same folder. Refer the screenshot :
c(df$x, df$y)
# returns: 26 21 20 34 29 28
if the particular order is important then:
M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28
Or more generally:
m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
q = c(q, m[i,])
}
# returns 26 34 21 29 20 28
Add servlet-api.jar into your classpath. It will be available into Tomcat's lib folder.
If you want to set Min 1 count and no Max length,
^.{1,}$
1. Include the Open Graph XML namespace extension to your HTML declaration
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="http://ogp.me/ns/fb#">
2. Inside your <head></head>
use the following meta tag to define the image you want to use
<meta property="og:image" content="fully_qualified_image_url_here" />
Read more about open graph protocol here.
After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time
In the toolbar in the bottom right corner you will see a item that looks like the following: After clicking on it you will get the option to indent using either spaces or tabs. After selecting your indent type you will then have the option to change how big an indent is. In the case of the example above, indentation is set to 4 space characters per indent. If tab is selected as your indentation character then you will see Tab Size instead of Spaces
If you want to have this apply to all files and not on an idividual file basis, override the Editor: Tab Size
and Editor: Insert Spaces
settings in either User Settings or Workspace Settings depending on your needs
To get to your user or workspace settings go to Preferences -> Settings. Verify that you are on the User or Workspace tab depending on your needs and use the search bar to locate the settings. You may also want to disable Editor: Detect Indentation
as this setting will override what you set for Editor: Insert Spaces
and Editor: Tab Size
when it is enabled
.format is a more readable way to handle variable formatting:
'{:.{prec}f}'.format(26.034, prec=2)
DO NOT use git push origin --mirror UNDER ALMOST ANY CIRCUMSTANCE.
It does not ask if you're sure you want to do this, and you'd better be sure, because it will erase all of your remote branches that are not on your local box.
Try this:
<select id="sel">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
<input type="button" value="Change option to 2" onclick="changeOpt()"/>
<script>
function changeOpt(){
document.getElementById("sel").options[1].selected = true;
alert("changed")
}
</script>
Are you familiar with other functional languages? i.e. are you trying to learn how python does functional programming, or are you trying to learn about functional programming and using python as the vehicle?
Also, do you understand list comprehensions?
map(f, sequence)
is directly equivalent (*) to:
[f(x) for x in sequence]
In fact, I think map()
was once slated for removal from python 3.0 as being redundant (that didn't happen).
map(f, sequence1, sequence2)
is mostly equivalent to:
[f(x1, x2) for x1, x2 in zip(sequence1, sequence2)]
(there is a difference in how it handles the case where the sequences are of different length. As you saw, map()
fills in None when one of the sequences runs out, whereas zip()
stops when the shortest sequence stops)
So, to address your specific question, you're trying to produce the result:
foos[0], bars
foos[1], bars
foos[2], bars
# etc.
You could do this by writing a function that takes a single argument and prints it, followed by bars:
def maptest(x):
print x, bars
map(maptest, foos)
Alternatively, you could create a list that looks like this:
[bars, bars, bars, ] # etc.
and use your original maptest:
def maptest(x, y):
print x, y
One way to do this would be to explicitely build the list beforehand:
barses = [bars] * len(foos)
map(maptest, foos, barses)
Alternatively, you could pull in the itertools
module. itertools
contains many clever functions that help you do functional-style lazy-evaluation programming in python. In this case, we want itertools.repeat
, which will output its argument indefinitely as you iterate over it. This last fact means that if you do:
map(maptest, foos, itertools.repeat(bars))
you will get endless output, since map()
keeps going as long as one of the arguments is still producing output. However, itertools.imap
is just like map()
, but stops as soon as the shortest iterable stops.
itertools.imap(maptest, foos, itertools.repeat(bars))
Hope this helps :-)
(*) It's a little different in python 3.0. There, map() essentially returns a generator expression.
For now, If you want to move a column over just 4 column units for instance, I would suggest to use just a dummy placeholder like in my example below
<div class="row">
<div class="col-md-4">Offset 4 column</div>
<div class="col-md-8">
//content
</div>
</div>
You want to use:
git checkout --ours foo/bar.java
git add foo/bar.java
If you rebase a branch feature_x
against main
(i.e. running git rebase main
while on branch feature_x
), during rebasing ours
refers to main
and theirs
to feature_x
.
As pointed out in the git-rebase docs:
Note that a rebase merge works by replaying each commit from the working branch on top of the branch. Because of this, when a merge conflict happens, the side reported as ours is the so-far rebased series, starting with <upstream>, and theirs is the working branch. In other words, the sides are swapped.
For further details read this thread.
Do not set cnopts.hostkeys = None
(as the second most upvoted answer shows), unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.
Use CnOpts.hostkeys
(returns HostKeys
) to manage trusted host keys.
cnopts = pysftp.CnOpts(knownhosts='known_hosts')
with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:
where the known_hosts
contains a server public key(s)] in a format like:
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...
If you do not want to use an external file, you can also use
from base64 import decodebytes
# ...
keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add('example.com', 'ssh-rsa', key)
with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:
Though as of pysftp 0.2.9, this approach will issue a warning, what seems like a bug:
"Failed to load HostKeys" warning while connecting to SFTP server with pysftp
An easy way to retrieve the host key in the needed format is using OpenSSH ssh-keyscan
:
$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...
(due to a bug in pysftp, this does not work, if the server uses non-standard port – the entry starts with [example.com]:port
+ beware of redirecting ssh-keyscan
to a file in PowerShell)
You can also make the application do the same automatically:
Use Paramiko AutoAddPolicy with pysftp
(It will automatically add host keys of new hosts to known_hosts
, but for known host keys, it will not accept a changed key)
Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.
See my article Where do I get SSH host key fingerprint to authorize the server?
It's for my WinSCP SFTP client, but most information there is valid in general.
If you need to verify the host key using its fingerprint only, see Python - pysftp / paramiko - Verify host key using its fingerprint.
If you want to easily view the contents of objects while debugging, install a tool like Firebug and use console.log
:
console.log(product);
If you want to view the properties of the object itself, don't alert
the object, but its properties:
alert(product.ProductName);
alert(product.UnitPrice);
// etc... (or combine them)
As said, if you really want to boost your JavaScript debugging, use Firefox with the Firebug addon. You will wonder how you ever debugged your code before.
If your project is a single page application, (eg project created by vue init webpack myproject
),
I found this way is most intuitive and simple:
In main.js
import moment from 'moment'
Vue.prototype.moment = moment
Then in your template, simply use
<span>{{moment(date).format('YYYY-MM-DD')}}</span>
It doesn't make any sense to have a named overloaded constructor in an anonymous class, as there would be no way to call it, anyway.
Depending on what you are actually trying to do, just accessing a final local variable declared outside the class, or using an instance initializer as shown by Arne, might be the best solution.
The below example shows how to read the text in the question, represented as the "jsonText" variable. This solution uses the Java EE7 javax.json API (which is mentioned in some of the other answers). The reason I've added it as a separate answer is that the following code shows how to actually access some of the values shown in the question. An implementation of the javax.json API would be required to make this code run. The full package for each of the classes required was included as I didn't want to declare "import" statements.
javax.json.JsonReader jr =
javax.json.Json.createReader(new StringReader(jsonText));
javax.json.JsonObject jo = jr.readObject();
//Read the page info.
javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
System.out.println(pageInfo.getString("pageName"));
//Read the posts.
javax.json.JsonArray posts = jo.getJsonArray("posts");
//Read the first post.
javax.json.JsonObject post = posts.getJsonObject(0);
//Read the post_id field.
String postId = post.getString("post_id");
Now, before anyone goes and downvotes this answer because it doesn't use GSON, org.json, Jackson, or any of the other 3rd party frameworks available, it's an example of "required code" per the question to parse the provided text. I am well aware that adherence to the current standard JSR 353 was not being considered for JDK 9 and as such the JSR 353 spec should be treated the same as any other 3rd party JSON handling implementation.
<i>
is not wrong because it is non-semantic. It's wrong (usually) because it's presentational. Separation of concern means that presentional information should be conveyed with CSS.
Naming in general can be tricky to get right, and class names are no exception, but nevertheless it's what you have to do. If you're using italics to make a block stand out from the body text, then maybe a class name of "flow-distinctive" would be in order. Think about reuse: class names are for categorization - where else would you want to do the same thing? That should help you identify a suitable name.
<i>
is included in HTML5, but it is given specific semantics. If the reason why you are marking something up as italic meets one of the semantics identified in the spec, it would be appropriate to use <i>
. Otherwise not.
Try something like this:
<html>
<body>
<script type="text/javascript">
function doSomething(event) {
var source = event.target || event.srcElement;
console.log(source);
alert('test');
if(window.event) {
// IE8 and earlier
// doSomething
} else if(e.which) {
// IE9/Firefox/Chrome/Opera/Safari
// doSomething
}
}
</script>
<button onclick="doSomething('param')" id="id_button">
action
</button>
</body>
</html>
Both Date
and moment
will parse the input string in the local time zone of the browser by default. However Date
is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD
, using hyphens, or if it is YYYY-MM-DD HH:mm:ss
, it will interpret it as local time. Unlike Date
, moment
will always be consistent about how it parses.
The correct way to parse an input moment as UTC in the format you provided would be like this:
moment.utc('07-18-2013', 'MM-DD-YYYY')
Refer to this documentation.
If you want to then format it differently for output, you would do this:
moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')
You do not need to call toString
explicitly.
Note that it is very important to provide the input format. Without it, a date like 01-04-2013
might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.
If you need a Win 10 UWP compatible variant:
using DomXmlDocument = Windows.Data.Xml.Dom.XmlDocument;
public static class DocumentExtensions
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.Load(xmlReader);
}
return xmlDocument;
}
public static DomXmlDocument ToDomXmlDocument(this XDocument xDocument)
{
var xmlDocument = new DomXmlDocument();
using (var xmlReader = xDocument.CreateReader())
{
xmlDocument.LoadXml(xmlReader.ReadOuterXml());
}
return xmlDocument;
}
public static XDocument ToXDocument(this XmlDocument xmlDocument)
{
using (var memStream = new MemoryStream())
{
using (var w = XmlWriter.Create(memStream))
{
xmlDocument.WriteContentTo(w);
}
memStream.Seek(0, SeekOrigin.Begin);
using (var r = XmlReader.Create(memStream))
{
return XDocument.Load(r);
}
}
}
public static XDocument ToXDocument(this DomXmlDocument xmlDocument)
{
using (var memStream = new MemoryStream())
{
using (var w = XmlWriter.Create(memStream))
{
w.WriteRaw(xmlDocument.GetXml());
}
memStream.Seek(0, SeekOrigin.Begin);
using (var r = XmlReader.Create(memStream))
{
return XDocument.Load(r);
}
}
}
}
For mac, shift+alt+down_arrow works in netbeans' editor.
SELECT MIN(COLUMN_NAME)
FROM (
SELECT DISTINCT TOP 3 COLUMN_NAME
FROM TABLE_NAME
ORDER BY
COLUMN_NAME DESC
) AS 'COLUMN_NAME'
If the entire program should stop use sys.exit() otherwise just use an empty return.
Join-Path is not exactly what you are looking for. It has multiple uses but not the one you are looking for. An example from Partying with Join-Path:
Join-Path C:\hello,d:\goodbye,e:\hola,f:\adios world
C:\hello\world
d:\goodbye\world
e:\hola\world
f:\adios\world
You see that it accepts an array of strings, and it concatenates the child string to each creating full paths. In your example, $path = join-path C: "Program Files" "Microsoft Office"
. You are getting the error since you are passing three positional arguments and join-path
only accepts two. What you are looking for is a -join
, and I could see this being a misunderstanding. Consider instead this with your example:
"C:","Program Files","Microsoft Office" -join "\"
-Join
takes the array of items and concatenates them with \
into a single string.
C:\Program Files\Microsoft Office
Minor attempt at a salvage
Yes, I will agree that this answer is better, but mine could still work. Comments suggest there could be an issue with slashes, so to keep with my concatenation approach you could do this as well.
"C:","\\Program Files\","Microsoft Office\" -join "\" -replace "(?!^\\)\\{2,}","\"
So if there are issues with extra slashes it could be handled as long as they are not in the beginning of the string (allows UNC paths). [io.path]::combine('c:\', 'foo', '\bar\')
would not work as expected and mine would account for that. Both require proper strings for input as you cannot account for all scenarios. Consider both approaches, but, yes, the other higher-rated answer is more terse, and I didn't even know it existed.
Also, would like to point out, my answer explains how what the OP doing was wrong on top of providing a suggestion to address the core problem.
Dirkgently gives an excellent description of integer division in C99, but you should also know that in C89 integer division with a negative operand has an implementation-defined direction.
From the ANSI C draft (3.3.5):
If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined, as is the sign of the result of the % operator. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.
So watch out with negative numbers when you are stuck with a C89 compiler.
It's a fun fact that C99 chose truncation towards zero because that was how FORTRAN did it. See this message on comp.std.c.
Don't abuse form elements where <a> elements will suffice.
<style>
/* or put this in your stylesheet */
.button {
display: inline-block;
padding: 3px 5px;
border: 1px solid #000;
background: #eee;
}
</style>
<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>
In later versions (tested with TensorFlow 1.14) there's a more numpy-like way to get the shape of a tensor. You can use tensor.shape
to get the shape of the tensor.
tensor_shape = tensor.shape
print(tensor_shape)
The problem is that you do not have a public void main(String[] args)
method in the class you attempt to invoke.
It
static
Note, that you HAVE actually specified an existing class (otherwise the error would have been different), but that class lacks the main method.
Use a DecimalFormat object with a format string of "0.#".
The answer is "nowhere" since the date formatting is proprietary functionality. I don't think the toString functions are intended to conform to a specific format. e.g. in the ECMAScript 5.1 spec (http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, 2/8/2013, page 173), the toString function is documented as follows:
"The contents of the String are implementation-dependent"
Functions such as the samples below could be used to accomplish formatting fairly easily.
function pad(toPad, padWith) {
return (String(padWith) + String(toPad)).slice(-1 * padWith.length);
}
function dateAsInputValue(toFormat) {
if(!(toFormat instanceof Date)) return null;
return toFormat.getFullYear() + "-" + pad(toFormat.getMonth() + 1, "00") + "-" + pad(toFormat.getDate(), "00");
}
function timeAsInputValue(toFormat) {
if(!(toFormat instanceof Date)) return null;
return pad(toFormat.getHours(), "00") + ":" + pad(toFormat.getMinutes(), "00") + ":" + pad(toFormat.getSeconds(), "00");
}
Just added to the answer from Kunal Mathur and an answer to @mockash, since I cannot comment due to lack of reputation.
Before you type: pip install package_name, you need to change the directory to the folder where pip.exe is. for example:
Open Visual C++ 2015 x86 x64 Cross Build Tools Command Prompt--> change directory cd C:\Users\Test\AppData\Local\Programs\Python\Python36-32\Scripts-->Type: pip install package_name
But the weird thing is I can only successfully install via 'Visual C++ 2015 x64 x86' not 'x86 x64'
Using .enumerate()
works, but it does not provide the true index of the element; it only provides an Int beginning with 0 and incrementing by 1 for each successive element. This is usually irrelevant, but there is the potential for unexpected behavior when used with the ArraySlice
type. Take the following code:
let a = ["a", "b", "c", "d", "e"]
a.indices //=> 0..<5
let aSlice = a[1..<4] //=> ArraySlice with ["b", "c", "d"]
aSlice.indices //=> 1..<4
var test = [Int: String]()
for (index, element) in aSlice.enumerate() {
test[index] = element
}
test //=> [0: "b", 1: "c", 2: "d"] // indices presented as 0..<3, but they are actually 1..<4
test[0] == aSlice[0] // ERROR: out of bounds
It's a somewhat contrived example, and it's not a common issue in practice but still I think it's worth knowing this can happen.
As Kaboing mentioned, MAXDOP(n)
actually controls the number of CPU cores that are being used in the query processor.
On a completely idle system, SQL Server will attempt to pull the tables into memory as quickly as possible and join between them in memory. It could be that, in your case, it's best to do this with a single CPU. This might have the same effect as using OPTION (FORCE ORDER)
which forces the query optimizer to use the order of joins that you have specified. IN some cases, I have seen OPTION (FORCE PLAN)
reduce a query from 26 seconds to 1 second of execution time.
Books Online goes on to say that possible values for MAXDOP
are:
0 - Uses the actual number of available CPUs depending on the current system workload. This is the default value and recommended setting.
1 - Suppresses parallel plan generation. The operation will be executed serially.
2-64 - Limits the number of processors to the specified value. Fewer processors may be used depending on the current workload. If a value larger than the number of available CPUs is specified, the actual number of available CPUs is used.
I'm not sure what the best usage of MAXDOP
is, however I would take a guess and say that if you have a table with 8 partitions on it, you would want to specify MAXDOP(8)
due to I/O limitations, but I could be wrong.
Here are a few quick links I found about MAXDOP
:
What I do is precalculate the three face normals,
in 3D by cross product of side vector and the face normal vector.
in 2D by simply swapping components and negating one,
then inside/outside for any one side is when a dot product of the side normal and the vertex to point vector, change sign. Repeat for other two (or more) sides.
Benefits:
a lot is precalculated so great for multiple point testing on same triangle.
early rejection of common case of more outside than inside points. (also if point distribution weighted to one side, can test that side first.)
Opacity serves your purpose?
If so, try this:
$('#elem').css('opacity','0.3')
The original conio.h was implemented by Borland, so its not a part of the C Standard Library nor is defined by POSIX.
But here is an implementation for Linux that uses ncurses to do the job.
You have to initialize the vector of vectors to the appropriate size before accessing any elements. You can do it like this:
// assumes using std::vector for brevity
vector<vector<int>> matrix(RR, vector<int>(CC));
This creates a vector of RR
size CC
vectors, filled with 0
.
Visual Studio 2015:
Tools > Options > Settings > Environment > Keyboard
Defaults:
Edit.CollapsetoDefinitions: CTRL + M + O
Edit.CollapseCurrentRegion: CTRL + M +CTRL + S
Edit.ExpandAllOutlining: CTRL + M + CTRL + X
Edit.ExpandCurrentRegion: CTRL + M + CTRL + E
I like to set and use IntelliJ's shortcuts:
Edit.CollapsetoDefinitions: CTRL + SHIFT + NUM-
Edit.CollapseCurrentRegion: CTRL + NUM-
Edit.ExpandAllOutlining: CTRL + SHIFT + NUM+
Edit.ExpandCurrentRegion: CTRL + NUM+
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Esperento57's script doesn't work in older PowerShell versions. This example does:
Get-ChildItem -Path "C:\temp" -Recurse -force -ErrorAction SilentlyContinue | where {($_.LastwriteTime -lt (Get-Date).AddDays(-15) ) -and (! $_.PSIsContainer)} | select name| Remove-Item -Verbose -Force -Recurse -ErrorAction SilentlyContinue
Here's a custom theme to make the ggplot2 background white and a bunch of other changes that's good for publications and posters. Just tack on +mytheme. If you want to add or change options by +theme after +mytheme, it will just replace those options from +mytheme.
library(ggplot2)
library(cowplot)
theme_set(theme_cowplot())
mytheme = list(
theme_classic()+
theme(panel.background = element_blank(),strip.background = element_rect(colour=NA, fill=NA),panel.border = element_rect(fill = NA, color = "black"),
legend.title = element_blank(),legend.position="bottom", strip.text = element_text(face="bold", size=9),
axis.text=element_text(face="bold"),axis.title = element_text(face="bold"),plot.title = element_text(face = "bold", hjust = 0.5,size=13))
)
ggplot(data=data.frame(a=c(1,2,3), b=c(2,3,4)), aes(x=a, y=b)) + mytheme + geom_line()
The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).
1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.
The gradle guys are doing their best to solve all (y)our problems ;-). They recently (since 1.9) added a new feature (incubating): the "build init" plugin.
This command did it for me:
zip -r Target.zip Source -x "*.DS_Store"
Target.zip
is the zip file to create. Source
is the source file/folder to zip up. And the _x
parameter specifies the file/folder to not include. If the above doesn't work for whatever reason, try this instead:
zip -r Target.zip Source -x "*.DS_Store" -x "__MACOSX"
If you are in SQL*Plus or SQL Developer, you want to run
SQL> set define off;
before executing the SQL statement. That turns off the checking for substitution variables.
SET directives like this are instructions for the client tool (SQL*Plus or SQL Developer). They have session scope, so you would have to issue the directive every time you connect (you can put the directive in your client machine's glogin.sql if you want to change the default to have DEFINE set to OFF). There is no risk that you would impact any other user or session in the database.
org.junit.Assert.assertEquals()
and org.junit.Assert.assertArrayEquals()
do the job.
To avoid next questions: If you want to ignore the order put all elements to set and then compare: Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))
If however you just want to ignore duplicates but preserve the order wrap you list with LinkedHashSet
.
Yet another tip. The trick Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))
works fine until the comparison fails. In this case it shows you error message with to string representations of your sets that can be confusing because the order in set is almost not predictable (at least for complex objects). So, the trick I found is to wrap the collection with sorted set instead of HashSet
. You can use TreeSet
with custom comparator.
You can use regular expressions for this, so I think this is what you want:
select t.*
from test t
where not regexp_like(sampletext, '.*[^a-zA-Z0-9 .{}\[\]].*')
I have seen JMS used in different commercial and academic projects. JMS can easily come into your picture, whenever you want to have a totally decoupled distributed systems. Generally speaking, when you need to send your request from one node, and someone in your network takes care of it without/with giving the sender any information about the receiver.
In my case, I have used JMS in developing a message-oriented middleware (MOM) in my thesis, where specific types of object-oriented objects are generated in one side as your request, and compiled and executed on the other side as your response.
I am reading a book (Effective Python) by Brett Slatkin and he shows another way to iterate over a list and also know the index of the current item in the list but he suggests that it is better not to use it and to use enumerate
instead.
I know you asked what enumerate means, but when I understood the following, I also understood how enumerate
makes iterating over a list while knowing the index of the current item easier (and more readable).
list_of_letters = ['a', 'b', 'c']
for i in range(len(list_of_letters)):
letter = list_of_letters[i]
print (i, letter)
The output is:
0 a
1 b
2 c
I also used to do something, even sillier before I read about the enumerate
function.
i = 0
for n in list_of_letters:
print (i, n)
i += 1
It produces the same output.
But with enumerate
I just have to write:
list_of_letters = ['a', 'b', 'c']
for i, letter in enumerate(list_of_letters):
print (i, letter)
Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:
The concept of leading zero is meaningless for an int, which is what you have. It is only meaningful, when printed out or otherwise rendered as a string.
Console.WriteLine("{0:0000000}", FileRecordCount);
Forgot to end the double quotes!
That offset is basically the x,y position that the browser has calculated for the element based on it's position css attribute. So if you put a <br>
before it or any other element, it would change the offset. For example, you could set it to 0 by:
#inputBox{position:absolute;top:0px;left:0px;}
or
#inputBox{position:relative;top:-12px;left:-2px;}
Therefore, whatever positioning issue you have, is not necessarily an issue with offset, though you could always fix it by playing with the top,left,right and bottom attributes.
Is your problem browser incompatibility?
I've created a couple of map tutorials that will cover what you need
Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.
Take a look at these 2 tutorials and the Github project containing the sample app.
It contains some tips to make your code cleaner and more efficient:
Interesting link: Why use a VARCHAR when you can use TEXT?
It's about PostgreSQL and MySQL, so the performance analysis is different, but the logic for "explicitness" still holds: Why force yourself to always worry about something that's relevant a small percentage of the time? If you saved an email address to a variable, you'd use a 'string' not a 'string limited to 80 chars'.
The underlying urllib3
library logs all new connections and URLs with the logging
module, but not POST
bodies. For GET
requests this should be enough:
import logging
logging.basicConfig(level=logging.DEBUG)
which gives you the most verbose logging option; see the logging HOWTO for more details on how to configure logging levels and destinations.
Short demo:
>>> import requests
>>> import logging
>>> logging.basicConfig(level=logging.DEBUG)
>>> r = requests.get('http://httpbin.org/get?foo=bar&baz=python')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org:80
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "GET /get?foo=bar&baz=python HTTP/1.1" 200 366
Depending on the exact version of urllib3, the following messages are logged:
INFO
: RedirectsWARN
: Connection pool full (if this happens often increase the connection pool size)WARN
: Failed to parse headers (response headers with invalid format)WARN
: Retrying the connectionWARN
: Certificate did not match expected hostnameWARN
: Received response with both Content-Length and Transfer-Encoding, when processing a chunked responseDEBUG
: New connections (HTTP or HTTPS)DEBUG
: Dropped connectionsDEBUG
: Connection details: method, path, HTTP version, status code and response lengthDEBUG
: Retry count incrementsThis doesn't include headers or bodies. urllib3
uses the http.client.HTTPConnection
class to do the grunt-work, but that class doesn't support logging, it can normally only be configured to print to stdout. However, you can rig it to send all debug information to logging instead by introducing an alternative print
name into that module:
import logging
import http.client
httpclient_logger = logging.getLogger("http.client")
def httpclient_logging_patch(level=logging.DEBUG):
"""Enable HTTPConnection debug logging to the logging framework"""
def httpclient_log(*args):
httpclient_logger.log(level, " ".join(args))
# mask the print() built-in in the http.client module to use
# logging instead
http.client.print = httpclient_log
# enable debugging
http.client.HTTPConnection.debuglevel = 1
Calling httpclient_logging_patch()
causes http.client
connections to output all debug information to a standard logger, and so are picked up by logging.basicConfig()
:
>>> httpclient_logging_patch()
>>> r = requests.get('http://httpbin.org/get?foo=bar&baz=python')
DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): httpbin.org:80
DEBUG:http.client:send: b'GET /get?foo=bar&baz=python HTTP/1.1\r\nHost: httpbin.org\r\nUser-Agent: python-requests/2.22.0\r\nAccept-Encoding: gzip, deflate\r\nAccept: */*\r\nConnection: keep-alive\r\n\r\n'
DEBUG:http.client:reply: 'HTTP/1.1 200 OK\r\n'
DEBUG:http.client:header: Date: Tue, 04 Feb 2020 13:36:53 GMT
DEBUG:http.client:header: Content-Type: application/json
DEBUG:http.client:header: Content-Length: 366
DEBUG:http.client:header: Connection: keep-alive
DEBUG:http.client:header: Server: gunicorn/19.9.0
DEBUG:http.client:header: Access-Control-Allow-Origin: *
DEBUG:http.client:header: Access-Control-Allow-Credentials: true
DEBUG:urllib3.connectionpool:http://httpbin.org:80 "GET /get?foo=bar&baz=python HTTP/1.1" 200 366
This helps for me after i remove read only flag from bin directory. http://www.thewindowsclub.com/error-0x80080015-windows-defender-activation-requires-display-name
You can make use of DecimalFormat
to give you the style you wish.
DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number)); // prints 1.30E7
Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.
Assuming you have other data types (and not only string) in your list try this. This removes trailing and leading zeros from strings and leaves other data types untouched. This also handles the special case s = '0'
e.g
a = ['001', '200', 'akdl00', 200, 100, '0']
b = [(lambda x: x.strip('0') if isinstance(x,str) and len(x) != 1 else x)(x) for x in a]
b
>>>['1', '2', 'akdl', 200, 100, '0']
I recommend setting the display options inside a context manager so that it only affects a single output. I usually prefer "pretty" html-output, and define a function force_show_all(df)
for displaying the DataFrame df
:
from IPython.core.display import display, HTML
def force_show_all(df):
with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.width', None):
display(HTML(df.to_html()))
# ... now when you're ready to fully display df:
force_show_all(df)
As others have mentioned, please be cautious to only call this on a reasonably-sized dataframe.
You can also capture jquery ready event this way:
$('#iframeid').ready(function () {
//Everything you need.
});
Here is a working example:
If you're using getline
after cin >> something
, you need to flush the newline out of the buffer in between.
My personal favourite for this if no characters past the newline are needed is cin.sync()
. However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore()
. Or make use of std::ws
to remove leading whitespace if desirable:
int a;
cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
//discard characters until newline is found
//my method: cin.sync(); //discard unread characters
string s;
getline (cin, s); //newline is gone, so this executes
//other method: getline(cin >> ws, s); //remove all leading whitespace
First add the collections and then apply lookup on these collections. Don't use $unwind
as unwind will simply separate all the documents of each collections. So apply simple lookup and then use $project
for projection.
Here is mongoDB query:
db.userInfo.aggregate([
{
$lookup: {
from: "userRole",
localField: "userId",
foreignField: "userId",
as: "userRole"
}
},
{
$lookup: {
from: "userInfo",
localField: "userId",
foreignField: "userId",
as: "userInfo"
}
},
{$project: {
"_id":0,
"userRole._id":0,
"userInfo._id":0
}
} ])
Here is the output:
/* 1 */ {
"userId" : "AD",
"phone" : "0000000000",
"userRole" : [
{
"userId" : "AD",
"role" : "admin"
}
],
"userInfo" : [
{
"userId" : "AD",
"phone" : "0000000000"
}
] }
Thanks.