After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
I have some experience at recovering from eclipse when it becomes unstartable for whatever reason, could these blog entries help you?
link (archived)
also search for "cannot start eclipse" (I am a new user, I can only post a single hyperlink, so I have to just ask that you search for the second :( sorry)
perhaps those allow you to recover your workspace as well, I hope it helps.
What I came here looking for is how to actually get the stash back, regardless of what I have checked out. In particular, I had stashed something, then checked out an older version, then poped it, but the stash was a no-op at that earlier time point, so the stash disappeared; I couldn't just do git stash
to push it back on the stack. This worked for me:
$ git checkout somethingOld
$ git stash pop
...
nothing added to commit but untracked files present (use "git add" to track)
Dropped refs/stash@{0} (27f6bd8ba3c4a34f134e12fe69bf69c192f71179)
$ git checkout 27f6bd8ba3c
$ git reset HEAD^ # Make the working tree differ from the parent.
$ git stash # Put the stash back in the stack.
Saved working directory and index state WIP on (no branch): c2be516 Some message.
HEAD is now at c2be516 Some message.
$ git checkout somethingOld # Now we are back where we were.
In retrospect, I should have been using git stash apply
not git stash pop
. I was doing a bisect
and had a little patch that I wanted to apply at every bisect
step. Now I'm doing this:
$ git reset --hard; git bisect good; git stash apply
$ # Run tests
$ git reset --hard; git bisect bad; git stash apply
etc.
I found a solution for converting the files to a .sql
file (you can then import the .sql
file to a server and recover the database), without needing to access the /var
directory, therefore you do not need to be a server admin to do this either.
It does require XAMPP or MAMP installed on your computer.
C:\XAMPP
), and the the sub-directory mysql\data
. The full path should be C:\XAMPP\mysql\data
Inside you will see folders of any other databases you have created. Copy & Paste the folder full of .myd
, .myi
and .frm
files into there. The path to that folder should be
C:\XAMPP\mysql\data\foldername\.mydfiles
Then visit localhost/phpmyadmin
in a browser. Select the database you have just pasted into the mysql\data
folder, and click on Export in the navigation bar. Chooses the export it as a .sql
file. It will then pop up asking where the save the file
And that is it! You (should) now have a .sql
file containing the database that was originally .myd
, .myi
and .frm
files. You can then import it to another server through phpMyAdmin by creating a new database and pressing 'Import' in the navigation bar, then following the steps to import it
class, interface, or enum expected
The above error is even possible when import statement is miss spelled. A proper statement is "import com.company.HelloWorld;"
If by mistake while code writing/editing it is miss written like "t com.company.HelloWorld;"
compiler will show "class, interface, or enum expected"
Go to command prompt at this path,
C:\Program Files (x86)\MySQL\MySQL Server 5.0\bin>
Then give this command to export your database (no space after -p)
mysqldump -u[username] -p[userpassword] yourdatabase > [filepath]wantedsqlfile.sql
The trick is this line
((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.login_input_hint_color));
use it in the onItemSelected. Here is my code with more context
List<String> list = getLabels(); // First item will be the placeholder
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// First item will be gray
if (position == 0) {
((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.login_input_hint_color));
} else {
((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.primary_text));
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Install the GenerateSerialVersionUID plugin by Olivier Descout.
Go to: menu File ? Settings ? Plugins ? Browse repositories ? GenerateSerialVersionUID
Install the plugin and restart.
Now you can generate the id from menu Code ? Generate ? serialVersionUID` or the shortcut.
The simplest way to display an object for debugging purposes:
console.log("data",data) // lets you unfold the object manually
If you want to display the object in the DOM, you should consider that it could contain strings that would be interpreted as HTML. Therefore, you need to do some escaping...
var s = JSON.stringify(data,null,2) // format
var e = new Option(s).innerHTML // escape
document.body.insertAdjacentHTML('beforeend','<pre>'+e+'</pre>') // display
An alternative to the answer provided by @Marc
SELECT SUBSTRING(LEFT(YOUR_FIELD, CHARINDEX('[', YOUR_FIELD) - 1), CHARINDEX(';', YOUR_FIELD) + 1, 100)
FROM YOUR_TABLE
WHERE CHARINDEX('[', YOUR_FIELD) > 0 AND
CHARINDEX(';', YOUR_FIELD) > 0;
This makes sure the delimiters exist, and solves an issue with the currently accepted answer where doing the LEFT last is working with the position of the last delimiter in the original string, rather than the revised substring.
For folks like me looking at the accepted answer, and not understanding why it's not working, you need to add quotes around your sub directory, in the green checked example,
x_file = open(os.path.join(direct, "5_1.txt"), "r")
should actually be
x_file = open(os.path.join('direct', "5_1.txt"), "r")
git log -p
will generate the a patch (the diff) for every commit selected. For a single file, use git log --follow -p $file
.
If you're looking for a particular change, use git bisect
to find the change in log(n) views by splitting the number of commits in half until you find where what you're looking for changed.
Also consider looking back in history using git blame
to follow changes to the line in question if you know what that is. This command shows the most recent revision to affect a certain line. You may have to go back a few versions to find the first change where something was introduced if somebody has tweaked it over time, but that could give you a good start.
Finally, gitk
as a GUI does show me the patch immediately for any commit I click on.
Example :
Your LMSInitialize
function is declared inside Scorm_API_12
function. So it can be seen only in Scorm_API_12
function's scope.
If you want to use this function like API.LMSInitialize("")
, declare Scorm_API_12
function like this:
function Scorm_API_12() {
var Initialized = false;
this.LMSInitialize = function(param) {
errorCode = "0";
if (param == "") {
if (!Initialized) {
Initialized = true;
errorCode = "0";
return "true";
} else {
errorCode = "101";
}
} else {
errorCode = "201";
}
return "false";
}
// some more functions, omitted.
}
var API = new Scorm_API_12();
You can use this:
Range("MyTable[#Data]").Rows.Count
You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:
If WorksheetFunction.CountA(Range("MyTable[#Data]"))
Well, you have some options.
You could configure sudo to not prompt for a password. This is not recommended, due to the security risks.
You could write an expect script to read the password and supply it to sudo when required, but that's clunky and fragile.
I would recommend designing the script to run as root and drop its privileges whenever they're not needed. Simply have it sudo -u someotheruser command
for the commands that don't require root.
(If they have to run specifically as the user invoking the script, then you could have the script save the uid and invoke a second script via sudo with the id as an argument, so it knows who to su to..)
The List
interface already has this solved.
int temp = 2;
if(bankAccNos.contains(bakAccNo)) temp=1;
More can be found in the documentation about List.
My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.
Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.
A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit
and see the there is a text
method.
To answer your specific question:
To make your GUI elements available to the rest of the object, preface them with self.
import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout
class Form(QDialog):
def __init__(self, parent=None):
super(Form, self).__init__(parent)
self.le = QLineEdit()
self.le.setObjectName("host")
self.le.setText("Host")
self.pb = QPushButton()
self.pb.setObjectName("connect")
self.pb.setText("Connect")
layout = QFormLayout()
layout.addWidget(self.le)
layout.addWidget(self.pb)
self.setLayout(layout)
self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
self.setWindowTitle("Learning")
def button_click(self):
# shost is a QString object
shost = self.le.text()
print shost
app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()
I use the Jetbrains Dot peek Software , you can try that too
Why not just use that:
manage.py inspectdb
Example output:
class GuardianUserobjectpermission(models.Model):
id = models.IntegerField(primary_key=True) # AutoField?
object_pk = models.CharField(max_length=255)
content_type = models.ForeignKey(DjangoContentType, models.DO_NOTHING)
permission = models.ForeignKey(AuthPermission, models.DO_NOTHING)
user = models.ForeignKey(CustomUsers, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'guardian_userobjectpermission'
unique_together = (('user', 'permission', 'object_pk'),)
This will do it:
/[A-Za-z\u00C0-\u00FF ]+/.exec('hipopótamo maçã pólen ñ poção água língüa')
It explicitly selects a range of unicode characters. It will work for latin characters, but other strange characters may be out of this range.
You need to define operator <
for the Class1.
Map needs to compare the values using operator < and hence you need to provide the same when user defined class are used as key.
class Class1
{
public:
Class1(int id);
bool operator <(const Class1& rhs) const
{
return id < rhs.id;
}
private:
int id;
};
Without seeing your code, it's hard to answer other than a stab in the dark. I would guess that the string you're passing to encodeURIComponent(), which is the correct method to use, is coming from the result of accessing the innerHTML property. The solution is to get the innerText/textContent property value instead:
var str,
el = document.getElementById("myUrl");
if ("textContent" in el)
str = encodeURIComponent(el.textContent);
else
str = encodeURIComponent(el.innerText);
If that isn't the case, you can use the replace() method to replace the HTML entity:
encodeURIComponent(str.replace(/&/g, "&"));
If your button is default "button" make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.
if you use js do like this
<form method="POST">
<button name="data" type="button" id="btnData" onclick="getData()">Click</button>
</form>
**If you use jquery use like this**
<form method="POST">
<button name="data" type="button" id="btnData">Click</button>
</form>
$('#btnData').click(function(e){
e.preventDefault();
// Code goes here
getData(); // your onclick function call here
});
$rootScope.$broadcast is a convenient way to raise a "global" event which all child scopes can listen for. You only need to use $rootScope
to broadcast the message, since all the descendant scopes can listen for it.
The root scope broadcasts the event:
$rootScope.$broadcast("myEvent");
Any child Scope can listen for the event:
$scope.$on("myEvent",function () {console.log('my event occurred');} );
Why we use $rootScope.$broadcast? You can use $watch
to listen for variable changes and execute functions when the variable state changes. However, in some cases, you simply want to raise an event that other parts of the application can listen for, regardless of any change in scope variable state. This is when $broadcast
is helpful.
Use this, it works 100% _your_videocode?rel=0&vq=hd1080"
Expanding on AnaPana's answer, how to remove an extension using pathlib (Python >= 3.4):
>>> from pathlib import Path
>>> filename = Path('/some/path/somefile.txt')
>>> filename_wo_ext = filename.with_suffix('')
>>> filename_replace_ext = filename.with_suffix('.jpg')
>>> print(filename)
/some/path/somefile.ext
>>> print(filename_wo_ext)
/some/path/somefile
>>> print(filename_replace_ext)
/some/path/somefile.jpg
I was dealing with this running Artifactory version 5.8.4. The "Set Me Up" function would generate settings.xml as follows:
<servers>
<server>
<username>${security.getCurrentUsername()}</username>
<password>${security.getEscapedEncryptedPassword()!"AP56eMPz8L12T5u4J6rWdqWqyhQ"}</password>
<id>central</id>
</server>
<server>
<username>${security.getCurrentUsername()}</username>
<password>${security.getEscapedEncryptedPassword()!"AP56eMPz8L12T5u4J6rWdqWqyhQ"}</password>
<id>snapshots</id>
</server>
</servers>
After using the mvn deploy -e -X switch, I noticed the credentials were not accurate. I removed the ${security.getCurrentUsername()} and replaced it with my username and removed ${security.getEscapedEncryptedPassword()!""} and just put my encrypted password which worked for me:
<servers>
<server>
<username>username</username>
<password>AP56eMPz8L12T5u4J6rWdqWqyhQ</password>
<id>central</id>
</server>
<server>
<username>username</username>
<password>AP56eMPz8L12T5u4J6rWdqWqyhQ</password>
<id>snapshots</id>
</server>
</servers>
Hope this helps!
2019-05-08 Android Studios needs an upgrade. upgrade Android Studios to 3.3.- and the error with .R; goes away.
Also the above methods also work.
Not tested but should work:
$("#MyDiv td input:checked").each(function()
{
alert($(this).attr("id"));
});
Underscore.js or Lodash.js for advanced array or object sorts
var data={
"models": {
"LTI": [
"TX"
],
"Carado": [
"A",
"T",
"A(????)",
"A(????)",
"T(????)",
"T(????)",
"A",
"T"
],
"SPARK": [
"SP110C 2",
"sp150r 18"
],
"Autobianchi": [
"A112"
]
}
};
var arr=[],
obj={};
for(var i in data.models){
arr.push([i, _.sortBy(data.models[i],function (el){return el;})]);
}
arr=_.sortBy(arr,function (el){
return el[0];
});
_.map(arr,function (el){return obj[el[0]]=el[1];});
console.log(obj);
You can change set orientation of linearlayout programmatically by:
LinearLayout linearLayout =new linearLayout(this);//just to give the clarity
linearLayout.setOrientation(LinearLayout.VERTICAL);
This is an old question, nevertheless this topic never ceases to bug me.
As many of the answers here and across the web focus on "enforcing" the interface, I'd like to suggest an alternative view:
I feel the lack of interfaces the most when I'm using multiple classes that behave similarly (i.e. implement an interface).
For example, I have an Email Generator that expects to receive Email Sections Factories, that "know" how to generate the sections' content and HTML. Hence, they all need to have some sort of getContent(id)
and getHtml(content)
methods.
The closest pattern to interfaces (albeit it's still a workaround) I could think of is using a class that'll get 2 arguments, which will define the 2 interface methods.
The main challenge with this pattern is that the methods either have to be static
, or to get as argument the instance itself, in order to access its properties. However there are cases in which I find this trade-off worth the hassle.
class Filterable {_x000D_
constructor(data, { filter, toString }) {_x000D_
this.data = data;_x000D_
this.filter = filter;_x000D_
this.toString = toString;_x000D_
// You can also enforce here an Iterable interface, for example,_x000D_
// which feels much more natural than having an external check_x000D_
}_x000D_
}_x000D_
_x000D_
const evenNumbersList = new Filterable(_x000D_
[1, 2, 3, 4, 5, 6], {_x000D_
filter: (lst) => {_x000D_
const evenElements = lst.data.filter(x => x % 2 === 0);_x000D_
lst.data = evenElements;_x000D_
},_x000D_
toString: lst => `< ${lst.data.toString()} >`,_x000D_
}_x000D_
);_x000D_
_x000D_
console.log('The whole list: ', evenNumbersList.toString(evenNumbersList));_x000D_
evenNumbersList.filter(evenNumbersList);_x000D_
console.log('The filtered list: ', evenNumbersList.toString(evenNumbersList));
_x000D_
You can use the function below which replaces the first occurrence of the word from right.
def replace_from_right(text: str, original_text: str, new_text: str) -> str:
""" Replace first occurrence of original_text by new_text. """
return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]
Java 8 provides a set of unsigned long operations that allows you to directly treat those Long variables as unsigned Long, here're some commonly used ones:
And additions, subtractions, and multiplications are the same for signed and unsigned longs.
for IE9 I found that a meta tag was required to set the mode
<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
<video width="400" height="300" preload controls>
<source src="movie.mp4" type="video/mp4" />
Your browser does not support the video tag
</video>
You can make your app as device/profile owner and call setScreenCaptureDisabled()
. From the docs, this api does the following:
public void setScreenCaptureDisabled (ComponentName admin, boolean disabled) Added in API level 21
Called by a device/profile owner to set whether the screen capture is disabled. Disabling screen capture also prevents the content from being shown on display devices that do not have a secure video output. See FLAG_SECURE for more details about secure surfaces and secure displays.
The calling device admin must be a device or profile owner. If it is not, a security exception will be thrown. Parameters admin Which DeviceAdminReceiver this request is associated with. disabled Whether screen capture is disabled or not.
Alternatively you can become an MDM(Mobile Device Management) partner app.OEMs provides additional APIs to their MDM partner apps to control the device.For example samsung provides api to control screen recording on the device to their MDM partners.
Currently this is the only way you can enforce screen capture restrictions.
If you want to use the font to draw with graphics2d or similar, this works:
InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)
There's nothing wrong with include file in head. It seems you forgot to add;
. Please try this one:
<body onload="imageRefreshBig();">
But as per my knowledge semicolons are optional. You can try with ;
but better debug code and see if chrome console gives any error.
I hope this helps.
You can also use the built-in template filter default
:
If value evaluates to False (e.g. None, an empty string, 0, False); the default "--" is displayed.
{{ profile.user.first_name|default:"--" }}
Documentation: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default
Using the awesome psutil
library it's pretty simple:
p = psutil.Process(pid)
p.terminate() #or p.kill()
If you don't want to install a new library, you can use the os
module:
import os
import signal
os.kill(pid, signal.SIGTERM) #or signal.SIGKILL
See also the os.kill
documentation.
If you are interested in starting the command python StripCore.py
if it is not running, and killing it otherwise, you can use psutil
to do this reliably.
Something like:
import psutil
from subprocess import Popen
for process in psutil.process_iter():
if process.cmdline() == ['python', 'StripCore.py']:
print('Process found. Terminating it.')
process.terminate()
break
else:
print('Process not found: starting it.')
Popen(['python', 'StripCore.py'])
Sample run:
$python test_strip.py #test_strip.py contains the code above
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
$killall python
$python test_strip.py
Process not found: starting it.
$python test_strip.py
Process found. Terminating it.
$python test_strip.py
Process not found: starting it.
Note: In previous psutil
versions cmdline
was an attribute instead of a method.
To run Anaconda Prompt using icon, I made an icon and put
%windir%\System32\cmd.exe "/K" C:\ProgramData\Anaconda3\Scripts\activate.bat C:\ProgramData\Anaconda3
The file location would be different in each computer.
at icon -> right click -> Property -> Shortcut -> Target
I see %HOMEPATH%
at icon -> right click -> Property -> Start in
OS: Windows 10, Library: Anaconda 10 (64 bit)
UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
MemberDetailsViewController* controller = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentiferInStoryBoard"];
[self.navigationController pushViewController:viewControllerName animated:YES];
Swift 4:
let storyBoard = UIStoryboard(name: "storyBoardName", bundle:nil)
let memberDetailsViewController = storyBoard.instantiateViewController(withIdentifier: "viewControllerIdentiferInStoryBoard") as! MemberDetailsViewController
self.navigationController?.pushViewController(memberDetailsViewController, animated:true)
You can do this using list:
new_list = list(fL)
Be aware that any spaces in the line will be included in this list, to the best of my knowledge.
The easiest way is to use the create
Manager method, which creates and saves the object in a single step.
for item in items:
MyModel.objects.create(name=item.name)
See https://github.com/php-pm/php-pm.
Works fine with symphony.
But I'm fighting with it, trying run a slim app
Be careful that when you using:
curl -H "Authorization: token_str" http://www.example.com
token_str
and Authorization
must be separated by white space, otherwise server-side will not get the HTTP_AUTHORIZATION
environment.
The default behavior of Commit PL/SQL block:
You should explicitly commit or roll back every transaction. Whether you issue the commit or rollback in your PL/SQL program or from a client program depends on the application logic. If you do not commit or roll back a transaction explicitly, the client environment determines its final state.
For example, in the SQLPlus environment, if your PL/SQL block does not include a COMMIT or ROLLBACK statement, the final state of your transaction depends on what you do after running the block. If you execute a data definition, data control, or COMMIT statement or if you issue the EXIT, DISCONNECT, or QUIT command, Oracle commits the transaction. If you execute a ROLLBACK statement or abort the SQLPlus session, Oracle rolls back the transaction.
https://docs.oracle.com/cd/B19306_01/appdev.102/b14261/sqloperations.htm#i7105
There's a promising javascript library called Arrive that looks like a great way to start taking advantage of the mutation observers once the browser support becomes commonplace.
It is possible using Apex Recovery Tool,i have successfully recovered my table rows which i accidentally deleted
if you download the trial version it will recover only 10th row
check here http://www.apexsql.com/sql_tools_log.aspx
A solution to ensure that images don't get cut when printed in a Web page is to have the following CSS rule:
@media print {
img {
max-width:100% !important;
}
}
Another way to do this is with operator -replace.
$TestString = "test=keep this, but not this."
$NewString = $TestString -replace ".*=" -replace ",.*"
.*=
means any number of characters up to and including an equals sign.
,.*
means a comma followed by any number of characters.
Since you are basically deleting those two parts of the string, you don't have to specify an empty string with which to replace them. You can use multiple -replaces, but just remember that the order is left-to-right.
You can use MemberwiseClone
obj myobj2 = (obj)myobj.MemberwiseClone();
The copy is a shallow copy which means the reference properties in the clone are pointing to the same values as the original object but that shouldn't be an issue in your case as the properties in obj
are of value types.
If you own the source code, you can also implement ICloneable
Check the latest Jest (v 0.22): https://github.com/facebook/jest
The Facebook team adds the Istanbul code coverage output as part of the coverage report and you can use it directly.
After executing Jest, you can get a coverage report in the console and under the root folder set by Jest, you will find the coverage report in JSON and HTML format.
FYI, if you install from npm, you might not get the latest version; so try the GitHub first and make sure the coverage is what you need.
For-loop in C:
for(int x = 0; x<=3; x++)
{
//Do something!
}
The same loop in 8086 assembler:
xor cx,cx ; cx-register is the counter, set to 0
loop1 nop ; Whatever you wanna do goes here, should not change cx
inc cx ; Increment
cmp cx,3 ; Compare cx to the limit
jle loop1 ; Loop while less or equal
That is the loop if you need to access your index (cx). If you just wanna to something 0-3=4 times but you do not need the index, this would be easier:
mov cx,4 ; 4 iterations
loop1 nop ; Whatever you wanna do goes here, should not change cx
loop loop1 ; loop instruction decrements cx and jumps to label if not 0
If you just want to perform a very simple instruction a constant amount of times, you could also use an assembler-directive which will just hardcore that instruction
times 4 nop
Do-while-loop in C:
int x=1;
do{
//Do something!
}
while(x==1)
The same loop in assembler:
mov ax,1
loop1 nop ; Whatever you wanna do goes here
cmp ax,1 ; Check wether cx is 1
je loop1 ; And loop if equal
While-loop in C:
while(x==1){
//Do something
}
The same loop in assembler:
jmp loop1 ; Jump to condition first
cloop1 nop ; Execute the content of the loop
loop1 cmp ax,1 ; Check the condition
je cloop1 ; Jump to content of the loop if met
For the for-loops you should take the cx-register because it is pretty much standard. For the other loop conditions you can take a register of your liking. Of course replace the no-operation instruction with all the instructions you wanna perform in the loop.
If you mean how to remove the 'checked' state from all checkboxes:
$('input:checkbox').removeAttr('checked');
Let's say your image is a 16x16 .png icon called icon.png Use the power of CSS!
CSS:
input#image-button{
background: #ccc url('icon.png') no-repeat top left;
padding-left: 16px;
height: 16px;
}
HTML:
<input type="submit" id="image-button" value="Text"></input>
This will put the image to the left of the text.
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
command.Parameters.AddWithValue("@param1", klantId));
command.Parameters.AddWithValue("@param2", klantNaam));
command.Parameters.AddWithValue("@param3", klantVoornaam));
command.ExecuteNonQuery();
}
}
svn revert will undo any local changes you've made
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
You can access component one's method from component two..
componentOne
ngOnInit() {}
public testCall(){
alert("I am here..");
}
componentTwo
import { oneComponent } from '../one.component';
@Component({
providers:[oneComponent ],
selector: 'app-two',
templateUrl: ...
}
constructor(private comp: oneComponent ) { }
public callMe(): void {
this.comp.testCall();
}
componentTwo html file
<button (click)="callMe()">click</button>
Lots of good answers had been added. I still want to contribute, might be it will clarify slightly more.
When you pass an instance as an argument to the method it passes the copy
of the instance. Now, if the instance you pass is a value type
(resides in the stack
) you pass the copy of that value, so if you modify it, it won't be reflected in the caller. If the instance is a reference type you pass the copy of the reference(again resides in the stack
) to the object. So you got two references to the same object. Both of them can modify the object. But if within the method body, you instantiate new object your copy of the reference will no longer refer to the original object, it will refer to the new object you just created. So you will end up having 2 references and 2 objects.
Just to clarify what moonlightcheese stated: To trigger a button click event through code in Android provide the following:
buttonName.performClick();
Try using an empty collapse argument within the paste function:
paste(sdata, collapse = '')
This error comes for me in windows application while calling server dll from client. After system restart it works fine
You can check the schema at http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition/ReportDefinition.xsd
Search for xsd:complexType name="StyleType"
This will list out all the possible Styles you can use.
Specific to your question however, you can use the Format style.
Format
Specify the data format to use for values that appear in the textbox.
Valid values include Default, Number, Date, Time, Percentage, and Currency.
Link to MSDN: http://msdn.microsoft.com/en-us/library/ms251684(VS.80).aspx
Try System.Func<T>
and System.Action
You're thinking too complicated. It's actually just $('#'+openaddress)
.
Open your PHPMyAdmin, don't select any database and look for Binary Log
tab .
You can select different logs from a drop down list and press GO
Button to view them.
Follow the steps given below:
Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.
Open your MS-DOS command prompt using "cmd" inside the Run window. Inside it navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.
Execute the following command in the command prompt: mysqld.exe -u root --skip-grant-tables
Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.
Navigate to your MySQL bin folder, such as C:\MySQL\bin using the cd command.
Enter mysql
and press enter.
You should now have the MySQL command prompt working. Type use mysql;
so that we switch to the "mysql" database.
Execute the following command to update the password:
UPDATE user SET Password = PASSWORD('NEW_PASSWORD') WHERE User = 'root';
However, you can now run any SQL command that you wish.
After you are finished close the first command prompt and type exit;
in the second command prompt windows to disconnect successfully. You can now start the MySQL service.
One possible PHP solution:
// load XML to SimpleXML
$x = simplexml_load_string($xmlstr);
// index it by title once
$index = array();
foreach ($x->CD as &$cd) {
$title = strtolower((string)$cd['title']);
if (!array_key_exists($title, $index)) $index[$title] = array();
$index[$title][] = &$cd;
}
// query the index
$result = $index[strtolower("EMPIRE BURLESQUE")];
For those using Flask, put this in your __init__.py
:
def clever_function():
return u'HELLO'
app.jinja_env.globals.update(clever_function=clever_function)
and in your template call it with {{ clever_function() }}
for i in count:
means for i in 7:
, which won't work. The bit after the in
should be of an iterable type, not a number. Try this:
for i in range(count):
For people landing here from google like me and just want to build containers using multiple docker-compose files with one shared service:
Sometimes you have different projects that would share e.g. a database docker container. Only the first run should start the DB-Docker, the second should be detect that the DB is already running and skip this. To achieve such a behaviour we need the Dockers to lay in the same network and in the same project. Also the docker container name needs to be the same.
1st: Set the same network and container name in docker-compose
docker-compose in project 1:
version: '3'
services:
service1:
depends_on:
- postgres
# ...
networks:
- dockernet
postgres:
container_name: project_postgres
image: postgres:10-alpine
restart: always
# ...
networks:
- dockernet
networks:
dockernet:
docker-compose in project 2:
version: '3'
services:
service2:
depends_on:
- postgres
# ...
networks:
- dockernet
postgres:
container_name: project_postgres
image: postgres:10-alpine
restart: always
# ...
networks:
- dockernet
networks:
dockernet:
2nd: Set the same project using -p
param or put both files in the same directory.
docker-compose -p {projectname} up
pd.DataFrame({'date' : dict_dates.keys() , 'date_value' : dict_dates.values() })
Android provides a non straight foward solution: BitmapDrawable
. To get the Bitmap , we'll have to provide the resource id R.drawable.flower_pic
to the a BitmapDrawable
and then cast it to a Bitmap
.
Bitmap bm = ((BitmapDrawable) getResources().getDrawable(R.drawable.flower_pic)).getBitmap();
With Swift 3, according to your needs, you may choose one of the two following ways to solve your problem.
You can use a DateComponentsFormatter
to create strings for your app’s interface. DateComponentsFormatter
has a maximumUnitCount
property with the following declaration:
var maximumUnitCount: Int { get set }
Use this property to limit the number of units displayed in the resulting string. For example, with this property set to 2, instead of “1h 10m, 30s”, the resulting string would be “1h 10m”. Use this property when you are constrained for space or want to round up values to the nearest large unit.
By setting maximumUnitCount
's value to 1
, you are guaranteed to display the difference in only one DateComponentsFormatter
's unit (years, months, days, hours or minutes).
The Playground code below shows how to display the difference between two dates:
import Foundation
let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [NSCalendar.Unit.year, .month, .day, .hour, .minute]
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
let timeDifference = dateComponentsFormatter.string(from: oldDate, to: newDate)
print(String(reflecting: timeDifference)) // prints Optional("5 hours")
Note that DateComponentsFormatter
rounds up the result. Therefore, a difference of 4 hours and 30 minutes will be displayed as 5 hours.
If you need to repeat this operation, you can refactor your code:
import Foundation
struct Formatters {
static let dateComponentsFormatter: DateComponentsFormatter = {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.allowedUnits = [NSCalendar.Unit.year, .month, .day, .hour, .minute]
dateComponentsFormatter.maximumUnitCount = 1
dateComponentsFormatter.unitsStyle = DateComponentsFormatter.UnitsStyle.full
return dateComponentsFormatter
}()
}
extension Date {
func offset(from: Date) -> String? {
return Formatters.dateComponentsFormatter.string(from: oldDate, to: self)
}
}
let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)
let timeDifference = newDate.offset(from: oldDate)
print(String(reflecting: timeDifference)) // prints Optional("5 hours")
If you don't need to display with formatting the difference between two dates to the user, you can use Calendar
. Calendar
has a method dateComponents(_:from:to:)
that has the following declaration:
func dateComponents(_ components: Set<Calendar.Component>, from start: Date, to end: Date) -> DateComponents
Returns the difference between two dates.
The Playground code below that uses dateComponents(_:from:to:)
shows how to retrieve the difference between two dates by returning the difference in only one type of Calendar.Component
(years, months, days, hours or minutes).
import Foundation
let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)
let descendingOrderedComponents = [Calendar.Component.year, .month, .day, .hour, .minute]
let dateComponents = Calendar.current.dateComponents(Set(descendingOrderedComponents), from: oldDate, to: newDate)
let arrayOfTuples = descendingOrderedComponents.map { ($0, dateComponents.value(for: $0)) }
for (component, value) in arrayOfTuples {
if let value = value, value > 0 {
print(component, value) // prints hour 4
break
}
}
If you need to repeat this operation, you can refactor your code:
import Foundation
extension Date {
func offset(from: Date) -> (Calendar.Component, Int)? {
let descendingOrderedComponents = [Calendar.Component.year, .month, .day, .hour, .minute]
let dateComponents = Calendar.current.dateComponents(Set(descendingOrderedComponents), from: from, to: self)
let arrayOfTuples = descendingOrderedComponents.map { ($0, dateComponents.value(for: $0)) }
for (component, value) in arrayOfTuples {
if let value = value, value > 0 {
return (component, value)
}
}
return nil
}
}
let oldDate = Date(timeIntervalSinceReferenceDate: -16200)
let newDate = Date(timeIntervalSinceReferenceDate: 0)
if let (component, value) = newDate.offset(from: oldDate) {
print(component, value) // prints hour 4
}
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
This keymap will duplicate the current line if nothing is selected or duplicate the selected words.
Access:
File/Preferences/Keyboard shortcuts
In the right top corner, click on Open Keyboard Shortcuts (JSON).
Insert this keymap:
{
"key": "shift+alt+d",
"command": "editor.action.duplicateSelection"
}
Use alt+arrows up/down to move the line (Default behaviour of VS Code).
For me - the folder from which the service was to run, and the files in it, were encrypted using the Windows "Encrypt" option. Removing that and - voila!
The simplest in my opinion is just this:
it = iter([1,2,3,4,5,6])
for x, y in zip(it, it):
print x, y
Out: 1 2
3 4
5 6
No extra imports or anything. And very elegant, in my opinion.
I got this error when I tried to install a Xamarin project built against Android N preview on a phone running api v23. Solution is to not do that.
if (!obj) {
// object (not class!) doesn't exist yet
}
else ...
String strWebData="html...." //**Your html string**
WebView webDetail=(WebView) findViewById(R.id.webView1);
WebSettings websetting = webDetail.getSettings();
websetting.setDefaultTextEncodingName("utf-8");
webDetail.loadData(strWebData, "text/html; charset=utf-8", null);
Perhaps I misunderstood the question but doesn't this do it?
int NumDigits(int x)
{
x = abs(x);
return (x < 10 ? 1 :
(x < 100 ? 2 :
(x < 1000 ? 3 :
(x < 10000 ? 4 :
(x < 100000 ? 5 :
(x < 1000000 ? 6 :
(x < 10000000 ? 7 :
(x < 100000000 ? 8 :
(x < 1000000000 ? 9 :
10)))))))));
}
Try split(",")[i]
where i
is the index in result array. split
gives array below
["test1", " test2", " test3", " test4", " test5"]
whose element can be accessed by index.
You may get ORA-01031: insufficient privileges
instead of ORA-00942: table or view does not exist
when you have at least one privilege on the table, but not the necessary privilege.
Create schemas
SQL> create user schemaA identified by schemaA;
User created.
SQL> create user schemaB identified by schemaB;
User created.
SQL> create user test_user identified by test_user;
User created.
SQL> grant connect to test_user;
Grant succeeded.
Create objects and privileges
It is unusual, but possible, to grant a schema a privilege like DELETE without granting SELECT.
SQL> create table schemaA.table1(a number);
Table created.
SQL> create table schemaB.table2(a number);
Table created.
SQL> grant delete on schemaB.table2 to test_user;
Grant succeeded.
Connect as TEST_USER and try to query the tables
This shows that having some privilege on the table changes the error message.
SQL> select * from schemaA.table1;
select * from schemaA.table1
*
ERROR at line 1:
ORA-00942: table or view does not exist
SQL> select * from schemaB.table2;
select * from schemaB.table2
*
ERROR at line 1:
ORA-01031: insufficient privileges
SQL>
you can use this code as template please customize it as per your requirement.
DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();
list.add(textField.getText());
list.add(comboBox.getSelectedItem());
model.addRow(list.toArray());
table.setModel(model);
here DefaultTableModel
is used to add rows in JTable
,
you can get more info here.
A gc-friendly piece of code:
public static<X> X[] arrayOfNotNull(X[] array) {
for (int p=0, N=array.length; p<N; ++p) {
if (array[p] == null) {
int m=p; for (int i=p+1; i<N; ++i) if (array[i]!=null) ++m;
X[] res = Arrays.copyOf(array, m);
for (int i=p+1; i<N; ++i) if (array[i]!=null) res[p++] = array[i];
return res;
}
}
return array;
}
It returns the original array if it contains no nulls. It does not modify the original array.
Type ctor, and then press the Tab key.
Use this function:
var getCleanUrl = function(url) {_x000D_
return url.replace(/#.*$/, '').replace(/\?.*$/, '');_x000D_
};_x000D_
_x000D_
// get rid of hash and params_x000D_
console.log(getCleanUrl('https://sidanmor.com/?firstname=idan&lastname=mor'));
_x000D_
If you want all the href parts, use this:
var url = document.createElement('a');_x000D_
url.href = 'https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container';_x000D_
_x000D_
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results-close-container_x000D_
console.log(url.protocol); // https:_x000D_
console.log(url.host); // developer.mozilla.org_x000D_
console.log(url.hostname); // developer.mozilla.org_x000D_
console.log(url.port); // (blank - https assumes port 443)_x000D_
console.log(url.pathname); // /en-US/search_x000D_
console.log(url.search); // ?q=URL_x000D_
console.log(url.hash); // #search-results-close-container_x000D_
console.log(url.origin); // https://developer.mozilla.org
_x000D_
It's as simple as:
if (value.compareTo(BigDecimal.ZERO) > 0)
The documentation for compareTo
actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo
method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.
First you have to download the certificate from this link
https://curl.haxx.se/ca/cacert.pem
and put it in a location you want the name of downloadable file is : cacert.pem So in my case I will put it under C:\wamp64\bin\php\cacert.pem
Then you have to specify the location of the php.ini file
For example, I am using php 7 the php.ini file is located at : C:\wamp64\bin\php\php7.0.10\php.ini
So access to that file and uncommit this line ;openssl.cafile
also update it to be looks like this openssl.cafile="C:\wamp64\bin\php\cacert.pem"
Finally restart your apache server and that's all
Probably the best high level description I have found for tail calls, recursive tail calls and tail call optimization is the blog post
"What the heck is: A tail call"
by Dan Sugalski. On tail call optimization he writes:
Consider, for a moment, this simple function:
sub foo (int a) { a += 15; return bar(a); }
So, what can you, or rather your language compiler, do? Well, what it can do is turn code of the form
return somefunc();
into the low-level sequencepop stack frame; goto somefunc();
. In our example, that means before we callbar
,foo
cleans itself up and then, rather than callingbar
as a subroutine, we do a low-levelgoto
operation to the start ofbar
.Foo
's already cleaned itself out of the stack, so whenbar
starts it looks like whoever calledfoo
has really calledbar
, and whenbar
returns its value, it returns it directly to whoever calledfoo
, rather than returning it tofoo
which would then return it to its caller.
And on tail recursion:
Tail recursion happens if a function, as its last operation, returns the result of calling itself. Tail recursion is easier to deal with because rather than having to jump to the beginning of some random function somewhere, you just do a goto back to the beginning of yourself, which is a darned simple thing to do.
So that this:
sub foo (int a, int b) { if (b == 1) { return a; } else { return foo(a*a + a, b - 1); }
gets quietly turned into:
sub foo (int a, int b) { label: if (b == 1) { return a; } else { a = a*a + a; b = b - 1; goto label; }
What I like about this description is how succinct and easy it is to grasp for those coming from an imperative language background (C, C++, Java)
I use Intellij IDEA but I think it will also work in Android Studio, can you see the "Event Log" at IDE right bottom corner, did it have some message like that "Android framework is detected in the project Configure", that means you should have a framework configuration. If so, just follow the message link.
In the same way, you can go to "File > Project Structure > Modules" , and then add a Android Facet.
by the way, if I want use a customized namespace like you do, I'll write the resource identifier as my package name as I define the AndroidManifest.xml package attribute of the manifest element, below is my code.
<manifest package="com.my.name.android">
...
</manifest>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/com.my.name.android">
</RelativeLayout>
Hope this helps you.
in addition to UseSsl, you have to include smtp port 587 to make it work.
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
First, the enum methods shouldn't be in all caps. They are methods just like other methods, with the same naming convention.
Second, what you are doing is not the best possible way to set up your enum. Instead of using an array of values for the values, you should use separate variables for each value. You can then implement the constructor like you would any other class.
Here's how you should do it with all the suggestions above:
public enum States {
...
MASSACHUSETTS("Massachusetts", "MA", true),
MICHIGAN ("Michigan", "MI", false),
...; // all 50 of those
private final String full;
private final String abbr;
private final boolean originalColony;
private States(String full, String abbr, boolean originalColony) {
this.full = full;
this.abbr = abbr;
this.originalColony = originalColony;
}
public String getFullName() {
return full;
}
public String getAbbreviatedName() {
return abbr;
}
public boolean isOriginalColony(){
return originalColony;
}
}
Does this work:
$msgid = $_GET['msgid'];
$oldMessage = '';
$deletedFormat = '';
//read the entire string
$str=file_get_contents('msghistory.txt');
//replace something in the file string - this is a VERY simple example
$str=str_replace($oldMessage, $deletedFormat,$str);
//write the entire string
file_put_contents('msghistory.txt', $str);
As long as you fix the width of the table itself and set the table-layout property, this is pretty simple :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">
td { width: 30px; overflow: hidden; }
table { width : 90px; table-layout: fixed; }
</style>
</head>
<body>
<table border="2">
<tr>
<td>word</td>
<td>two words</td>
<td>onereallylongword</td>
</tr>
</table>
</body>
</html>
I've tested this in IE6 and 7 and it seems to work fine.
How about this solution:
$type = gettype($your_iteratable);
$types = array(
'array',
'object'
);
if (in_array($type, $types)) {
// foreach code comes here
}
I noticed following line from error.
exact fetch returns more than requested number of rows
That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.
Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.
So, I truncated dual
table and inserted only row which X
value. And, everything working fine.
You have already staged the changes (presumably by running git add
), so in order to get their diff, you need to run:
git diff --cached
(A plain git diff
will only show unstaged changes.)
For example:
You can try another way like that:
<div class="content">
Australia
</div>
jQuery code:
$(".content").css({
background: "#d1d1d1",
fontSize: "30px"
})
Now you can add more css property as you want.
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
There are some similar questions: Spring MVC response encoding issue, Custom HttpMessageConverter with @ResponseBody to do Json things.
However, my simple solution:
@RequestMapping(method=RequestMethod.GET,value="/GetMyList")
public ModelAndView getMyList(){
String test = "ccždš";
...
ModelAndView mav = new ModelAndView("html_utf8");
mav.addObject("responseBody", test);
}
and the view html_utf8.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>${responseBody}
No additional classes and configuration.
And You can also create another view (for example json_utf8) for other content type.
Just call dict()
on the list of tuples directly
>>> my_list = [('a', 1), ('b', 2)]
>>> dict(my_list)
{'a': 1, 'b': 2}
if you want to select column with specific name then just do
A=mtcars[,which(conames(mtcars)==cols[1])]
#and then
colnames(mtcars)[A]=cols[1]
you can run it in loop as well reverse way to add dynamic name eg if A is data frame and xyz is column to be named as x then I do like this
A$tmp=xyz
colnames(A)[colnames(A)=="tmp"]=x
again this can also be added in loop
As Inian suggested, you should alias python to point to python 3. It is very easy to do, and very easy to switchback, personally i have an alias setup for p2=python2 and p3=python3 as well to save on keystrokes. Read here for more information: How do I create a Bash alias?
Here is an example of doing so for python:
alias python=python3
Like so:
$ python --version
Python 2.7.6
$ python3 --version
Python 3.4.3
$ alias python=python3
$ python --version
Python 3.4.3
See here for the original: https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3
In Anon's answer:
"If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__
, you must call it yourself, since that will not happen automatically"
It's incredible: he is wording exactly the contrary of the principle of inheritance.
It is not that "something from super's __init__
(...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__
is overriden by the definition of the derived-clas __init__
So then, WHY defining a derived_class' __init__
, since it overrides what is aimed at when someone resorts to inheritance ??
It's because one needs to define something that is NOT done in the base-class' __init__
, and the only possibility to obtain that is to put its execution in a derived-class' __init__
function.
In other words, one needs something in base-class' __init__
in addition to what would be automatically done in the base-classe' __init__
if this latter wasn't overriden.
NOT the contrary.
Then, the problem is that the desired instructions present in the base-class' __init__
are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__
, in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__
.
That's exactly what is said in the official doc:
An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance
That's all the story:
when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__
function in the derived class
when the aim is to REPLACE the initialization performed by the base-class, __init__
must be defined in the derived-class
when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__
must be defined , comprising an explicit call to the base-class __init__
What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.
Use below code to generate files on fly..
<? //Generate text file on the fly
header("Content-type: text/plain");
header("Content-Disposition: attachment; filename=savethis.txt");
// do your Db stuff here to get the content into $content
print "This is some text...\n";
print $content;
?>
ok i can run android from cordova, i changed ANDROID_HOME to,
export ANDROID_HOME=/usr/local/opt/android-sdk
I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen()
after 'dynamic library').
They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.
Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.
This will do the trick:
SELECT CONVERT(char(10), GetDate(),126)
run this:
rm -rf node_modules && npm cache clear && npm install
Node will install from whatever is cached. So if you clear everything out first, then NPM use 0.10.xx, it will revert properly.
You can call the btnTest_Click just like any other function.
The most basic form would be this:
btnTest_Click(this, null);
I had the same problem and solved by using Newtonsoft.Json;
var list = JsonConvert.SerializeObject(model,
Formatting.None,
new JsonSerializerSettings() {
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
});
return Content(list, "application/json");
TypeError
# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'
# same intent with a f-string
i = 15
test = f'Here is a test that can be run {i} times'
print(test)
# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i # will cause a TypeError
# should be
t = f'test{i}'
print(t)
# output
'test15'
int
.dtype
i = '15'
# t = 15 + i # will cause a TypeError
# convert the string to int
t = 15 + int(i)
print(t)
# output
30
TypeError
shown in the question title, which is why people seem to be coming to this question.TypeError
is caused because message
type is a str
.char
, a str
type, to an int
char
to an int
secret_string
needs to be initialized with 0
instead of ""
.ValueError: chr() arg not in range(0x110000)
because 7429146
is out of range for chr()
.message = input("Enter a message you want to be revealed: ")
secret_string = 0
for char in message:
char = int(char)
value = char + 742146
secret_string += ord(chr(value))
print(f'\nRevealed: {secret_string}')
# Output
Enter a message you want to be revealed: 999
Revealed: 2226465
message
is now an int
type, so for char in message:
causes TypeError: 'int' object is not iterable
message
is converted to int
to make sure the input
is an int
.str()
value
to Unicode with chr
ord
while True:
try:
message = str(int(input("Enter a message you want to be decrypt: ")))
break
except ValueError:
print("Error, it must be an integer")
secret_string = ""
for char in message:
value = int(char) + 10000
secret_string += chr(value)
print("Decrypted", secret_string)
# output
Enter a message you want to be decrypt: 999
Decrypted ???
Enter a message you want to be decrypt: 100
Decrypted ???
Here are a few ways of removing a single '
from a string in python.
replace
is usually used to return a string with all the instances of the substring replaced.
"A single ' char".replace("'","")
str.translate
To remove characters you can pass the first argument to the funstion with all the substrings to be removed as second.
"A single ' char".translate(None,"'")
You will have to use str.maketrans
"A single ' char".translate(str.maketrans({"'":None}))
Regular Expressions using re
are even more powerful (but slow) and can be used to replace characters that match a particular regex rather than a substring.
re.sub("'","","A single ' char")
Other Ways
There are a few other ways that can be used but are not at all recommended. (Just to learn new ways). Here we have the given string as a variable string
.
Using list comprehension
''.join([c for c in string if c != "'"])
Using generator Expression
''.join(c for c in string if c != "'")
Another final method can be used also (Again not recommended - works only if there is only one occurrence )
I coincidentally found out that Break <UnknownLabel>
(e.g. simply Break Script
, where the label Script
doesn't exists) appears to break out of the entire script (even from within a function) and keeps the host alive.
This way you could create a function that breaks the script from anywhere (e.g. a recursive loop) without knowing the current scope (and creating labels):
Function Quit($Text) {
Write-Host "Quiting because: " $Text
Break Script
}
If you came here like I did, after receiving a similar error when trying the React Getting Started guide, you might like to know that the problem could have been caused by not having installed Watchman. Download it here, or install it with Homebrew with brew install watchman
and try again: https://facebook.github.io/watchman/docs/install.html
PS: You might want to do a brew update
first.
If you are using BIDS with SQL 2008 R2 you can only get the "Report Data" menu by clicking inside the actual report layout itself.
Click inside the actual report layout.
Now select "View" from the main menu bar.
Now select "Report Data" which is the last item.
You must press enter after continuation character
Note: Space after continuation character leads to error
cost = {"apples": [3.5, 2.4, 2.3], "bananas": [1.2, 1.8]}
0.9 * average(cost["apples"]) + \ """enter here"""
0.1 * average(cost["bananas"])
Try this: tar -cf file.tar file-to-compress ; xz -z file.tar
Note:
|
because this runs commands simultaneously. Using ;
or &
executes commands one after another.The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:
http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial
You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.
Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.
If you look at the line which is causing the error, you'll see this:
from numpy._distributor_init import NUMPY_MKL # requires numpy+mkl
This line comment states the dependency as numpy+mkl
(numpy
with Intel Math Kernel Library). This means that you've installed the numpy
by pip
, but the scipy
was installed by precompiled archive, which expects numpy+mkl
.
This problem can be easy solved by installation for numpy+mkl
from whl file from here.
As Maciej Jonczyk mentioned, you may also need to increase margins
par(las=2)
par(mar=c(8,8,1,1)) # adjust as needed
plot(...)
Without mod_expires it will be harder to set expiration headers on your files. For anything generated you can certainly set some default headers on the answer, doing the job of mod_expires like that:
<?php header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); ?>
(taken from: Stack Overflow answer from @brianegge, where the mod_expires solution is also explained)
Now this won't work for static files, like your javascript files. As for static files there is only apache (without any expiration module) between the browser and the source file.
To prevent caching of javascript files, which is done on your browser, you can use a random token at the end of the js url, something like ?rd=45642111
, so the url looks like:
<script type="texte/javascript" src="my/url/myjs.js?rd=4221159546">
If this url on the page is generated by a PHP file you can simply add the random part with PHP. This way of randomizing url by simply appending random query string parameters is the base thing upôn no-cache setting of ajax jQuery request for example. The browser will never consider 2 url having different query strings to be the same, and will never use the cached version.
EDIT
Note that you should alos test mod_headers. If you have mod_headers you can maybe set the Expires headers directly with the Header keyword.
I think it actually depends on what are you going to do inside your doSomething
function. If you are going to access MyObject
properties using this keyword then you have to use that. But I think that the following code fragment will also work if you are not doing any special things using object(MyObject)
properties.
function doSomething(){
.........
}
$("#foobar").ready('click', function(){
});
myList[1] is an element of myList and it's type is string.
myList[1] is str, you can not append to it. myList is a list, you should have been appending to it.
>>> myList = [1, 'from form', [1,2]]
>>> myList[1]
'from form'
>>> myList[2]
[1, 2]
>>> myList[2].append('t')
>>> myList
[1, 'from form', [1, 2, 't']]
>>> myList[1].append('t')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
>>>
Use line-height:30px
for the span so that text is align with the image:
<div>
<img style="width:30px; height:30px;">
<span style="line-height:30px;">Doesn't work.</span>
</div>
git show <revhash>
Documentation here. Or if that doesn't work, try Google Code's GIT Documentation
The command build
in pipeline is there to trigger other jobs in jenkins.
The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git
Here I can't see even a single correct answer for this question (in WinForms tag) and it's strange for such frequent question.
Items of a ListBox
control may be DataRowView
, Complex Objects, Anonymous types, primary types and other types. Underlying value of an item should be calculated base on ValueMember
.
ListBox
control has a GetItemText
which helps you to get the item text regardless of the type of object you added as item. It really needs such GetItemValue
method.
GetItemValue Extension Method
We can create GetItemValue
Extension Method to get item value which works like GetItemText
:
using System;
using System.Windows.Forms;
using System.ComponentModel;
public static class ListControlExtensions
{
public static object GetItemValue(this ListControl list, object item)
{
if (item == null)
throw new ArgumentNullException("item");
if (string.IsNullOrEmpty(list.ValueMember))
return item;
var property = TypeDescriptor.GetProperties(item)[list.ValueMember];
if (property == null)
throw new ArgumentException(
string.Format("item doesn't contain '{0}' property or column.",
list.ValueMember));
return property.GetValue(item);
}
}
Using above method you don't need to worry about settings of ListBox
and it will return expected Value
for an item. It works with List<T>
, Array
, ArrayList
, DataTable
, List of Anonymous Types, list of primary types and all other lists which you can use as data source. Here is an example of usage:
//Gets underlying value at index 2 based on settings
this.listBox1.GetItemValue(this.listBox1.Items[2]);
Since we created the GetItemValue
method as an extension method, when you want to use the method, don't forget to include the namespace which you put the class in.
This method is applicable on ComboBox
and CheckedListBox
too.
@choz answer is the correct way. If you have many usages and want to make sure it works everywhere without changes you can add these small migration-snippet:
/* Migration jQuery from 1.8 to 3.x */
jQuery.fn.load = function (callback) {
var el = $(this);
el.on('load', callback);
return el;
};
In this case you got no erros on other nodes e.g. on $image
like in @Korsmakolnikov answer!
const $image = $('img.image').load(function() {
$(this).doSomething();
});
$image.doSomethingElseWithTheImage();
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render
render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])
render()
is a brand spanking new shortcut for render_to_response
in 1.3 that will automatically use RequestContext
that I will most definitely be using from now on.
2020 EDIT: It should be noted that render_to_response()
was removed in Django 3.0
https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response
render_to_response(template[, dictionary][, context_instance][, mimetype])¶
render_to_response
is your standard render function used in the tutorials and such. To use RequestContext
you'd have to specify context_instance=RequestContext(request)
direct_to_template
is a generic view that I use in my views (as opposed to in my urls) because like the new render()
function, it automatically uses RequestContext
and all its context_processor
s.
But direct_to_template
should be avoided as function based generic views are deprecated. Either use render
or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/
I'm happy I haven't typed RequestContext
in a long, long time.
No, Cookies can be cleaned only by setting the Expiry date for each of them.
if (Request.Cookies["UserSettings"] != null)
{
HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
At the moment of Session.Clear()
:
Session
collection are removed. Session_End
event is not happen.If you use this method during logout, you should also use the Session.Abandon
method to
Session_End
event:
Try put this in the head of the document:
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico"/>
if your text size is small, you should make the width of your text view to be "fill_parent". After that, you can set your TextView Gravity to center :
TextView textView = new TextView(this);
textView.setText(message);
textView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
textView.setGravity(Gravity.CENTER);
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
If you're generating your javascript with a php file, add this as the beginning of your file:
<?php Header("Content-Type: application/x-javascript; charset=UTF-8"); ?>
The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName)
.
Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)
In this case you have to use @foreach
@foreach (var item in Model.Foos)
{
@Html.DisplayFor(x => item, "FooTemplate")
}
[+]is simpler
String s = "ddjdjdj+kfkfkf";
if(s.contains ("+"))
{
String parts[] = s.split("[+]");
s = parts[0]; // i want to strip part after +
}
System.out.println(s);
min(d.items(), key=lambda x: x[1])[0]
In my case i was missing trailing /
in path.
find /var/opt/gitlab/backups/ -name *.tar
using new keyword we always create a instance (new object) and throwing it , not called a method
throw new RuntimeException("Your Message");
You need the new in there. It's creating an instance and throwing it, not calling a method.
int no= new Scanner().nextInt(); // we crate an instance using new keyword and throwing it
using new keyword memory clean [because use and throw]
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//do your work here..
}
}, 1000);
I've tried different numbers, and it always acts as if the 0s aren't there and sorts the numbers correctly otherwise. Anyone know why?
You're getting a lexicographical sort (e.g. convert objects to strings, and sort them in dictionary order), which is the default sort behavior in Javascript:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
array.sort([compareFunction])
Parameters
compareFunction
Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.
In the ECMAscript specification (the normative reference for the generic Javascript), ECMA-262, 3rd ed., section 15.4.4.11, the default sort order is lexicographical, although they don't come out and say it, instead giving the steps for a conceptual sort function that calls the given compare function if necessary, otherwise comparing the arguments when converted to strings:
13. If the argument comparefn is undefined, go to step 16.
14. Call comparefn with arguments x and y.
15. Return Result(14).
16. Call ToString(x).
17. Call ToString(y).
18. If Result(16) < Result(17), return -1.
19. If Result(16) > Result(17), return 1.
20. Return +0.
Either !=
or ne
will work, but you need to get the accessor syntax and nested quotes sorted out.
<c:if test="${content.contentType.name ne 'MCE'}">
<%-- snip --%>
</c:if>
For passive mode you need to use command "literal" ftp>literal PASV
sudo yum install fontconfig freetype libfreetype.so.6 libfontconfig.so.1 libstdc++.so.6
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
Similarly, you could do plt.cla()
to just clear the current axes.
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
You may use window.URL
class:
new URL(location.href).searchParams.get('year')
// Returns 2008 for href = "http://localhost/search.php?year=2008".
// Or in two steps:
const params = new URL(location.href).searchParams;
const year = params.get('year');
As it is written before, some folders (/META-INF/resources/, /resources/, /static/, /public/) serve static content by default, conroller misconfiguration can break this behaviour.
It is a common pitfall that people define the base url of a controller in the @RestController
annotation, instead of the @RequestMapping
annotation on the top of the controllers.
This is wrong:
@RestController("/api/base")
public class MyController {
@PostMapping
public String myPostMethod( ...) {
The above example will prevent you from opening the index.html. The Spring expects a POST method at the root, because the myPostMethod
is mapped to the "/" path.
You have to use this instead:
@RestController
@RequestMapping("/api/base")
public class MyController {
@PostMapping
public String myPostMethod( ...) {
I've solved my problems, so I post here the correct code in case someone needs similar stuff.
Open Port
int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );
Set parameters
struct termios tty;
struct termios tty_old;
memset (&tty, 0, sizeof tty);
/* Error Handling */
if ( tcgetattr ( USB, &tty ) != 0 ) {
std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;
}
/* Save old tty parameters */
tty_old = tty;
/* Set Baud Rate */
cfsetospeed (&tty, (speed_t)B9600);
cfsetispeed (&tty, (speed_t)B9600);
/* Setting other Port Stuff */
tty.c_cflag &= ~PARENB; // Make 8n1
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~CRTSCTS; // no flow control
tty.c_cc[VMIN] = 1; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_cflag |= CREAD | CLOCAL; // turn on READ & ignore ctrl lines
/* Make raw */
cfmakeraw(&tty);
/* Flush Port, then applies attributes */
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
std::cout << "Error " << errno << " from tcsetattr" << std::endl;
}
Write
unsigned char cmd[] = "INIT \r";
int n_written = 0,
spot = 0;
do {
n_written = write( USB, &cmd[spot], 1 );
spot += n_written;
} while (cmd[spot-1] != '\r' && n_written > 0);
It was definitely not necessary to write byte per byte, also int n_written = write( USB, cmd, sizeof(cmd) -1)
worked fine.
At last, read:
int n = 0,
spot = 0;
char buf = '\0';
/* Whole response*/
char response[1024];
memset(response, '\0', sizeof response);
do {
n = read( USB, &buf, 1 );
sprintf( &response[spot], "%c", buf );
spot += n;
} while( buf != '\r' && n > 0);
if (n < 0) {
std::cout << "Error reading: " << strerror(errno) << std::endl;
}
else if (n == 0) {
std::cout << "Read nothing!" << std::endl;
}
else {
std::cout << "Response: " << response << std::endl;
}
This one worked for me. Thank you all!
You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.
Write a list of data.frames to individual worksheets using list names as worksheet names.
require(openxlsx)
list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")
I know, this has been asked and answered long ago, however if anyone is interested, here is my solution - custom set class backed by HashMap:
You can easily implement all other Set methods.
I had exactly the same problem, one day eclipse wouldn't open. Tried editing eclipse.ini to the correct java version 1.7, but still the same error. Eventually changed :
-Xms384m
-Xmx384m
...and all working.
I can give you an example but sure this is what you need.
map = {10 = 3, 11 = 1,12 = 2}
Let's say you want the top 2 most frequent key which is (10, 12) So the easiest way is using a PriorityQueue to sort based on the value of the map.
PriorityQueue<Integer> pq = new PriorityQueue<>((a, b) -> (map.get(a) - map.get(b));
for(int key: map.keySets()) {
pq.add(key);
if(pq.size() > 2) {
pq.poll();
}
}
// Now pq has the top 2 most frequent key based on value. It sorts the value.
You can use the collate clause in a query (I can't find my example right now, so my syntax is probably wrong - I hope it points you in the right direction)
select sone_field collate SQL_Latin1_General_CP850_CI_AI
from table_1
inner join table_2
on (table_1.field collate SQL_Latin1_General_CP850_CI_AI = table_2.field)
where whatever
You need to run the script as source
or the shorthand .
source ./myscript.sh
or
. ./myscript.sh
This will run within the existing shell, ensuring any variables created or modified by the script will be available after the script completes.
Running the script just using the filename will execute the script in a separate subshell.
dimen.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="weight">1</integer>
<dimen name="dialog_top_radius">21dp</dimen>
<dimen name="textview_dialog_head_min_height">50dp</dimen>
<dimen name="textview_dialog_drawable_padding">5dp</dimen>
<dimen name="button_dialog_layout_margin">3dp</dimen>
</resources>
styles.xml
<style name="TextView.Dialog">
<item name="android:paddingLeft">@dimen/dimen_size</item>
<item name="android:paddingRight">@dimen/dimen_size</item>
<item name="android:gravity">center_vertical</item>
<item name="android:textColor">@color/black</item>
</style>
<style name="TextView.Dialog.Head">
<item name="android:minHeight">@dimen/textview_dialog_head_min_height</item>
<item name="android:textColor">@color/white</item>
<item name="android:background">@drawable/dialog_title_style</item>
<item name="android:drawablePadding">@dimen/textview_dialog_drawable_padding</item>
</style>
<style name="TextView.Dialog.Text">
<item name="android:textAppearance">@style/Font.Medium.16</item>
</style>
<style name="Button" parent="Base.Widget.AppCompat.Button">
<item name="android:layout_height">@dimen/button_min_height</item>
<item name="android:layout_width">match_parent</item>
<item name="android:textColor">@color/white</item>
<item name="android:gravity">center</item>
<item name="android:textAppearance">@style/Font.Medium.20</item>
</style>
<style name="Button.Dialog">
<item name="android:layout_weight">@integer/weight</item>
<item name="android:layout_margin">@dimen/button_dialog_layout_margin</item>
</style>
<style name="Button.Dialog.Middle">
<item name="android:background">@drawable/button_primary_selector</item>
</style>
dialog_title_style.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:angle="270"
android:endColor="@color/primaryDark"
android:startColor="@color/primaryDark" />
<corners
android:topLeftRadius="@dimen/dialog_top_radius"
android:topRightRadius="@dimen/dialog_top_radius" />
</shape>
dialog_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/backgroundDialog" />
<corners
android:topLeftRadius="@dimen/dialog_top_radius"
android:topRightRadius="@dimen/dialog_top_radius" />
<padding />
</shape>
dialog_one_button.xml
<?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="wrap_content"
android:background="@drawable/dailog_background"
android:orientation="vertical">
<TextView
android:id="@+id/dialogOneButtonTitle"
style="@style/TextView.Dialog.Head"
android:text="Process Completed" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:orientation="vertical">
<TextView
android:id="@+id/dialogOneButtonText"
style="@style/TextView.Dialog.Text"
android:text="Return the main menu" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/dialogOneButtonOkButton"
style="@style/Button.Dialog.Middle"
android:text="Ok" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
OneButtonDialog.java
package com.example.sametoztoprak.concept.dialogs;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.example.sametoztoprak.concept.R;
import com.example.sametoztoprak.concept.models.DialogFields;
/**
* Created by sametoztoprak on 26/09/2017.
*/
public class OneButtonDialog extends Dialog implements View.OnClickListener {
private static OneButtonDialog oneButtonDialog;
private static DialogFields dialogFields;
private Button dialogOneButtonOkButton;
private TextView dialogOneButtonText;
private TextView dialogOneButtonTitle;
public OneButtonDialog(AppCompatActivity activity) {
super(activity);
}
public static OneButtonDialog getInstance(AppCompatActivity activity, DialogFields dialogFields) {
OneButtonDialog.dialogFields = dialogFields;
return oneButtonDialog = (oneButtonDialog == null) ? new OneButtonDialog(activity) : oneButtonDialog;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.dialog_one_button);
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialogOneButtonTitle = (TextView) findViewById(R.id.dialogOneButtonTitle);
dialogOneButtonText = (TextView) findViewById(R.id.dialogOneButtonText);
dialogOneButtonOkButton = (Button) findViewById(R.id.dialogOneButtonOkButton);
dialogOneButtonOkButton.setOnClickListener(this);
}
@Override
protected void onStart() {
super.onStart();
dialogOneButtonTitle.setText(dialogFields.getTitle());
dialogOneButtonText.setText(dialogFields.getText());
dialogOneButtonOkButton.setText(dialogFields.getOneButton());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dialogOneButtonOkButton:
break;
default:
break;
}
dismiss();
}
}
Or, KISS.
DIRS=build build/bins
...
$(shell mkdir -p $(DIRS))
This will create all the directories after the Makefile is parsed.
To get the location of a script being sourced, you can use utils::getSrcDirectory
or utils::getSrcFilename
. So changing the working directory to that of the current file can be done with:
setwd(getSrcDirectory()[1])
This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext
.
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
This second solution requires that you are using RStudio as your IDE, of course.
Your query should have date as
select * from table between `lowerdate` and `upperdate`
try
SELECT * FROM `objects`
WHERE (date_field BETWEEN '2010-01-30 14:15:55' AND '2010-09-29 10:15:55')
Single command without ps variables when using JSON
as body {lastName:"doe"}
for POST api call:
Invoke-WebRequest -Headers @{"Authorization" = "Bearer N-1234ulmMGhsDsCAEAzmo1tChSsq323sIkk4Zq9"} `
-Method POST `
-Body (@{"lastName"="doe";}|ConvertTo-Json) `
-Uri https://api.dummy.com/getUsers `
-ContentType application/json
This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array()
then pass the variable into your function, VBA will be happy.
Sub test()
Dim fString As String
Dim arr() As Variant
arr = Array("foo", "bar")
fString = processArr(arr)
End Sub
Also your function processArr()
could be written as:
Function processArr(arr() As Variant) As String
processArr = Replace(Join(arr()), " ", "")
End Function
If you are into the whole brevity thing.
I was able to achieve this by using the webkit-line-clamp
and the following css:
div {
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
overflow: hidden;
}
$str = '<img border="0" src=\'/images/image.jpg\' alt="Image" width="100" height="100"/>';
preg_match('/(src=["\'](.*?)["\'])/', $str, $match); //find src="X" or src='X'
$split = preg_split('/["\']/', $match[0]); // split by quotes
$src = $split[1]; // X between quotes
echo $src;
Other regexp's can be used to determine if the pulled src tag is a picture like so:
if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) {
//its an image
}
TRY THIS Button Border With Rounded Corners
anyButton.backgroundColor = .clear
anyButton.layer.cornerRadius = anyButton.frame.height / 2
anyButton.layer.borderWidth = 1
anyButton.layer.borderColor = UIColor.black.cgColor
I changed a couple of pngs and the build number in the gradle and now I get this. No amount of cleaning and restarting helped. Disabling Instant Run fixed it for me. YMMV
This also balances HTML tags so that they won't be left open and doesn't break words.
add_filter("the_content", "break_text");
function break_text($text){
$length = 500;
if(strlen($text)<$length+10) return $text;//don't cut if too short
$break_pos = strpos($text, ' ', $length);//find next space after desired length
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . " […]";
}
The difference concerns redirecting POST
, PUT
and DELETE
requests and what the expectations of the server are for the user agent behavior (RFC 2616
):
Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.
Also, read Wikipedia article on the 30x redirection codes.
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
Using lambda:
activity.runOnUiThread(() -> Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show());
Running as admin didn't help me. (also got errors with syscall: rename)
Turns out this error can also occur if files are locked by Windows.
This can occur if :
Running as admin doesn't get around windows file locking.
I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error
Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.
It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.
In Web API, it's very simple to remember how parameter binding is happening.
POST
simple types, Web API tries to bind it from the URL if you POST
complex type, Web API tries to bind it from the body of
the request (this uses a media-type
formatter).
If you want to bind a complex type from the URL, you'll use [FromUri]
in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.
public IHttpActionResult Put([FromUri] ViewModel data) { ... }
If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.
public IHttpActionResult Put([FromBody] string name) { ... }
as a side note, say you are making a PUT
request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data
parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.
var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});
and your web api action will look something like below.
public IHttpActionResult Put([FromBody] string name){ ... }
This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
if (User.Identity.IsAuthenticated)
{
Page.Title = "Home page for " + User.Identity.Name;
}
else
{
Page.Title = "Home page for guest user.";
}
Using Promises (Q) to solve this in a Functional style:
var fs = require('fs'),
fsPath = require('path'),
Q = require('q');
var walk = function (dir) {
return Q.ninvoke(fs, 'readdir', dir).then(function (files) {
return Q.all(files.map(function (file) {
file = fsPath.join(dir, file);
return Q.ninvoke(fs, 'lstat', file).then(function (stat) {
if (stat.isDirectory()) {
return walk(file);
} else {
return [file];
}
});
}));
}).then(function (files) {
return files.reduce(function (pre, cur) {
return pre.concat(cur);
});
});
};
It returns a promise of an array, so you can use it as:
walk('/home/mypath').then(function (files) { console.log(files); });
In Android
Android has a built in class for managing URIs.
Uri uri = Uri.parse("http://base_path/some_segment/id");
String lastPathSegment = uri.getLastPathSegment()
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
You should have a default server for catch-all, you can return 404
or better to not respond at all (will save some bandwidth) by returning 444
which is nginx specific HTTP response that simply close the connection and return nothing
server {
listen 80 default_server;
server_name _; # some invalid name that won't match anything
return 444;
}
It's actually pretty easy to do with Preview on a mac. All you have to do is open the file in Preview and save-as (or export) a png or jpeg but make sure that you use at least 300 dpi at the bottom of the window to get a high quality image.
I think that you can just catch org.openqa.selenium.NoSuchElementException
that will be thrown by driver.findElement
if there's no such element:
import org.openqa.selenium.NoSuchElementException;
....
public static void assertLinkNotPresent(WebDriver driver, String text) {
try {
driver.findElement(By.linkText(text));
fail("Link with text <" + text + "> is present");
} catch (NoSuchElementException ex) {
/* do nothing, link is not present, assert is passed */
}
}
Gift.new.instance_values # => {"name"=>"book", "price"=>15.95}
It seems that many of the ideas listed still use ordering
However, if you use a temporary table, you are able to assign a random index (like many of the solutions have suggested), and then grab the first one that is greater than an arbitrary number between 0 and 1.
For example (for DB2):
WITH TEMP AS (
SELECT COMLUMN, RAND() AS IDX FROM TABLE)
SELECT COLUMN FROM TABLE WHERE IDX > .5
FETCH FIRST 1 ROW ONLY
Simply, the logic would be
(condition) ? {code for YES} : {code for NO}
This code not only allows you to add two columns, it allows you to add as many coloumns as you want and align them left or right, change colors, add links etc. Check out the Fiddle link also
Fiddle Link : http://jsfiddle.net/eguFN/
<div class="menu">
<ul class="menuUl">
<li class="menuli"><a href="#">Cadastro</a></li>
<li class="menuli"><a href="#">Funcionamento</a></li>
<li class="menuli"><a href="#">Regulamento</a></li>
<li class="menuli"><a href="#">Contato</a></li>
</ul>
</div>
Css is as follows
.menu {
font-family:arial;
color:#000000;
font-size:12px;
text-align: left;
margin-top:35px;
}
.menu a{
color:#000000
}
.menuUl {
list-style: none outside none;
height: 34px;
}
.menuUl > li {
display:inline-block;
line-height: 33px;
margin-right: 45px;
}
The methods can be inspected in the prototype chain of the object using the browser's developer tools (F12):
console.log(yourJSObject);
or more directly
console.dir(yourJSObject.__proto__);
The number is held in an int[]
- the maximum size of an array is Integer.MAX_VALUE
. So the maximum BigInteger probably is (2 ^ 32) ^ Integer.MAX_VALUE
.
Admittedly, this is implementation dependent, not part of the specification.
In Java 8, some information was added to the BigInteger javadoc, giving a minimum supported range and the actual limit of the current implementation:
BigInteger
must support values in the range-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive) and may support values outside of that range.Implementation note:
BigInteger
constructors and operations throwArithmeticException
when the result is out of the supported range of-2
Integer.MAX_VALUE
(exclusive) to+2
Integer.MAX_VALUE
(exclusive).
Perhaps this is specific to .net core, I found DisplayName would not work but Display(Name=...) does. This may save someone else the troubleshooting involved :)
//using statements
using System;
using System.ComponentModel.DataAnnotations; //needed for Display annotation
using System.ComponentModel; //needed for DisplayName annotation
public class Whatever
{
//Property
[Display(Name ="Release Date")]
public DateTime ReleaseDate { get; set; }
}
//cshtml file
@Html.DisplayNameFor(model => model.ReleaseDate)
If you use a CSS sprite for the background images, you could bump the background offset +/- n pixels depending on whether you were expanding or collapsing. Not a toggle, but closer to it than having to switch background image URLs.
Check out the opensource Forge project. It provides a JavaScript TLS implementation, along with some Flash to handle the actual cross-domain requests:
http://github.com/digitalbazaar/forge/blob/master/README
In short, Forge will enable you to make XmlHttpRequests from a web page loaded over http to an https site. You will need to provide a Flash cross-domain policy file via your server to enable the cross-domain requests. Check out the blog posts at the end of the README to get a more in-depth explanation for how it works.
However, I should mention that Forge is better suited for requests between two different https-domains. The reason is that there's a potential MiTM attack. If you load the JavaScript and Flash from a non-secure site it could be compromised. The most secure use is to load it from a secure site and then use it to access other sites (secure or otherwise).
A Float
represents double
in SQL server. You can find a proof from the coding in C# in visual studio. Here I have declared Overtime
as a Float
in SQL server and in C#. Thus I am able to convert
int diff=4;
attendance.OverTime = Convert.ToDouble(diff);
Here OverTime
is declared float type
For those who would like to use #pragma once and include guards together: If you are not using MSVC, then you won't get much optimization from #pragma once.
And you shouldn't put "#pragma once" into a header that supposed to be included multiple times with each inclusion possibly having a different effect.
Here is a detailed discussion with examples about #pragma once usage.
You do not have to call parseJSON since the output of json_encode
is a javascript literal. Just assign it to a js variable.
<script type="text/javascript">
//Assign php generated json to JavaScript variable
var tempArray = <?php echo json_encode($php_array); ?>;
//You will be able to access the properties as
alert(tempArray[0].Key);
</script>
Try REPLACE(@strip,'''','')
SQL
uses two quotes to represent one in a string.
Simply creating a filter will do the trick. (Answered for Angular 1.6)
.filter('trustHtml', [
'$sce',
function($sce) {
return function(value) {
return $sce.trustAs('html', value);
}
}
]);
And use this as follow in the html.
<h2 ng-bind-html="someScopeValue | trustHtml"></h2>
If you have the file descriptor fstat()
returns a stat structure which contain the file size.
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
// fd = fileno(f); //if you have a stream (e.g. from fopen), not a file descriptor.
struct stat buf;
fstat(fd, &buf);
off_t size = buf.st_size;
About access
<ol class="viewer-nav">
<li *ngFor="let section of sections"
[attr.data-sectionvalue]="section.value"
(click)="get_data($event)">
{{ section.text }}
</li>
</ol>
And
get_data(event) {
console.log(event.target.dataset.sectionvalue)
}
Here is a much improved version of Archana's solution. It works for any radix 1-16, and numbers <= 0, and it shouldn't clobber memory.
static char _numberSystem[] = "0123456789ABCDEF";
static char _twosComp[] = "FEDCBA9876543210";
static void safestrrev(char *buffer, const int bufferSize, const int strlen)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
for (int index = 0; index < (len / 2); index++)
{
char ch = buffer[index];
buffer[index] = buffer[len - index - 1];
buffer[len - index - 1] = ch;
}
}
static int negateBuffer(char *buffer, const int bufferSize, const int strlen, const int radix)
{
int len = strlen;
if (len > bufferSize)
{
len = bufferSize;
}
if (radix == 10)
{
if (len < (bufferSize - 1))
{
buffer[len++] = '-';
buffer[len] = '\0';
}
}
else
{
int twosCompIndex = 0;
for (int index = 0; index < len; index++)
{
if ((buffer[index] >= '0') && (buffer[index] <= '9'))
{
twosCompIndex = buffer[index] - '0';
}
else if ((buffer[index] >= 'A') && (buffer[index] <= 'F'))
{
twosCompIndex = buffer[index] - 'A' + 10;
}
else if ((buffer[index] >= 'a') && (buffer[index] <= 'f'))
{
twosCompIndex = buffer[index] - 'a' + 10;
}
twosCompIndex += (16 - radix);
buffer[index] = _twosComp[twosCompIndex];
}
if (len < (bufferSize - 1))
{
buffer[len++] = _numberSystem[radix - 1];
buffer[len] = 0;
}
}
return len;
}
static int twosNegation(const int x, const int radix)
{
int n = x;
if (x < 0)
{
if (radix == 10)
{
n = -x;
}
else
{
n = ~x;
}
}
return n;
}
static char *safeitoa(const int x, char *buffer, const int bufferSize, const int radix)
{
int strlen = 0;
int n = twosNegation(x, radix);
int nuberSystemIndex = 0;
if (radix <= 16)
{
do
{
if (strlen < (bufferSize - 1))
{
nuberSystemIndex = (n % radix);
buffer[strlen++] = _numberSystem[nuberSystemIndex];
buffer[strlen] = '\0';
n = n / radix;
}
else
{
break;
}
} while (n != 0);
if (x < 0)
{
strlen = negateBuffer(buffer, bufferSize, strlen, radix);
}
safestrrev(buffer, bufferSize, strlen);
return buffer;
}
return NULL;
}
awk -v m="\x0a" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'
This chops what is before the given field nr., N, and prints all the rest of the line, including field nr.N and maintaining the original spacing (it does not reformat). It doesn't mater if the string of the field appears also somewhere else in the line, which is the problem with daisaa's answer.
Define a function:
fromField () {
awk -v m="\x0a" -v N="$1" '{$N=m$N; print substr($0,index($0,m)+1)}'
}
And use it like this:
$ echo " bat bi iru lau bost " | fromField 3
iru lau bost
$ echo " bat bi iru lau bost " | fromField 2
bi iru lau bost
Output maintains everything, including trailing spaces
Works well for files where '/n' is the record separator so you don't have that new-line char inside the lines. If you want to use it with other record separators then use:
awk -v m="\x01" -v N="3" '{$N=m$N ;print substr($0, index($0,m)+1)}'
for example. Works well with almost all files as long as they don't use hexadecimal char nr. 1 inside the lines.
Put your script in a file foo.py
starting with
#!/usr/bin/python
Then give execute permission to that script using
chmod a+x foo.py
and use the full path of your foo.py
file in your crontab
.
See documentation of execve(2) which is handling the shebang.