@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
Nothing worked for me until I encoded the video properly. Try this guide for the correct handbrake settings: http://forum.handbrake.fr/viewtopic.php?f=7&t=9694
You could also change your PYTHONPATH:
$ python -c 'import dateutil'
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named dateutil
$
$ PYTHONPATH="/usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg":"${PYTHONPATH}"
$ export PYTHONPATH
$ python -c 'import dateutil'
$
Where /usr/lib/python2.6/site-packages/python_dateutil-1.5-py2.6.egg
is the place dateutil was installed in my box (centos using sudo yum install python-dateutil15
)
In most cases, you shouldn't use a regex for that.
os.path.splitext(filename)[0]
This will also handle a filename like .bashrc
correctly by keeping the whole name.
Use the pdfpages
package.
\usepackage{pdfpages}
To include all the pages in the PDF file:
\includepdf[pages=-]{myfile.pdf}
To include just the first page of a PDF:
\includepdf[pages={1}]{myfile.pdf}
Run texdoc pdfpages
in a shell to see the complete manual for pdfpages
.
If you use two times vue instance. Then it will give you this error. For example in app.js and your own script tag in view file. Just use one time
const app = new Vue({
el: '#app',
});
Have you considered applying ON DELETE CASCADE
where relevant?
As per the documentation:
@dynamic tells the compiler that the accessor methods are provided at runtime.
With a little bit of investigation I found out that providing accessor methods override the @dynamic directive.
@synthesize tells the compiler to create those accessors for you (getter and setter)
@property tells the compiler that the accessors will be created, and that can be accessed with the dot notation or [object message]
With urlsearchparams:
const params = new URLSearchParams()
params.append('imageurl', http://www.image.com/?username=unknown&password=unknown)
return `http://www.foobar.com/foo?${params.toString()}`
public class JsonMapExample {
public static void main(String[] args) {
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
Map<String, String> map = new HashMap<String, String>();
ObjectMapper mapper = new ObjectMapper();
try {
//convert JSON string to Map
map = mapper.readValue(json, new TypeReference<HashMap<String, String>>() {});
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
{phonetype=N95, cat=WP}
You can see this link it's helpful http://www.mkyong.com/java/how-to-convert-java-map-to-from-json-jackson/
Switch the alloc type:
GCHandle handle = GCHandle.Alloc(a, GCHandleType.Normal);
That would be:
b.rstrip('\n')
If you want to strip space from each and every line, you might consider instead:
a.read().splitlines()
This will give you a list of lines, without the line end characters.
i have a more simple way to determine weather a url is valid.
if (Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
{
//...
}
In case you want to improve the commit message with header and body after you created the commit, you can reword it. This approach is more useful because you know what the code does only after you wrote it.
git rebase -i origin/master
Then, your commits will appear:
pick e152ce2 Update framework
pick ffcf91e Some magic
pick fa672e1 Update comments
Select the commit you want to reword and save.
pick e152ce2 Update framework
reword ffcf91e Some magic
pick fa672e1 Update comments
Now, you have the opportunity to add header and body, where the first line will be the header.
Create perpetuum mobile
Redesign laws of physics with a pinch of imagination. Open a wormhole in 23 dimensions. Add protection to avoid high instability.
Arrays can hold pointers so when I want an array of objects I do that.
$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);
This will show that the object is referenced and accessible through the array.
Just put this in your batch file where you want the wait.
@ping 127.0.0.1 -n 11 -w 1000 > null
Solution is very simple
Just put following line into your style named as AppTheme
<item name="colorControlNormal">@color/white</item>
Now your whole xml code will look like shown below (default style).
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#0F0F0F</item>
<item name="android:statusBarColor">#EEEEF0</item>
<item name="android:windowLightStatusBar">true</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowActivityTransitions">true</item>
<item name="colorControlNormal">@color/white</item>
</style>
Simplest of all would be.
Create xml layout file for dialog . Add whatever view you want like EditText , ListView , Spinner etc.
Inflate this view and set this to AlertDialog
Lets start with Layout file first.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<EditText
android:id="@+id/etComments"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="top"
android:hint="Enter comments(Optional)"
android:inputType="textMultiLine"
android:lines="8"
android:maxLines="3"
android:minLines="6"
android:scrollbars="vertical" />
</LinearLayout>
final View view = layoutInflater.inflate(R.layout.xml_file_created_above, null);
AlertDialog alertDialog = new AlertDialog.Builder(ct).create();
alertDialog.setTitle("Your Title Here");
alertDialog.setIcon("Icon id here");
alertDialog.setCancelable(false);
Constant.alertDialog.setMessage("Your Message Here");
final EditText etComments = (EditText) view.findViewById(R.id.etComments);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss()
}
});
alertDialog.setView(view);
alertDialog.show();
Here is a script you can use to merge your master branch into your current branch.
The script does the following:
Save this code as a batch file (.bat) and place the script anywhere in your repository. Then click on it to run it and you are set.
:: This batch file pulls current master and merges into current branch
@echo off
:: Option to use the batch file outside the repo and pass the repo path as an arg
set repoPath=%1
cd %repoPath%
FOR /F "tokens=*" %%g IN ('git rev-parse --abbrev-ref HEAD') do (SET currentBranch=%%g)
echo current branch is %currentBranch%
echo switching to master
git checkout master
echo.
echo pulling origin master
git pull origin master
echo.
echo switching back to %currentBranch%
git checkout %currentBranch%
echo.
echo attemting merge master into %currentBranch%
git merge master
echo.
echo script finished successfully
PAUSE
Maven needs to be able to access various Maven repositories in order to download artifacts to the local repository. If your local system is accessing the Internet through a proxy host, you might need to explicitly specify the proxy settings for Maven by editing the Maven settings.xml
file. Maven builds ignore the IDE proxy settings that are set in the Options window.
For many common cases, just passing -Djava.net.useSystemProxies=true
to Maven should suffice to download artifacts through the system's configured proxy. NetBeans 7.1 will offer to configure this flag for you if it detects a possible proxy problem. https://netbeans.org/bugzilla/show_bug.cgi?id=194916 has discussion.
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
I have modified few changes related to Patrick Kostjens.
<a href="#">
<img src="http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png"
onmouseover="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/red-bird-icon.png'"
onmouseout="this.src='http://icons.iconarchive.com/icons/fasticon/angry-birds/128/yellow-bird-icon.png'"
border="0" alt=""/></a>
DEMO
The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.
If you view the code that is used for the demo website and basically copy/paste, you'll be fine.
To get an inline Fancybox working, you will need to have this code present in your index.html file:
<head>
<link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
<script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#various1").fancybox({
'titlePosition' : 'inside',
'transitionIn' : 'none',
'transitionOut' : 'none'
});
});
</script>
</head>
<body>
<a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
<div style="display: none;">
<div id="inline1" style="width:400px;height:100px;overflow:auto;">
Write whatever text you want right here!!
</div>
</div>
</body>
Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.
Python 3 includes an improved super() which allows use like this:
super().__init__(args)
aca definis los anchos
float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};
aca se los insertas a la tabla que tiene las columnas
table.setWidths(anchoDeColumnas);
Step1: rename the file from oldfile to newfile
git mv #oldfile #newfile
Step2: git commit and add comments
git commit -m "rename oldfile to newfile"
Step3: push this change to remote sever
git push origin #localbranch:#remotebranch
First you should take a note about difference between git am
and git apply
When you are using git am
you usually wanna to apply many patches. Thus should use:
git am *.patch
or just:
git am
Git will find patches automatically and apply them in order ;-)
UPD
Here you can find how to generate such patches
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
Whether something is a "checked exception" has nothing to do with whether you catch it or what you do in the catch block. It's a property of exception classes. Anything that is a subclass of Exception
except for RuntimeException
and its subclasses is a checked exception.
The Java compiler forces you to either catch checked exceptions or declare them in the method signature. It was supposed to improve program safety, but the majority opinion seems to be that it's not worth the design problems it creates.
Why do they let the exception bubble up? Isnt handle error the sooner the better? Why bubble up?
Because that's the entire point of exceptions. Without this possibility, you would not need exceptions. They enable you to handle errors at a level you choose, rather than forcing you to deal with them in low-level methods where they originally occur.
You need a spring-security-config.jar
on your classpath.
The exception means that the security:
xml namescape cannot be handled by spring "parsers". They are implementations of the NamespaceHandler
interface, so you need a handler that knows how to process <security:
tags. That's the SecurityNamespaceHandler
located in spring-security-config
It seems that you have a bunch of describe
s that never have end
s keywords, starting with describe "when email format is invalid" do
until describe "when email address is already taken" do
Put an end on those guys and you're probably done =)
Upvoted answer din't work for me, It was fixed by editing connection line as follows(replace semicolons with coma and also remove those quotes):
import pyodbc
cnxn = pyodbc.connect(DRIVER='{SQL Server}',SERVER=SQLSRV01,DATABASE=DATABASE,UID=USER,PWD=PASSWORD)
cursor = cnxn.cursor()
cursor.execute("SELECT WORK_ORDER.TYPE,WORK_ORDER.STATUS, WORK_ORDER.BASE_ID, WORK_ORDER.LOT_ID FROM WORK_ORDER")
for row in cursor.fetchall():
print row
The only alternative to using a loop is to use recursion.
You can define a method like
public static int sum(List<Integer> ints) {
return ints.isEmpty() ? 0 : ints.get(0) + ints.subList(1, ints.length());
}
This is very inefficient compared to using a plain loop and can blow up if you have many elements in the list.
An alternative which avoid a stack overflow is to use.
public static int sum(List<Integer> ints) {
int len = ints.size();
if (len == 0) return 0;
if (len == 1) return ints.get(0);
return sum(ints.subList(0, len/2)) + sum(ints.subList(len/2, len));
}
This is just as inefficient, but will avoid a stack overflow.
The shortest way to write the same thing is
int sum = 0, a[] = {2, 4, 6, 8};
for(int i: a) {
sum += i;
}
System.out.println("sum(a) = " + sum);
prints
sum(a) = 20
You likely want to use onupdate=datetime.now
so that UPDATEs also change the last_updated
field.
SQLAlchemy has two defaults for python executed functions.
default
sets the value on INSERT, only onceonupdate
sets the value to the callable result on UPDATE as well.I had the same issue and found out that the format of my ~/.aws/credentials
file was wrong.
It worked with a file containing:
[default]
aws_access_key_id=XXXXXXXXXXXXXX
aws_secret_access_key=YYYYYYYYYYYYYYYYYYYYYYYYYYY
Note that the profile name must be "[default]
". Some official documentation make reference to a profile named "[credentials]
", which did not work for me.
Had the same problem in Xcode 10.1 and was able to resolve it. In path Project Target > Build Setting > No Common Blocks
, I changed it to No
.
After using slf4s and logula for a while, I wrote loglady
, a simple logging trait wrapping slf4j.
It offers an API similar to that of Python's logging library, which makes the common cases (basic string, simple formatting) trivial and avoids formatting boilerplate.
As of iOS 5.0 Apple provides the NSJSONSerialization class "to convert JSON to Foundation objects and convert Foundation objects to JSON". No external frameworks to incorporate and according to benchmarks its performance is quite good, significantly better than SBJSON.
I also had to save Base64 encoded images that are part of data URLs, so I ended up making a small npm module to do it in case I (or someone else) needed to do it again in the future. It's called ba64.
Simply put, it takes a data URL with a Base64 encoded image and saves the image to your file system. It can save synchronously or asynchronously. It also has two helper functions, one to get the file extension of the image, and the other to separate the Base64 encoding from the data:
scheme prefix.
Here's an example:
var ba64 = require("ba64"),
data_url = "data:image/jpeg;base64,[Base64 encoded image goes here]";
// Save the image synchronously.
ba64.writeImageSync("myimage", data_url); // Saves myimage.jpeg.
// Or save the image asynchronously.
ba64.writeImage("myimage", data_url, function(err){
if (err) throw err;
console.log("Image saved successfully");
// do stuff
});
Install it: npm i ba64 -S
. Repo is on GitHub: https://github.com/HarryStevens/ba64.
P.S. It occurred to me later that ba64 is probably a bad name for the module since people may assume it does Base64 encoding and decoding, which it doesn't (there are lots of modules that already do that). Oh well.
Use Array
's sort()
method, eg
myArray.sort(function(a, b) {
return a.distance - b.distance;
});
Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!
Both these will give you the first child node:
console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);
If you need the first child that is an element node then use:
console.log(parentElement.children[0]);
Edit
Ah, I see your problem now; parentElement
is an array.
If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0]
to dearray (yes, I made that word up) the element:
var parentElement = document.getElementsByClassName("uniqueClassName")[0];
Here is an example to fully programmatically:
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
select 'i like' || type_column || ' with' ect....
HRESULT E_FAIL has been returned from a call to a COM component
In my case, it was because i had differents projects with same GUID in my solution. (Project was created by copy/paste)
Instead of setting the @JsonSerialize on each member or getter you can configure a module that use a custome serializer for a certain type:
SimpleModule module = new SimpleModule();
module.addSerializer(BigInteger.class, new ToStringSerializer());
objectMapper.registerModule(module);
In the above example, I used the to string serializer to serialize BigIntegers (since javascript can not handle such numeric values).
Update: Leaving this answer for historical reasons, but I don't recommend it. Please see the accepted answer above.
Tell Jackson to map using your custom [de]serialization classes:
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
private LocalDateTime ignoreUntil;
provide custom classes:
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime arg0, JsonGenerator arg1, SerializerProvider arg2) throws IOException {
arg1.writeString(arg0.toString());
}
}
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser arg0, DeserializationContext arg1) throws IOException {
return LocalDateTime.parse(arg0.getText());
}
}
random fact: if i nest above classes and don't make them static, the error message is weird:
org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json;charset=UTF-8' not supported
The class AbstractMap.SimpleEntry is generic and can be useful.
For future reference, the above code does not work with Python 3. For Python 3, the D.keys()
needs to be converted to a list.
import matplotlib.pyplot as plt
D = {u'Label1':26, u'Label2': 17, u'Label3':30}
plt.bar(range(len(D)), D.values(), align='center')
plt.xticks(range(len(D)), list(D.keys()))
plt.show()
Look at it this way - is it more efficient to throw out the kitchen garbage when the garbage can is at 10% or let it fill up before taking it out?
By not letting it fill up, you are wasting your time walking to and from the garbage bin outside. This analogous to what happens when the GC thread runs - all the managed threads are suspended while it is running. And If I am not mistaken, the GC thread can be shared among multiple AppDomains, so garbage collection affects all of them.
Of course, you might encounter a situation where you won't be adding anything to the garbage can anytime soon - say, if you're going to take a vacation. Then, it would be a good idea to throw out the trash before going out.
This MIGHT be one time that forcing a GC can help - if your program idles, the memory in use is not garbage-collected because there are no allocations.
const { promisify } = require("util")
const directory = path.join(__dirname, "/tmpl")
const pathnames = promisify(fs.readdir)(directory)
try {
async function emitData(directory) {
let filenames = await pathnames
var ob = {}
const data = filenames.map(async function(filename, i) {
if (filename.includes(".")) {
var storedFile = promisify(fs.readFile)(directory + `\\${filename}`, {
encoding: "utf8",
})
ob[filename.replace(".js", "")] = await storedFile
socket.emit("init", { data: ob })
}
return ob
})
}
emitData(directory)
} catch (err) {
console.log(err)
}
Who wants to try with generators?
Sort by _id
descending:
collection.find(filter={"keyword": keyword}, sort=[( "_id", -1 )])
Sort by _id
ascending:
collection.find(filter={"keyword": keyword}, sort=[( "_id", 1 )])
use process monitor and search for name not found log for tnsnames.ora file.
check your environment variables. if not valid than uninstall all oracle client and reinstall.
My preferred option on 2.0.0 and up is to create a 404 route and also allow a ** route path to resolve to the same component. This allows you to log and display more information about the invalid route rather than a plain redirect which can act to hide the error.
Simple 404 example:
{ path '/', component: HomeComponent },
// All your other routes should come first
{ path: '404', component: NotFoundComponent },
{ path: '**', component: NotFoundComponent }
To display the incorrect route information add in import to router within NotFoundComponent:
import { Router } from '@angular/router';
Add it to the constructior of NotFoundComponent:
constructor(public router: Router) { }
Then you're ready to reference it from your HTML template e.g.
The page <span style="font-style: italic">{{router.url}}</span> was not found.
Try using white-space: pre-line;
. It creates a line-break wherever a line-break appears in the code, but ignores the extra whitespace (tabs and spaces etc.).
First, write your words on separate lines in your code:
<div>Short
Word</div>
Then apply the style to the element containing the words.
div { white-space: pre-line; }
Be careful though, every line break in the code inside the element will create a line break. So writing the following will result in an extra line break before the first word and after the last word:
<div>
Short
Word
</div>
There's a great article on CSS Tricks explaining the other white-space attributes.
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysql_query("select userip from pageview where page='yourpage' and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{
}
else
{
$insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");
$updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}
code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php
Using bits of answers from this question and the latest doc, I was able to extract my numerical arrays using
import h5py
with h5py.File(filename, 'r') as h5f:
h5x = h5f[list(h5f.keys())[0]]['x'][()]
Where 'x'
is simply the X coordinate in my case.
Try this:
INSERT INTO `center_course_fee` (`fk_course_id`,`fk_center_code`,`course_fee`) VALUES ('69', '4920153', '6000') ON DUPLICATE KEY UPDATE `course_fee` = '6000';
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
The better option is create a new table copy the rows to the destination table, drop the actual table and rename the newly created table . This method is good for small tables,
Easiest way I know of is to use "child_process" package which comes packaged with node.
Then you can do something like:
const spawn = require("child_process").spawn;
const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
Then all you have to do is make sure that you import sys
in your python script, and then you can access arg1
using sys.argv[1]
, arg2
using sys.argv[2]
, and so on.
To send data back to node just do the following in the python script:
print(dataToSendBack)
sys.stdout.flush()
And then node can listen for data using:
pythonProcess.stdout.on('data', (data) => {
// Do something with the data returned from python script
});
Since this allows multiple arguments to be passed to a script using spawn, you can restructure a python script so that one of the arguments decides which function to call, and the other argument gets passed to that function, etc.
Hope this was clear. Let me know if something needs clarification.
This will format column A as text, B as General, C as a number.
Sub formatColumns()
Columns(1).NumberFormat = "@"
Columns(2).NumberFormat = "General"
Columns(3).NumberFormat = "0"
End Sub
The first one is the default object constructor call. You can use it's parameters if you want.
var array = new Array(5); //initialize with default length 5
The second one gives you the ability to create not empty array:
var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
You need to run these commands in /var/www/html/
or any other directory that your project is on:
sudo chgrp -R GROUP ./
sudo chown -R USER:GROUP ./
find ./ -type d -exec chmod 755 -R {} \;
find ./ -type f -exec chmod 644 {} \;
In my case (apache web server) I use www-data
for USER
and GROUP
You can use jQuery's Deferred object along with the when method.
deferredArray = [];
forloop {
deferred = new $.Deferred();
ajaxCall(function() {
deferred.resolve();
}
deferredArray.push(deferred);
}
$.when(deferredArray, function() {
//this code is called after all the ajax calls are done
});
They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name "Bean" was given to encompass this standard, which aims to create reusable software components for Java. According to Wikipedia.
The objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. Otherwise, a bean is simply one of many objects in your application. According to Spring IoC.
scaleLabel : "<%= Number(value).toFixed(2).replace('.', ',') + ' $'%>"
As far as I know you can't do that, I may be wrong. However I'd do this with php, generate a JPEG using php standard functions and then display the image, should not be a very hard job, however depends on how flashy the contents of the DIV are
Hope I'm not going offtopic on my first post, but I'd like to expand a little on the casting of integer to string as some respondents appear to have it wrong.
Because the expression in this query uses an arithmetic operator (the plus symbol +), MySQL will convert any strings in the expression to numbers.
To demonstrate, the following will produce the result 6:
SELECT ' 05.05 '+'.95';
String concatenation in MySQL requires the CONCAT() function so there is no ambiguity here and MySQL converts the strings to floats and adds them together.
I actually think the reason the initial query wasn't working is most likely because the $points variable was not in fact set to the user's current points. It was either set to zero, or was unset: MySQL will cast an empty string to zero. For illustration, the following will return 0:
SELECT ABS('');
Like I said, I hope I'm not being too off-topic. I agree that Daan and Tomas have the best solutions for this particular problem.
df.groupby(['Fruit','Name'])['Number'].sum()
You can select different columns to sum numbers.
If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.
if (isset($_POST['mycheckbox'])) {
echo "checked!";
}
I think both are correct programming wise,
But i think your first option is more correct in an object oriented way, because in the constructor is when the object is created, and it is when the variable should initialized.
I think it is the "by the book" convention, but it is open for discussion.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
INDEXES
- to find data easily
UNIQUE INDEX
- duplicate values are not allowed
Syntax for INDEX
CREATE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
Syntax for UNIQUE INDEX
CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME(COLUMN);
Try to use
for today:
SELECT * FROM `tbl_name` where DATE(column_name) = CURDATE()
for selected date:
SELECT * FROM `tbl_name` where DATE(column_name) = DATE('2016-01-14')
This link (How to get line count cheaply in Python?) has lots of potential solutions, but they all ignore one way to make this run considerably faster, namely by using the unbuffered (raw) interface, using bytearrays, and doing your own buffering.
Using a modified version of the timing tool, I believe the following code is faster (and marginally more pythonic) than any of the solutions offered:
def _make_gen(reader):
b = reader(1024 * 1024)
while b:
yield b
b = reader(1024*1024)
def rawpycount(filename):
f = open(filename, 'rb')
f_gen = _make_gen(f.raw.read)
return sum( buf.count(b'\n') for buf in f_gen )
Here are my timings:
rawpycount 0.0048 0.0046 1.00
bufcount 0.0074 0.0066 1.43
wccount 0.01 0.01 2.17
itercount 0.014 0.014 3.04
opcount 0.021 0.02 4.43
kylecount 0.023 0.021 4.58
simplecount 0.022 0.022 4.81
mapcount 0.038 0.032 6.82
I would post it there, but I'm a relatively new user to stack exchange and don't have the requisite manna.
EDIT:
This can be done completely with generators expressions in-line using itertools, but it gets pretty weird looking:
from itertools import (takewhile,repeat)
def rawbigcount(filename):
f = open(filename, 'rb')
bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
return sum( buf.count(b'\n') for buf in bufgen if buf )
I met this issue this morning because I used the same executable in DIFFERENT OSes: after compiling my program with gcc -ggdb -Wall test.c -o test
in my Mac(10.15.2), I ran gdb
with the executable in Ubuntu(16.04) in my VirtualBox.
Fix: recompile with the same command under Ubuntu, then you should be good.
One approach is to strip object and functions from main object. And stringify the simpler form
function simpleStringify (object){
var simpleObject = {};
for (var prop in object ){
if (!object.hasOwnProperty(prop)){
continue;
}
if (typeof(object[prop]) == 'object'){
continue;
}
if (typeof(object[prop]) == 'function'){
continue;
}
simpleObject[prop] = object[prop];
}
return JSON.stringify(simpleObject); // returns cleaned up JSON
};
I see quite a few things wrong. For starters, you don't have your magic button defined and there is no event handler for it.
Also you shouldn't use:
dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
Use only one of the two. From Android documentation:
View.GONE This view is invisible, and it doesn't take any space for layout purposes.
View.INVISIBLE This view is invisible, but it still takes up space for layout purposes.
In your example, you are overriding the View.GONE
assignment with the View.INVISIBLE
one.
Try replacing:
final DatePicker dp2 = new DatePicker(this)
with:
DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
Similarly for other widgets:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
final DatePicker dp2 = new DatePicker(this);
final Button btn2 = new Button(this);
final Button magicButton = new Button(this);
final TextView txt2 = new TextView(TestActivity.this);
dp2.setVisibility(View.GONE);
btn2.setVisibility(View.GONE);
btn2.setText("set Date");
btn2.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
txt2.setText("You selected "
+ dp2.getDayOfMonth() + "/" + (dp2.getMonth() + 1)
+ "/" + dp2.getYear());
}
});
magicButton.setText("Magic Button");
magicButton.setOnClickListener(new View.OnClickListener()
public void onClick(View arg0) {
dp2.setVisibility(View.VISIBLE);
btn2.setVisibility(View.VISIBLE);
}
});
ll.addView(dp2);
ll.addView(btn2);
ll.addView(magicButton);
ll.addView(txt2);
setContentView(ll);
}
Using imagemagick, you can try:
convert page.png page.pdf
Or for multiple images:
convert page*.png mydoc.pdf
Despite answer from CaioToOn above, I still had problems getting this to work initially.
After multiple attempts, finally got it working. Am pasting my final version here - hoping it will benefit somebody else.
<build>
<plugins>
<!--
Copy all Maven Dependencies (-MD) into libMD/ folder to use in classpath via shellscript
-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>copy</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/libMD</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<!--
Above maven-dependepcy-plugin gives a validation error in m2e.
To fix that, add the plugin management step below. Per: http://stackoverflow.com/a/12109018
-->
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<versionRange>[2.0,)</versionRange>
<goals>
<goal>copy-dependencies</goal>
</goals>
</pluginExecutionFilter>
<action>
<execute />
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
<?php
$ConvertDateBack = Zend_Controller_Action_HelperBroker::getStaticHelper('ConvertDate');
$disabledDaysRange = array();
foreach($this->reservedDates as $dates) {
$date = $ConvertDateBack->ConvertDateBack($dates->reservation_date);
$disabledDaysRange[] = $date;
}
$disDays = size($disabledDaysRange);
?>
<script>
var disabledDaysRange = {};
var disDays = '<?=$disDays;?>';
for(i=0;i<disDays;i++) {
array.push(disabledDaysRange,'<?=$disabledDaysRange[' + i + '];?>');
}
............................
The main difference between C++ and Javascript is that C++ is a static-typed language, wile javascript is dynamic.
In dynamic typed languages a variable can contain whatever thing, and its type is given by the value it holds, moment by moment. In static typed languages the type of a variable is declared, and cannot change.
There can be dynamic dispatch and object composition and subtyping (inheritance and virtual functions) as well as static-dispatch and supertyping (via template CRTP), but in any case the type of the variable must be known to the compiler.
If you are in the position to don't know what it is or could be, it is because you designed something as the language has a dynamic type-system.
If that's the case you had better to re-think your design, since it is going into a land not natural for the language you are using (most like going in a motorway with a caterpillar, or in the water with a car)
setTimeout(function() {
$("body,html,document").scrollTop( $('body').height() );
}, 100);
This probably should work even if time is 10ms.
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
I also had issues in running source
in a Dockerfile
This runs perfectly fine for building CentOS 6.6 Docker container, but gave issues in Debian containers
RUN cd ansible && source ./hacking/env-setup
This is how I tackled it, may not be an elegant way but this is what worked for me
RUN echo "source /ansible/hacking/env-setup" >> /tmp/setup
RUN /bin/bash -C "/tmp/setup"
RUN rm -f /tmp/setup
For updating multiple rows in a single query, you can try this
UPDATE table_name
SET
column_1 = CASE WHEN any_column = value and any_column = value THEN column_1_value end,
column_2 = CASE WHEN any_column = value and any_column = value THEN column_2_value end,
column_3 = CASE WHEN any_column = value and any_column = value THEN column_3_value end,
.
.
.
column_n = CASE WHEN any_column = value and any_column = value THEN column_n_value end
if you don't need additional condition then remove and
part of this query
In your build.gradle file add useLibrary 'org.apache.http.legacy' as per Android 6.0 Changes
> Apache HTTP Client Removal
notes.
android {
...
useLibrary 'org.apache.http.legacy'
...
}
To avoid missing link errors add to dependencies
dependencies {
provided 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
}
using 'provided' the dependency will be not included in the apk
Convert.ChangeType()
doesn't correctly handle nullable types or enumerations in .NET 2.0 BCL (I think it's fixed for BCL 4.0 though). Rather than make the outer implementation more complex, make the converter do more work for you. Here's an implementation I use:
public static class Converter
{
public static T ConvertTo<T>(object value)
{
return ConvertTo(value, default(T));
}
public static T ConvertTo<T>(object value, T defaultValue)
{
if (value == DBNull.Value)
{
return defaultValue;
}
return (T) ChangeType(value, typeof(T));
}
public static object ChangeType(object value, Type conversionType)
{
if (conversionType == null)
{
throw new ArgumentNullException("conversionType");
}
// if it's not a nullable type, just pass through the parameters to Convert.ChangeType
if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
// null input returns null output regardless of base type
if (value == null)
{
return null;
}
// it's a nullable type, and not null, which means it can be converted to its underlying type,
// so overwrite the passed-in conversion type with this underlying type
conversionType = Nullable.GetUnderlyingType(conversionType);
}
else if (conversionType.IsEnum)
{
// strings require Parse method
if (value is string)
{
return Enum.Parse(conversionType, (string) value);
}
// primitive types can be instantiated using ToObject
else if (value is int || value is uint || value is short || value is ushort ||
value is byte || value is sbyte || value is long || value is ulong)
{
return Enum.ToObject(conversionType, value);
}
else
{
throw new ArgumentException(String.Format("Value cannot be converted to {0} - current type is " +
"not supported for enum conversions.", conversionType.FullName));
}
}
return Convert.ChangeType(value, conversionType);
}
}
Then your implementation of GetQueryString<T> can be:
public static T GetQueryString<T>(string key)
{
T result = default(T);
string value = HttpContext.Current.Request.QueryString[key];
if (!String.IsNullOrEmpty(value))
{
try
{
result = Converter.ConvertTo<T>(value);
}
catch
{
//Could not convert. Pass back default value...
result = default(T);
}
}
return result;
}
Small but IMPORTANT notices:
FB.getLoginStatus
must be called after FB.init
, otherwise it will not fire the event.
you can use FB.Event.subscribe('auth.statusChange', callback)
, but it will not fire when user is not logged in facebook.
Here is the working example with both functions
window.fbAsyncInit = function() {
FB.Event.subscribe('auth.statusChange', function(response) {
console.log( "FB.Event.subscribe auth.statusChange" );
console.log( response );
});
FB.init({
appId : "YOUR APP KEY HERE",
cookie : true, // enable cookies to allow the server to access
// the session
xfbml : true, // parse social plugins on this page
version : 'v2.1', // use version 2.1
status : true
});
FB.getLoginStatus(function(response){
console.log( "FB.getLoginStatus" );
console.log( response );
});
};
// Load the SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
You're returning a tuple
. Index it.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
public static string GetFileNameFromUrl (string url)
{
var decoded = HttpUtility.UrlDecode(url);
if (decoded.IndexOf("?") is {} queryIndex && queryIndex != -1)
{
decoded = decoded.Substring(0, queryIndex);
}
return Path.GetFileName(decoded);
}
A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:
For the shell’s purposes, a command which exits with a zero exit status has succeeded. An exit status of zero indicates success. A non-zero exit status indicates failure. When a command terminates on a fatal signal N, bash uses the value of 128+N as the exit status.
If a command is not found, the child process created to execute it returns a status of 127. If a com-
mand is found but is not executable, the return status is 126.
If a command fails because of an error during expansion or redirection, the exit status is greater than
zero.
Shell builtin commands return a status of 0 (true) if successful, and non-zero (false) if an error
occurs while they execute. All builtins return an exit status of 2 to indicate incorrect usage.
Bash itself returns the exit status of the last command executed, unless a syntax error occurs, in
which case it exits with a non-zero value. See also the exit builtin command below.
td image
{
display: block;
margin-left: auto;
margin-right: auto;
}
If you are using >= .NET 4 then you can use Tuple
Class:
// declaration
var list = new List<Tuple<string, List<object>>>();
// to add an item to the list
var item = Tuple<string, List<object>>("key", new List<object>);
list.Add(item);
// to iterate
foreach(var i in list)
{
Console.WriteLine(i.Item1.ToString());
}
%hash1 = (%hash1, %hash2) ## or else ... @hash1{keys %hash2} = values %hash2; ## or with references ... $hash_ref1 = { %$hash_ref1, %$hash_ref2 };
undef
, zero, empty string, false
, falsy ...)1 * (aka associative-array, aka dictionary)
If your function is expecting to return a boolean, just do this:
import { of, Observable } from 'rxjs';
import { map, catchError } from 'rxjs/operators';
checkLogin(): Observable<boolean> {
return this.service.getData()
.pipe(
map(response => {
this.data = response;
this.checkservice = true;
return true;
}),
catchError(error => {
this.router.navigate(['newpage']);
console.log(error);
return of(false);
})
)}
Actually, there is a better way to do it than split:
public string GetFirstFromSplit(string input, char delimiter)
{
var i = input.IndexOf(delimiter);
return i == -1 ? input : input.Substring(0, i);
}
And as extension methods:
public static string FirstFromSplit(this string source, char delimiter)
{
var i = source.IndexOf(delimiter);
return i == -1 ? source : source.Substring(0, i);
}
public static string FirstFromSplit(this string source, string delimiter)
{
var i = source.IndexOf(delimiter);
return i == -1 ? source : source.Substring(0, i);
}
Usage:
string result = "hi, hello, sup".FirstFromSplit(',');
Console.WriteLine(result); // "hi"
TryParse works if your number is less than Int32.MaxValue. This also gives you the opportunity to handle badly formatted strings. Works the same for Int64.MaxValue and Int64.TryParse.
int number;
if(Int32.TryParse(nvarchar, out number))
{
// etc...
number.ToString();
}
Also, if you can't change class B, you can fix the error by using multiple inheritance.
class B:
def meth(self, arg):
print arg
class C(B, object):
def meth(self, arg):
super(C, self).meth(arg)
print C().meth(1)
You neglected to say which version of C you are concerned about. Let's assume it's this one:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
As you can see by reading the specification, the standard definitions of true
and false
are 1 and 0, yes.
If your question is about a different version of C, or about non-standard definitions for true
and false
, then ask a more specific question.
Because a (super)class must have complete control over how it is constructed. If the programmer decides that it doesn't make sense to provide a default (no args) constructor as part of the class's contract, then the compiler should not provide one.
adb push [file path on your computer] [file path on your mobile]
Flat and simple config without rewrite, can work in some cases:
location / {
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /home/webuser/site/index.php;
}
i just reinstalled the pip and it works, but I still wanna know why it happened...
i used the apt-get remove --purge python-pip
after I just apt-get install pyhton-pip
and it works, but don't ask me why...
Tag can be completed in another line. This is why \n
needs to be added.
<PRE>(.|\n)*?<\/PRE>
The line below throws exception
if the key does not exists.
IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
Work around :
Include System.Linq;
IEnumerable<string> headerValues;
var userId = string.Empty;
if (request.Headers.TryGetValues("MyCustomID", out headerValues))
{
userId = headerValues.FirstOrDefault();
}
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
To clarify some points:
As jro has mentioned, the right way is to use subprocess.communicate
.
Yet, when feeding the stdin
using subprocess.communicate
with input
, you need to initiate the subprocess with stdin=subprocess.PIPE
according to the docs.
Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.
Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input
rather than a string
. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).
If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.
So, if the streams were not opened explicitly in text mode, then something like below should work:
import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]
I've left the stderr
value above deliberately as STDOUT
as an example.
That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m
. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme
data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc
process' stdin (in the meantime, get rid of the extra newline character):
import subprocess
what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'
# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]
# Well the result includes an '\n' at the end,
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()
# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()
This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.
Hope that helps someone out.
Object is a collection of methods and variables.You can't print the variables in object by just cout operation . if you want to show the things inside the object you have to declare either a getter or a display text method in class.
ex
#include <iostream>
using namespace std;
class mystruct
{
private:
int m_a;
float m_b;
public:
mystruct(int x, float y)
{
m_a = x;
m_b = y;
}
public:
void getm_aAndm_b()
{
cout<<m_a<<endl;
cout<<m_b<<endl;
}
};
int main()
{
mystruct m = mystruct(5,3.14);
cout << "my structure " << endl;
m.getm_aAndm_b();
return 0;
}
Not that this is just a one way of doing it
Make sure there is no whitespace before your php tag
// whitespace
<?php
namespace HelloWorld
?>
Remove the white space before your php tag starts
<?php
namespace HelloWorld
?>
Lambda Expression Java 8
In Java 1.8 (Java 8) this has become lot easier by using forEach method from Aggregate operations(Stream operations) that looks similar to iterators from Iterable Interface.
Just copy paste below statement to your code and rename the HashMap variable from hm to your HashMap variable to print out key-value pair.
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
/*
* Logic to put the Key,Value pair in your HashMap hm
*/
// Print the key value pair in one line.
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Here is an example where a Lambda Expression is used:
HashMap<Integer,Integer> hm = new HashMap<Integer, Integer>();
Random rand = new Random(47);
int i=0;
while(i<5){
i++;
int key = rand.nextInt(20);
int value = rand.nextInt(50);
System.out.println("Inserting key: "+key+" Value: "+value);
Integer imap =hm.put(key,value);
if( imap == null){
System.out.println("Inserted");
}
else{
System.out.println("Replaced with "+imap);
}
}
hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v));
Output:
Inserting key: 18 Value: 5
Inserted
Inserting key: 13 Value: 11
Inserted
Inserting key: 1 Value: 29
Inserted
Inserting key: 8 Value: 0
Inserted
Inserting key: 2 Value: 7
Inserted
key: 1 value:29
key: 18 value:5
key: 2 value:7
key: 8 value:0
key: 13 value:11
Also one can use Spliterator for the same.
Spliterator sit = hm.entrySet().spliterator();
UPDATE
Including documentation links to Oracle Docs. For more on Lambda go to this link and must read Aggregate Operations and for Spliterator go to this link.
The -p
flag of netstat
gives you PID of the process:
netstat -l -p
Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat
.
As we worked out during the discussion with @Cyclone, the line that does the job is:
sockstat -4 -l | grep :80 | awk '{print $3}' | head -1
If you commit one file and push your revision, it will not transfer the whole repository, it will push changes.
Is there any reason you have to hook and test for the enter key?
Couldn't you simply add a
<input type="submit" />
to your form and have it naturally be submitted when enter is pushed? You could even then hook the form's onsubmit
action and call a validation function from there if you wanted...
You could even use the onsubmit
as a test to see if your form is being submitted, but it won't work if you call form.submit()
.
I recently found out by accident that since you have more control on a ImageView that you can set an onclicklistener for an image here is a sample of a dynamically created image button
private int id;
private bitmap bmp;
LinearLayout.LayoutParams familyimagelayout = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT );
final ImageView familyimage = new ImageView(this);
familyimage.setBackground(null);
familyimage.setImageBitmap(bmp);
familyimage.setScaleType(ImageView.ScaleType.FIT_START);
familyimage.setAdjustViewBounds(true);
familyimage.setId(id);
familyimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//what you want to do put here
}
});
It looks like you want the indices of the duplicates. Here is some short code that will find those in O(n) time, without using any packages:
dups = {}
[dups.setdefault(v, []).append(i) for i, v in enumerate(mylist)]
dups = {k: v for k, v in dups.items() if len(v) > 1}
# dups now has keys for all the duplicate values
# and a list of matching indices for each
# The second line produces an unused list.
# It could be replaced with this:
for i, v in enumerate(mylist):
dups.setdefault(v, []).append(i)
At the initial start up of the server the following happens, given that the data directory of the server is empty:
To reveal it, use the following command:
shell> sudo grep 'temporary password' /var/log/mysqld.log
Change the root password as soon as possible by logging in with the generated temporary password and set a custom password for the superuser account:
shell> mysql -u root -p #Login to root user with some password
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass5!';
Spring Boot will handle those repositories automatically as long as they are included in the same package (or a sub-package) of your @SpringBootApplication class. For more control over the registration process, you can use the @EnableMongoRepositories annotation. spring.io guides
@SpringBootApplication
@EnableMongoRepositories(basePackages = {"RepositoryPackage"})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
From your example it seems reasonable to assume that the siteIP
column is determined by the siteName
column (that is, each site has only one siteIP
). If this is indeed the case, then there is a simple solution using group by
:
select
sites.siteName,
sites.siteIP,
max(history.date)
from sites
inner join history on
sites.siteName=history.siteName
group by
sites.siteName,
sites.siteIP
order by
sites.siteName;
However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP
), then it is not clear from you question which siteIP
you want the query to return in the second column. If just any siteIP
, then the following query will do:
select
sites.siteName,
min(sites.siteIP),
max(history.date)
from sites
inner join history on
sites.siteName=history.siteName
group by
sites.siteName
order by
sites.siteName;
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
console.log(e.type);_x000D_
return false;_x000D_
});
_x000D_
This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On
Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.
Lastly, I'm simply showing an alternative syntax to attach the event to the element.
void myfunc(void)
{
char* text = "Hello World";
char aLetter = 'C';
printf("%s\n", text);
printf("%c\n", aLetter);
}
For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80
, e.g 8080
by setting the TCP port in the properties of each of its sites (including the default one).
In Apache, enable mod_proxy
and mod_proxy_http
, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.
<VirtualHost *:80>
ServerName foo.bar
ServerAlias *
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8080/
</VirtualHost>
Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.
Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.
If you try it on CellContentClick
Event
Use:
dataGridView1.EndEdit(); //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
I know its late to answer here, still if anybody want to know solution is below
conversationView.smoothScrollToPosition(conversationView.getAdapter().getItemCount() - 1);
I separate it, and then use an identity comparison to dictate what is does next.
$("#selectField").change(function(){
if(this.value === 'textValue1'){ $(".contentClass1").fadeIn(); }
if(this.value === 'textValue2'){ $(".contentclass2").fadeIn(); }
});
Check Safari developer reference on Touch class.
According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX
and not PageX
You could do simple thing very simple like this
(window.screen.width < 700) {
//The device is a Mobile
} else {
//The device is a Desktop
}
If you already fetched your remote branch and do git branch -a
,
you obtain something like :
* 8.0
xxx
remotes/origin/xxx
remotes/origin/8.0
remotes/origin/HEAD -> origin/8.0
remotes/rep_mirror/8.0
After that, you can use rep_mirror/8.0
to designate locally your remote branch.
The trick is that remotes/rep_mirror/8.0
doesn't work but rep_mirror/8.0
does.
So, a command like git merge -m "my msg" rep_mirror/8.0
do the merge.
(note : this is a comment to @VonC answer. I put it as another answer because code blocks don't fit into the comment format)
You can use an anonymous function to pass the matches to your function:
$result = preg_replace_callback(
"/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
$result
);
Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e
would convert a double quote "
into \"
.
Not a definite answer but too much to fit in comments:
I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl
and openssl client
paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.
Do openssl x509 <clientcert.pem -noout -subject -issuer
and the same on the cert from the test P12 that works. Do openssl s_client
(or check the one you did) and look under Acceptable client certificate CA names
; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.
If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text
for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.
If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.
Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
You can do the access control at the Web server level using HTTP Basic authentication and htpasswd. There are a number of problems with this:
Unless you're building a site for internal use with few users, I wouldn't really recommend it.
Why not just display it in the user's web browser?
Your code is fine, just replace the following line:
JSONArray jsonMainArr = new JSONArray(mainJSON.getJSONArray("source"));
with this line:
JSONArray jsonMainArr = mainJSON.getJSONArray("source");
I solved the problem by saving the fragments in SparceArray:
public abstract class SaveFragmentsPagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> fragments = new SparseArray<>();
public SaveFragmentsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
fragments.append(position, fragment);
return fragment;
}
@Nullable
public Fragment getFragmentByPosition(int position){
return fragments.get(position);
}
}
In short you have to do like this
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "https://maven.fabric.io/public" }
}
Detail:
You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:
apply plugin: 'java'
sourceCompatibility = 1.7
version = '1.0'
repositories {
maven { url "http://maven.springframework.org/release" }
maven { url "http://maven.restlet.org" }
mavenCentral()
}
dependencies {
compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
testCompile group:'junit', name:'junit', version:'4.11'
}
Lucene is nice and all, but their stop word set is awful. I had to manually add a ton of stop words to StopAnalyzer.ENGLISH_STOP_WORDS_SET just to get it anywhere near usable.
I haven't used Sphinx but I know people swear by its speed and near-magical "ease of setup to awesomeness" ratio.
I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
# the inbox. You can change that number to reference
# any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content
The java.net blog had a class the other day that might have done what you want (but it is down right now so I cannot check).
This code here could probably be modified to do what you want:
Here is the one I was thinking of from java.net: https://urlencodedquerystring.dev.java.net/
if you are receiving data from a serial port, make sure you are using the right baudrate (and the other configs ) : decoding using (utf-8) but the wrong config will generate the same error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
to check your serial port config on linux use : stty -F /dev/ttyUSBX -a
SELECT Priority, COALESCE(cnt, 0)
FROM (
SELECT 1 AS Priority
UNION ALL
SELECT 2 AS Priority
UNION ALL
SELECT 3 AS Priority
UNION ALL
SELECT 4 AS Priority
UNION ALL
SELECT 5 AS Priority
) p
LEFT JOIN
(
SELECT Priority, COUNT(*) AS cnt
FROM jobs
GROUP BY
Priority
) j
ON j.Priority = p.Priority
A standard solution for this problem is to allow slashes by making the parameter that may contain slashes the last parameter in the url.
For a product code url you would then have...
mysite.com/product/details/PR12345/22
For a search term you'd have
http://project/search_exam/0/search_subject/0/keyword/Psychology/Management
(The keyword here is Psychology/Management)
It's not a massive amount of work to process the first "named" parameters then concat the remaining ones to be product code or keyword.
Some frameworks have this facility built in to their routing definitions.
This is not applicable to use case involving two parameters that my contain slashes.
As an addition
$this -> router -> fetch_module(); //Module Name if you are using HMVC Component
toolbarHeight
:There's no longer a need to use PreferredSize
. Use toolbarHeight
with flexibleSpace
.
AppBar(
toolbarHeight: 120, // Set this height
flexibleSpace: Container(
color: Colors.orange,
child: Column(
children: [
Text('1'),
Text('2'),
Text('3'),
Text('4'),
],
),
),
)
<script>
function submit(){
var userPass = document.getElementById('pass');
var userName = document.getElementById('user');
alert(user.value);
alert(pass.value);
}
</script>
<input type="text" id="user" />
<input type="text" id="pass" />
<button onclick="submit();" href="javascript:;">Submit</button>
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
Android custom SeekBar - custom track or progress, shape, size, background and thumb and for other seekbar customization see http://www.zoftino.com/android-seekbar-and-custom-seekbar-examples
Custom Track drawable
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background"
android:gravity="center_vertical|fill_horizontal">
<shape android:shape="rectangle"
android:tint="#ffd600">
<corners android:radius="8dp"/>
<size android:height="30dp" />
<solid android:color="#ffd600" />
</shape>
</item>
<item android:id="@android:id/progress"
android:gravity="center_vertical|fill_horizontal">
<scale android:scaleWidth="100%">
<selector>
<item android:state_enabled="false"
android:drawable="@android:color/transparent" />
<item>
<shape android:shape="rectangle"
android:tint="#f50057">
<corners android:radius="8dp"/>
<size android:height="30dp" />
<solid android:color="#f50057" />
</shape>
</item>
</selector>
</scale>
</item>
</layer-list>
Custom thumb drawable
?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
android:thickness="4dp"
android:useLevel="false"
android:tint="#ad1457">
<solid
android:color="#ad1457" />
<size
android:width="32dp"
android:height="32dp" />
</shape>
Output
Create a .htaccess file in the images folder and add this
<IfModule mod_rewrite.c>
RewriteEngine On
# directory browsing
Options All +Indexes
</IfModule>
you can put this Options All -Indexes
in the project file .htaccess
,file to deny direct access to other folders.
This does what you want
Assuming "current version" is the working directory (uncommitted modifications) and "last version" is HEAD
(last committed modifications for the current branch), simply do
git diff HEAD
Credit for the following goes to user Cerran
.
And if you always skip the staging area with -a
when you commit, then you can simply use git diff
.
Summary
git diff
shows unstaged changes.git diff --cached
shows staged changes.git diff HEAD
shows all changes (both staged and unstaged).Source: git-diff(1) Manual Page – Cerran
By converting the matrix to array by using
n12 = np.squeeze(np.asarray(n2))
X12 = np.squeeze(np.asarray(x1))
solved the issue.
Generate values from the uniform distribution on the interval [a, b].
r = a + (b-a).*rand(100,1);
Was CV_FONT_HERSHEY_SIMPLEX
in cv(1)?
Here's all I have available for cv2 "FONT":
FONT_HERSHEY_COMPLEX
FONT_HERSHEY_COMPLEX_SMALL
FONT_HERSHEY_DUPLEX
FONT_HERSHEY_PLAIN
FONT_HERSHEY_SCRIPT_COMPLEX
FONT_HERSHEY_SCRIPT_SIMPLEX
FONT_HERSHEY_SIMPLEX
FONT_HERSHEY_TRIPLEX
FONT_ITALIC
Dropping the 'CV_' seems to work for me.
cv2.putText(image,"Hello World!!!", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 2, 255)
Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.
The way we do that is with og:meta
tags.
The tags look something like this -
<meta property="og:title" content="Stuffed Cookies" />
<meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
<meta property="og:description" content="The Turducken of Cookies" />
<meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">
You'll need to place these or similar meta tags in the <head>
of your HTML file. Don't forget to substitute the values for your own!
For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/
Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.
One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.
If you are using a linux system you can get a random number out of /dev/random or /dev/urandom. Be carefull /dev/random will block if there are not enough random numbers available. If you need speed over randomness use /dev/urandom.
These "files" will be filled with random numbers generated by the operating system. It depends on the implementation of /dev/random on your system if you get true or pseudo random numbers. True random numbers are generated with help form noise gathered from device drivers like mouse, hard drive, network.
You can get random numbers from the file with dd
In addition to the very great answer above I want to mention application wide events which can be very useful in an MVC setup to enable communication between controllers. (extjs4.1)
Lets say we have a controller Station (Sencha MVC examples) with a select box:
Ext.define('Pandora.controller.Station', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'stationslist': {
selectionchange: this.onStationSelect
},
...
});
},
...
onStationSelect: function(selModel, selection) {
this.application.fireEvent('stationstart', selection[0]);
},
...
});
When the select box triggers a change event, the function onStationSelect
is fired.
Within that function we see:
this.application.fireEvent('stationstart', selection[0]);
This creates and fires an application wide event that we can listen to from any other controller.
Thus in another controller we can now know when the station select box has been changed. This is done through listening to this.application.on
as follows:
Ext.define('Pandora.controller.Song', {
extend: 'Ext.app.Controller',
...
init: function() {
this.control({
'recentlyplayedscroller': {
selectionchange: this.onSongSelect
}
});
// Listen for an application wide event
this.application.on({
stationstart: this.onStationStart,
scope: this
});
},
....
onStationStart: function(station) {
console.info('I called to inform you that the Station controller select box just has been changed');
console.info('Now what do you want to do next?');
},
}
If the selectbox has been changed we now fire the function onStationStart
in the controller Song
also ...
From the Sencha docs:
Application events are extremely useful for events that have many controllers. Instead of listening for the same view event in each of these controllers, only one controller listens for the view event and fires an application-wide event that the others can listen for. This also allows controllers to communicate with one another without knowing about or depending on each other’s existence.
In my case: Clicking on a tree node to update data in a grid panel.
Update 2016 thanks to @gm2008 from the comments below:
In terms of firing application-wide custom events, there is a new method now after ExtJS V5.1 is published, which is using Ext.GlobalEvents
.
When you fire events, you can call: Ext.GlobalEvents.fireEvent('custom_event');
When you register a handler of the event, you call: Ext.GlobalEvents.on('custom_event', function(arguments){/* handler codes*/}, scope);
This method is not limited to controllers. Any component can handle a custom event through putting the component object as the input parameter scope.
Use with=FALSE
:
cols = paste("V", c(1,2,3,5), sep="")
dt[, !cols, with=FALSE]
I suggest going through the "Introduction to data.table" vignette.
Update: From v1.10.2
onwards, you can also do:
dt[, ..cols]
See the first NEWS item under v1.10.2 here for additional explanation.
conda info
will display information about the current install, including the active env location which is what you want.
Here's my output:
(base) C:\Users\USERNAME>conda info
active environment : base
active env location : C:\ProgramData\Miniconda3
shell level : 1
user config file : C:\Users\USERNAME\.condarc
populated config files :
conda version : 4.8.2
conda-build version : not installed
python version : 3.7.6.final.0
virtual packages : __cuda=10.2
base environment : C:\ProgramData\Miniconda3 (read only)
channel URLs : https://repo.anaconda.com/pkgs/main/win-64
https://repo.anaconda.com/pkgs/main/noarch
https://repo.anaconda.com/pkgs/r/win-64
https://repo.anaconda.com/pkgs/r/noarch
https://repo.anaconda.com/pkgs/msys2/win-64
https://repo.anaconda.com/pkgs/msys2/noarch
package cache : C:\ProgramData\Miniconda3\pkgs
C:\Users\USERNAME\.conda\pkgs
C:\Users\USERNAME\AppData\Local\conda\conda\pkgs
envs directories : C:\Users\USERNAME\.conda\envs
C:\ProgramData\Miniconda3\envs
C:\Users\USERNAME\AppData\Local\conda\conda\envs
platform : win-64
user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Windows/10 Windows/10.0.18362
administrator : False
netrc file : None
offline mode : False
If your shell/prompt complains that it cannot find the command, it likely means that you installed Anaconda without adding it to the PATH environment variable.
If that's the case find and open the Anaconda Prompt and do it from there.
Alternatively reinstall Anaconda choosing to add it to the PATH. Or add the variable manually.
Anaconda Prompt should be available in your Start Menu (Win) or Applications Menu (macos)
Try this in MVC 4.0
@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })
Apparently the only reliable and accepted solution would be to do feature detection like this:
browser_treats_urls_like_safari_does = false;
var last_location_hash = location.hash;
location.hash = '"blah"';
if (location.hash == '#%22blah%22')
browser_treats_urls_like_safari_does = true;
location.hash = last_location_hash;
Here's a one-liner (imports
don't count :) that can easily be generalized to concatenate N dictionaries:
from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))
and:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.items() for d in args))
from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))
Output:
>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}
Generalized to concatenate N dicts:
from itertools import chain
def dict_union(*args):
return dict(chain.from_iterable(d.iteritems() for d in args))
I'm a little late to this party, I know, but I hope this helps someone.
It is simple, as a java, Android also supporting singleton. -
Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.
-> Static member : This contains the instance of the singleton class.
-> Private constructor : This will prevent anybody else to instantiate the Singleton class.
-> Static public method : This provides the global point of access to the Singleton object and returns the instance to the client calling class.
use getInstance() of Singleton class
public class Logger{
private static Logger objLogger;
private Logger(){
//ToDo here
}
public static Logger getInstance()
{
if (objLogger == null)
{
objLogger = new Logger();
}
return objLogger;
}
}
while use singleton -
Logger.getInstance();
To be absolutely correct you should put all the names into the SAN field.
The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.
This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.
The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...
If you found a correct implementation, the answers for your questions will be the followings:
Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.
What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.
In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.
The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)
On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)
To install the 3rd party jar which is not in maven repository use maven-install-plugin.
Below are steps:
mvn install:install-file -Dfile= -DgroupId= -DartifactId= -Dversion= -Dpackaging=
Below is the e.g one I used it for simonsite log4j
mvn install:install-file -Dfile=/Users/athanka/git/MyProject/repo/log4j-rolling-appender.jar -DgroupId=uk.org.simonsite -DartifactId=log4j-rolling-appender -Dversion=20150607-2059 -Dpackaging=jar
In the pom.xml include the dependency as below
<dependency> <groupId>uk.org.simonsite</groupId> <artifactId>log4j-rolling-appender</artifactId> <version>20150607-2059</version> </dependency>
Run the mvn clean install command to create your packaging
Below is the reference link:
https://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html
Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix
wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
Create an xml file jax-ws-catalog.xml under META-INF as below
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
prefer="system">
<system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" />
</catalog>
Now package your jar. No more reference to the local directory, it's all packaged and referenced within
If they're block level elements they won't be affected by text-align: center;
. Someone may have set img { display: block; }
and that's throwing it out of whack. You can try:
td { text-align: center; }
td * { display: inline; }
and if it looks as desired you should definitely replace * with the desired elements like:
td img, td foo { display: inline; }
Try this.
dpkg -s apache2 | grep Status
dpkg -s php5 | grep Status
The above are all good solutions and I tried all of them, but got the solution here, which is to
Debug -> Delete All Breakpoints
Generally, Python programs should be written with the assumption that all users are consenting adults, and thus are responsible for using things correctly themselves. However, in the rare instance where it just does not make sense for an attribute to be settable (such as a derived value, or a value read from some static datasource), the getter-only property is generally the preferred pattern.
i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?
following code is working fine for me:
import smtplib
to = '[email protected]'
gmail_user = '[email protected]'
gmail_pwd = 'yourpassword'
smtpserver = smtplib.SMTP("smtp.gmail.com",587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo() # extra characters to permit edit
smtpserver.login(gmail_user, gmail_pwd)
header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:testing \n'
print header
msg = header + '\n this is test msg from mkyong.com \n\n'
smtpserver.sendmail(gmail_user, to, msg)
print 'done!'
smtpserver.quit()
Ref: http://www.mkyong.com/python/how-do-send-email-in-python-via-smtplib/
For making alert just put below javascript code in footer.
<script>
$(document).ready(function(){
alert('Hi');
});
</script>
You need to also load jquery min file. Please insert this script in header.
<script type='text/javascript' src='https://code.jquery.com/jquery-1.12.0.min.js'></script>
Unlike constructors, where throwing exceptions can be a useful way to indicate that object creation succeeded, exceptions should not be thrown in destructors.
The problem occurs when an exception is thrown from a destructor during the stack unwinding process. If that happens, the compiler is put in a situation where it doesn’t know whether to continue the stack unwinding process or handle the new exception. The end result is that your program will be terminated immediately.
Consequently, the best course of action is just to abstain from using exceptions in destructors altogether. Write a message to a log file instead.
To improve on Forumpie's answer, the trick is using %*
(all params) in the sub:
Edit: Added echo of the TRIM subroutines params, to provide more insight
@ECHO OFF
SET /p NAME=- NAME ?
ECHO "%NAME%"
CALL :TRIM %NAME%
SET NAME=%TRIMRESULT%
ECHO "%NAME%"
GOTO :EOF
:TRIM
echo "%1"
echo "%2"
echo "%3"
echo "%4"
SET TRIMRESULT=%*
GOTO :EOF
This strips leading and trailing spaces, but keeps all spaces between.
" 1 2 3 4 "
"1 2 3 4"
Details of %*: Batch Parameters
select translate(description,'\\t','') from myTable;
Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)
Char/varchar support added as of Hive 0.14.0
As you have define the id in int type at the database creation, you have to use the same data type in the model class too. And as you have defined the id to auto increment in the database, you have to mention it in the model class by passing value 'GenerationType.AUTO' into the attribute 'strategy' within the annotation @GeneratedValue. Then the code becomes as below.
@Entity
public class Operator{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String username;
private String password;
private Integer active;
//Getters and setters...
}
Sometimes problems in your project build path
can cause this, make sure you resolve it first, in my case the prolem was :
And when fix it highlights come back.
DataSet ds = new DataSet();
DataTable dt = new DataTable("MyTable");
dt.Columns.Add(new DataColumn("id",typeof(int)));
dt.Columns.Add(new DataColumn("name", typeof(string)));
DataRow dr = dt.NewRow();
dr["id"] = 123;
dr["name"] = "John";
dt.Rows.Add(dr);
ds.Tables.Add(dt);
With method chaining:
product = (
df1.assign(key=1)
.merge(df2.assign(key=1), on="key")
.drop("key", axis=1)
)
In the following example,
playground
is the database name andequipment
is the table name
Another way is using SHOW-COLUMNS:5.5 (available also for 5.5>
)
$ mysql -uroot -p<password> -h<host> -P<port> -e \
"SHOW COLUMNS FROM playground.equipment"
And the output:
mysql: [Warning] Using a password on the command line interface can be insecure.
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| type | varchar(50) | YES | | NULL | |
| quant | int(11) | YES | | NULL | |
| color | varchar(25) | YES | | NULL | |
+-------+-------------+------+-----+---------+----------------+
One can also use mysqlshow-client (also available for 5.5>
) like following:
$ mysqlshow -uroot -p<password> -h<host> -P<port> \
playground equipment
And the output:
mysqlshow: [Warning] Using a password on the command line interface can be insecure.
Database: playground Table: equipment
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment |
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
| id | int(11) | | NO | PRI | | auto_increment | select,insert,update,references | |
| type | varchar(50) | latin1_swedish_ci | YES | | | | select,insert,update,references | |
| quant | int(11) | | YES | | | | select,insert,update,references | |
| color | varchar(25) | latin1_swedish_ci | YES | | | | select,insert,update,references | |
+-------+-------------+-------------------+------+-----+---------+----------------+---------------------------------+---------+
If you run into TypeError: unhashable type: 'list'
you need to turn lists or sets into tuples, e.g.
set(map(tuple, list_of_lists1)).symmetric_difference(set(map(tuple, list_of_lists2)))
Execute this code on a good server which will provide you the complete rights for PUBLIC role. Copy the output and paste to the server with the issue. Execute. Try logging in again. It fixed our problem.
SELECT SDP.state_desc ,
SDP.permission_name ,
SSU.[name] AS "Schema" ,
SSO.[name] ,
SSO.[type]
FROM sys.sysobjects SSO
INNER JOIN sys.database_permissions SDP ON SSO.id = SDP.major_id
INNER JOIN sys.sysusers SSU ON SSO.uid = SSU.uid
ORDER BY SSU.[name] ,
SSO.[name]
Think about somebody doing help(yourmodule)
at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help
in terms of amount of information). So if you have in x.py
:
"""This module does blah blah."""
class Blah(object):
"""This class does blah blah."""
then:
>>> import x; help(x)
shows:
Help on module x:
NAME
x - This module does blah blah.
FILE
/tmp/x.py
CLASSES
__builtin__.object
Blah
class Blah(__builtin__.object)
| This class does blah blah.
|
| Data and other attributes defined here:
|
| __dict__ = <dictproxy object>
| dictionary for instance variables (if defined)
|
| __weakref__ = <attribute '__weakref__' of 'Blah' objects>
| list of weak references to the object (if defined)
As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).
I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.
Django's contributed humanize application does this:
{% load humanize %}
{{ my_num|intcomma }}
Be sure to add 'django.contrib.humanize'
to your INSTALLED_APPS
list in the settings.py
file.
In C, "strings" are just plain char
arrays. Therefore, you can't directly concatenate them with other "strings".
You can use the strcat
function, which appends the string pointed to by src
to the end of the string pointed to by dest
:
char *strcat(char *dest, const char *src);
Here is an example from cplusplus.com:
char str[80];
strcpy(str, "these ");
strcat(str, "strings ");
strcat(str, "are ");
strcat(str, "concatenated.");
For the first parameter, you need to provide the destination buffer itself. The destination buffer must be a char array buffer. E.g.: char buffer[1024];
Make sure that the first parameter has enough space to store what you're trying to copy into it. If available to you, it is safer to use functions like: strcpy_s
and strcat_s
where you explicitly have to specify the size of the destination buffer.
Note: A string literal cannot be used as a buffer, since it is a constant. Thus, you always have to allocate a char array for the buffer.
The return value of strcat
can simply be ignored, it merely returns the same pointer as was passed in as the first argument. It is there for convenience, and allows you to chain the calls into one line of code:
strcat(strcat(str, foo), bar);
So your problem could be solved as follows:
char *foo = "foo";
char *bar = "bar";
char str[80];
strcpy(str, "TEXT ");
strcat(str, foo);
strcat(str, bar);
There are few steps to overcome this problem:
The problem solved: The problem raised to me at the uninstallation on openfire server.
This doesn't answer your question directly, but it will give you the elements that are in common. This can be done with Paul Murrell's package compare
:
library(compare)
a1 <- data.frame(a = 1:5, b = letters[1:5])
a2 <- data.frame(a = 1:3, b = letters[1:3])
comparison <- compare(a1,a2,allowAll=TRUE)
comparison$tM
# a b
#1 1 a
#2 2 b
#3 3 c
The function compare
gives you a lot of flexibility in terms of what kind of comparisons are allowed (e.g. changing order of elements of each vector, changing order and names of variables, shortening variables, changing case of strings). From this, you should be able to figure out what was missing from one or the other. For example (this is not very elegant):
difference <-
data.frame(lapply(1:ncol(a1),function(i)setdiff(a1[,i],comparison$tM[,i])))
colnames(difference) <- colnames(a1)
difference
# a b
#1 4 d
#2 5 e
Use the map
method:
var a = [1, 2, 3]_x000D_
var b = ['a', 'b', 'c']_x000D_
_x000D_
var c = a.map(function(e, i) {_x000D_
return [e, b[i]];_x000D_
});_x000D_
_x000D_
console.log(c)
_x000D_
To know where your .sqlite file is stored in your AppDelegate.m add the following code
- (NSURL *)applicationDocumentsDirectory
{
NSLog(@"%@",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
now call this method in AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//call here
[self applicationDocumentsDirectory];
}
You get that error because you don't have the public key of the person who signed the message.
gpg
should have given you a message containing the ID of the key that was used to sign it. Obtain the public key from the person who encrypted the file and import it into your keyring (gpg2 --import key.asc
); you should be able to verify the signature after that.
If the sender submitted its public key to a keyserver (for instance, https://pgp.mit.edu/), then you may be able to import the key directly from the keyserver:
gpg2 --keyserver https://pgp.mit.edu/ --search-keys <sender_name_or_address>
We can return like this,
return <React.Fragment />;
I faced the same issue after I removed the php5 package (that includes all the drivers as well) in order to install php7 package. I actually installed php7 package without a mysql module.
I managed to solve it by typing in the terminal:
1) $ apt-cache search php7 which lists all the modules, looking through the modules I found,
php7.0-mysql - MySQL module for PHP
2) $ sudo apt-get install php7.0-mysql
That's it. It worked for me in my linux system.
(use the appropriate php version, yours could be php5)
With modern Git versions, the command to use would be:
git push -u origin <branch_name_test>
This will automatically set the branch name to track from remote and push in one go.
In Short: In order to deal with "Leading Zero" numbers (any 0 digit that comes before the first non-zero) in bash
- Use bc
An arbitrary precision calculator language
Example:
a="000001"
b=$(echo $a | bc)
echo $b
Output: 1
From Bash manual:
"bc is a language that supports arbitrary precision numbers with interactive execution of statements. There are some similarities in the syntax to the C programming lan- guage. A standard math library is available by command line option. If requested, the math library is defined before processing any files. bc starts by processing code from all the files listed on the command line in the order listed. After all files have been processed, bc reads from the standard input. All code is executed as it is read. (If a file contains a command to halt the processor, bc will never read from the standard input.)"
An alternative is Joda-Time.
Use DateTime
DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();
If you are planning to get the image from its path, it's better to use Assets instead of trying to figure out the path of the drawable folder.
InputStream stream = getAssets().open("image.png");
Drawable d = Drawable.createFromStream(stream, null);
Some points.
Use $.data Instead of $.fn.data
// regular
$(elem).data(key,value);
// 10x faster
$.data(elem,key,value);
Then, You can get the previous value through the event object, without complicating your life:
$('#myInputElement').change(function(event){
var defaultValue = event.target.defaultValue;
var newValue = event.target.value;
});
Be warned that defaultValue is NOT the last set value. It's the value the field was initialized with. But you can use $.data to keep track of the "oldValue"
I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...)
I check if a number is prime or not with the following code( of course using sqrt ):
bool IsPrime(const unsigned int x)
{
const unsigned int TOP
= static_cast<int>(
std::sqrt( static_cast<double>( x ) )
) + 1;
for ( int i=2; i != TOP; ++i )
{
if (x % i == 0) return false;
}
return true;
}
I use this method to determine the primes:
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
#include <cmath>
void initialize( unsigned int *, const unsigned int );
void show_list( const unsigned int *, const unsigned int );
void criba( unsigned int *, const unsigned int );
void setItem ( unsigned int *, const unsigned int, const unsigned int );
bool IsPrime(const unsigned int x)
{
const unsigned int TOP
= static_cast<int>(
std::sqrt( static_cast<double>( x ) )
) + 1;
for ( int i=2; i != TOP; ++i )
{
if (x % i == 0) return false;
}
return true;
}
int main()
{
unsigned int *l;
unsigned int n;
cout << "Ingrese tope de criba" << endl;
cin >> n;
l = new unsigned int[n];
initialize( l, n );
cout << "Esta es la lista" << endl;
show_list( l, n );
criba( l, n );
cout << "Estos son los primos" << endl;
show_list( l, n );
}
void initialize( unsigned int *l, const unsigned int n)
{
for( int i = 0; i < n - 1; i++ )
*( l + i ) = i + 2;
}
void show_list( const unsigned int *l, const unsigned int n)
{
for( int i = 0; i < n - 1; i++ )
{
if( *( l + i ) != 0)
cout << l[i] << " - ";
}
cout << endl;
}
void setItem( unsigned int *l, const unsigned int n, const unsigned int p)
{
unsigned int i = 2;
while( p * i <= n)
{
*( l + (i * p - 2) ) = 0;
i++;
}
}
void criba( unsigned int *l, const unsigned int n)
{
for( int i = 0; i * i <= n ; i++ )
if( IsPrime ( *( l + i) ) )
setItem( l, n, *(l + i) );
}
Won't you need to take the e
in e666.76
into account?
With
(e|0-9)\d*\d.\d{1,2)
I hade this error when transfering a csv to mssql I converted the columns to DT_NTEXT and some columns on mssql where set to nvarchar(255).
setting them to nvarchar(max) resolved it.