I worked quite a long time with Flux and now quite a long time using Redux. As Dan pointed out both architectures are not so different. The thing is that Redux makes the things simpler and cleaner. It teaches you a couple of things on top of Flux. Like for example Flux is a perfect example of one-direction data flow. Separation of concerns where we have data, its manipulations and view layer separated. In Redux we have the same things but we also learn about immutability and pure functions.
I have faced the same problem once too. I have solved it by creating on empty link with a ref to it like so:
linkRef = React.createRef();
render() {
return (
<a ref={this.linkRef}/>
);
}
and in my fetch function i have done something like this:
fetch(/*your params*/)
}).then(res => {
return res.blob();
}).then(blob => {
const href = window.URL.createObjectURL(blob);
const a = this.linkRef.current;
a.download = 'Lebenslauf.pdf';
a.href = href;
a.click();
a.href = '';
}).catch(err => console.error(err));
basically i have assigned the blobs url(href) to the link, set the download attribute and enforce one click on the link. As far as i understand this is the "basic" idea of the answer provided by @Nate. I dont know if this is a good idea to do it this way... I did.
Using cp-axios wrapper you able to abort your requests with three diffent types of the cancellation API:
1. Promise cancallation API (CPromise):
const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const chain = cpAxios(url)
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
chain.cancel();
}, 500);
2. Using AbortController signal API:
const cpAxios= require('cp-axios');
const CPromise= require('c-promise2');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const abortController = new CPromise.AbortController();
const {signal} = abortController;
const chain = cpAxios(url, {signal})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
abortController.abort();
}, 500);
3. Using a plain axios cancelToken:
const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
const source = cpAxios.CancelToken.source();
cpAxios(url, {cancelToken: source.token})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
setTimeout(() => {
source.cancel();
}, 500);
const getJsonIndented = (obj) => JSON.stringify(newObj, null, 4).replace(/["{[,\}\]]/g, "")
const JSONDisplayer = ({children}) => (
<div>
<pre>{getJsonIndented(children)}</pre>
</div>
)
Then you can easily use it:
const Demo = (props) => {
....
return <JSONDisplayer>{someObj}<JSONDisplayer>
}
You can use the dotenv package no matter what setup you use. It allows you to create a .env in your project root and specify your keys like so
REACT_APP_SERVER_PORT=8000
In your applications entry file your just call dotenv(); before accessing the keys like so
process.env.REACT_APP_SERVER_PORT
Here's one solution that extracts all zip files to the working directory and involves the find command and a while loop:
find . -name "*.zip" | while read filename; do unzip -o -d "`basename -s .zip "$filename"`" "$filename"; done;
this.close_Button = (Button)this.findViewById(R.id.close);
this.close_Button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
finish()
- Call this when your activity is done and should be closed. The ActivityResult
is propagated back to whoever launched you via onActivityResult()
.
We know that
And that The n-th power of that matrix gives us:
So we can implement a function that simply computes the power of that matrix to the n-th -1 power.
as all we know the power a^n is equal to
So at the end the fibonacci function would be O( n )... nothing really different than an easier implementation if it wasn't for the fact that we also know that x^n * x^n = x^2n
and the evaluation of x^n
can therefore be done with complexity O( log n )
Here is my fibonacci implementation using swift programming language:
struct Mat {
var m00: Int
var m01: Int
var m10: Int
var m11: Int
}
func pow(m: Mat, n: Int) -> Mat {
guard n > 1 else { return m }
let temp = pow(m: m, n: n/2)
var result = matMultiply(a: temp, b: temp)
if n%2 != 0 {
result = matMultiply(a: result, b: Mat(m00: 1, m01: 1, m10: 1, m11: 0))
}
return result
}
func matMultiply(a: Mat, b: Mat) -> Mat {
let m00 = a.m00 * b.m00 + a.m01 * b.m10
let m01 = a.m00 * b.m01 + a.m01 * b.m11
let m10 = a.m10 * b.m00 + a.m11 * b.m10
let m11 = a.m10 * b.m01 + a.m11 * b.m11
return Mat(m00: m00, m01: m01, m10: m10, m11: m11)
}
func fibonacciFast(n: Int) -> Int {
guard n > 0 else { return 0 }
let m = Mat(m00: 1, m01: 1, m10: 1, m11: 0)
return pow(m: m, n: n-1).m00
}
This has complexity O( log n ). We compute the oìpower of Q with exponent n-1 and then we take the element m00 which is Fn+1 that at the power exponent n-1 is exactly the n-th Fibonacci number we wanted.
Once you have the fast fibonacci function you can iterate from start number and end number to get the part of the Fibonacci sequence you are interested in.
let sequence = (start...end).map(fibonacciFast)
of course first perform some check on start and end to make sure they can form a valid range.
I know the question is 8 years old, but I had fun answering anyway. :)
'self' is only a reference to the object. 'del self' is deleting the 'self' reference from the local namespace of the kill function, instead of the actual object.
To see this for yourself, look at what happens when these two functions are executed:
>>> class A():
... def kill_a(self):
... print self
... del self
... def kill_b(self):
... del self
... print self
...
>>> a = A()
>>> b = A()
>>> a.kill_a()
<__main__.A instance at 0xb771250c>
>>> b.kill_b()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in kill_b
UnboundLocalError: local variable 'self' referenced before assignment
Run your script with .
. myscript.sh
This will run the script in the current shell environment.
export
governs which variables will be available to new processes, so if you say
FOO=1
export BAR=2
./runScript.sh
then $BAR
will be available in the environment of runScript.sh
, but $FOO
will not.
One think you should change is the call $state.go()
. As described here:
The param passed should be the state name
$scope.create = function() {
// instead of this
//$state.go("/tab/newpost");
// we should use this
$state.go("tab.newpost");
};
Some cite from doc (the first parameter to of the [$state.go(to \[, toParams\] \[, options\]
):
String Absolute State Name or Relative State Path
The name of the state that will be transitioned to or a relative state path. If the path starts with ^ or . then it is relative, otherwise it is absolute.
Some examples:
$state.go('contact.detail') will go to the 'contact.detail' state
$state.go('^') will go to a parent state.
$state.go('^.sibling') will go to a sibling state.
$state.go('.child.grandchild') will go to a grandchild state.
If modal are 100% height/width "mouseenter/leave" will work to easily enable/disable scrolling. This really worked out for me:
var currentScroll=0;
function lockscroll(){
$(window).scrollTop(currentScroll);
}
$("#myModal").mouseenter(function(){
currentScroll=$(window).scrollTop();
$(window).bind('scroll',lockscroll);
}).mouseleave(function(){
currentScroll=$(window).scrollTop();
$(window).unbind('scroll',lockscroll);
});
Most html tags have some default properties. A css reset will help you change the default properties.
What I usually do is:
{ padding: 0; margin: 0; font-face:Arial; }
Although the font is up to you!
You can do it by javascript on client side or using some regex validator on the textbox.
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
As other posters have mentioned, I'd suggest you have a look at aria2. From the Ubuntu man page for version 1.16.1:
aria2 is a utility for downloading files. The supported protocols are HTTP(S), FTP, BitTorrent, and Metalink. aria2 can download a file from multiple sources/protocols and tries to utilize your maximum download bandwidth. It supports downloading a file from HTTP(S)/FTP and BitTorrent at the same time, while the data downloaded from HTTP(S)/FTP is uploaded to the BitTorrent swarm. Using Metalink's chunk checksums, aria2 automatically validates chunks of data while downloading a file like BitTorrent.
You can use the -x
flag to specify the maximum number of connections per server (default: 1):
aria2c -x 16 [url]
If the same file is available from multiple locations, you can choose to download from all of them. Use the -j
flag to specify the maximum number of parallel downloads for every static URI (default: 5).
aria2c -j 5 [url] [url2]
Have a look at http://aria2.sourceforge.net/ for more information. For usage information, the man page is really descriptive and has a section on the bottom with usage examples. An online version can be found at http://aria2.sourceforge.net/manual/en/html/README.html.
$('.input').keypress(function (e) {
if (e.which == 13) {
$('form#login').submit();
return false; //<---- Add this line
}
});
Check out this stackoverflow answer: event.preventDefault() vs. return false
Essentially, "return false" is the same as calling e.preventDefault
and e.stopPropagation()
.
My clean solution for situation that key is unique in both enumerables:
private static IEnumerable<TResult> FullOuterJoin<Ta, Tb, TKey, TResult>(
IEnumerable<Ta> a, IEnumerable<Tb> b,
Func<Ta, TKey> key_a, Func<Tb, TKey> key_b,
Func<Ta, Tb, TResult> selector)
{
var alookup = a.ToLookup(key_a);
var blookup = b.ToLookup(key_b);
var keys = new HashSet<TKey>(alookup.Select(p => p.Key));
keys.UnionWith(blookup.Select(p => p.Key));
return keys.Select(key => selector(alookup[key].FirstOrDefault(), blookup[key].FirstOrDefault()));
}
so
var ax = new[] {
new { id = 1, first_name = "ali" },
new { id = 2, first_name = "mohammad" } };
var bx = new[] {
new { id = 1, last_name = "rezaei" },
new { id = 3, last_name = "kazemi" } };
var list = FullOuterJoin(ax, bx, a => a.id, b => b.id, (a, b) => "f: " + a?.first_name + " l: " + b?.last_name).ToArray();
outputs:
f: ali l: rezaei
f: mohammad l:
f: l: kazemi
Go into File ? Settings ? Project Settings ? Project Interpreter.
Then press configure interpreter, and navigate to the "Paths" tab.
Press the + button in the Paths area. You can put the path to the module you'd like it to recognize.
Open the python interpreter where you can import the module.
>> import gnuradio
>> gnuradio.__file__
"path/to/gnuradio"
Most commonly you'll have a folder structure like this:
foobarbaz/
gnuradio/
__init__.py
other_file.py
You want to add foobarbaz to the path here.
I present you with the cleanest way ever, in the form of the world's smallest jquery plugin:
jQuery.fn.reverse = [].reverse;
Usage:
$('jquery-selectors-go-here').reverse().each(function () {
//business as usual goes here
});
-All credit to Michael Geary in his post here: http://www.mail-archive.com/[email protected]/msg04261.html
Java script plays on browser where java code is server side thing so you can't simply do this.
What you can do is submit the calculated variable from javascript to server by form-submission, or using URL parameter or using AJAX calls and then you can make it available on server
HTML
<input type="hidden" id="hiddenField"/>
make sure this fields lays under <form>
Javascript
document.getElementById("hiddenField").value=yourCalculatedVariable;
on server you would get this as a part of request
There are scenarios in wich you cannot use bc becouse it might simply not be present, like in some cut down versions of busybox or embedded systems. In any case limiting outer dependencies is always a good thing to do so you can always add zeroes to the number being divided by (numerator), that is the same as multiplying by a power of 10 (you should choose a power of 10 according to the precision you need), that will make the division output an integer number. Once you have that integer treat it as a string and position the decimal point (moving it from right to left) a number of times equal to the power of ten you multiplied the numerator by. This is a simple way of obtaining float results by using only integer numbers.
Instead of using an Array, consider using either a Hash or a Set.
Sets behave similar to an Array, only they contain unique values only, and, under the covers, are built on Hashes. Sets don't retain the order that items are put into them unlike Arrays. Hashes don't retain the order either but can be accessed via a key so you don't have to traverse the hash to find a particular item.
I favor using Hashes. In your application the user_id could be the key and the value would be the entire object. That will automatically remove any duplicates from the hash.
Or, only extract unique values from the database, like John Ballinger suggested.
My gut told me the same thing when I came across this design.
I am working on a code base where there are three dbContexts to one database. 2 out of the 3 dbcontexts are dependent on information from 1 dbcontext because it serves up the administrative data. This design has placed constraints on how you can query your data. I ran into this problem where you cannot join across dbcontexts. Instead what you are required to do is query the two separate dbcontexts then do a join in memory or iterate through both to get the combination of the two as a result set. The problem with that is instead of querying for a specific result set you are now loading all your records into memory and then doing a join against the two result sets in memory. It can really slow things down.
I would ask the question "just because you can, should you?"
See this article for the problem I came across related to this design.
The specified LINQ expression contains references to queries that are associated with different contexts
You can do
var color = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
Or this (you will need the System.Windows.Media
namespace)
var color = (Color)ColorConverter.ConvertFromString("#FFFFFF");
You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.
When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.
Reference:
C++03 standard, § 14.7.2.4:
The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.
EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:
.cpp
file. #include
the .cpp
file defining the template at the .cpp
file using the template. Each of them have their pros and cons,
Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.
Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.
While including cpp files is confusing at the same time shares the problems of both above approaches.
I find first method the easiest to follow and implement and hence advocte using it.
There is a little hack with php. And it works not only with Google, but with any website you don't control and can't add Access-Control-Allow-Origin *
We need to create PHP-file (ex. getContentFromUrl.php) on our webserver and make a little trick.
PHP
<?php
$ext_url = $_POST['ext_url'];
echo file_get_contents($ext_url);
?>
JS
$.ajax({
method: 'POST',
url: 'getContentFromUrl.php', // link to your PHP file
data: {
// url where our server will send request which can't be done by AJAX
'ext_url': 'https://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis'
},
success: function(data) {
// we can find any data on external url, cause we've got all page
var $h1 = $(data).find('h1').html();
$('h1').val($h1);
},
error:function() {
console.log('Error');
}
});
How it works:
And we can make events onClick, put this event on some button. Hope this will help!
group by default order by pk id,so the result
username point avg_time
demo123 100 90 ---> id = 4
demo123456 100 100 ---> id = 7
demo 90 120 ---> id = 1
ArrayList<String[]> action = new ArrayList<String[]>();
Don't need String[2]
;
You can pass function as parameter to a Go function. Here is an example of passing function as parameter to another Go function:
package main
import "fmt"
type fn func(int)
func myfn1(i int) {
fmt.Printf("\ni is %v", i)
}
func myfn2(i int) {
fmt.Printf("\ni is %v", i)
}
func test(f fn, val int) {
f(val)
}
func main() {
test(myfn1, 123)
test(myfn2, 321)
}
You can try this out at: https://play.golang.org/p/9mAOUWGp0k
If you're doing automation and want to get coordinates of where to click, simplest and shortest approach would be:
import pyautogui
while True:
print(pyautogui.position())
This will track your mouse position and would keep on printing coordinates.
SELECT <...>
FROM A.table1 t1 JOIN B.table2 t2 ON t2.column2 = t1.column1;
Just make sure that in the SELECT line you specify which table columns you are using, either by full reference, or by alias. Any of the following will work:
SELECT *
SELECT t1.*,t2.column2
SELECT A.table1.column1, t2.*
etc.
You can use Apache Commons.
In the IOUtils you can find the toString method with three helpful implementations.
public static String toString(InputStream input) throws IOException {
return toString(input, Charset.defaultCharset());
}
public static String toString(InputStream input) throws IOException {
return toString(input, Charset.defaultCharset());
}
public static String toString(InputStream input, String encoding)
throws IOException {
return toString(input, Charsets.toCharset(encoding));
}
Declare your progress dialog:
ProgressDialog progressDialog;
To start the progress dialog:
progressDialog = ProgressDialog.show(this, "","Please Wait...", true);
To dismiss the Progress Dialog :
progressDialog.dismiss();
A more fail-safe method than all previous answers:
git submodule deinit -f .
git submodule update --init
The first command completely "unbinds" all submodules, the second then makes a fresh checkout of them.
It takes longer than the other methods, but will work whatever the state of your submodules.
Now you can use the SQL Server Management Studio to do this.
You can overwrite your default activity animation and it perform better than overridePendingTransition. I use this solution that work for every android version. Just copy paste 4 files and add a 4 lines style as below:
Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorPrimary</item>
<item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>
</style>
<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">
<item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>
<item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>
<item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>
<item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>
</style>
Then Create anim folder under res folder and then create this four animation files into anim folder:
slide_in_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="-100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_in_left.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="-100%p" android:toXDelta="0"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
slide_out_right.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromXDelta="0" android:toXDelta="100%p"
android:duration="@android:integer/config_mediumAnimTime"/>
</set>
If you face any problem then you can download my sample project from github.
Thanks
I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:
<input type="checkbox" ng-model="entity.isChecked">
Whenever the user checks or unchecks the checkbox the entity.isChecked
value will change too.
If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.
When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners
array. The listeners in this array get called after the model value has been set, avoiding this problem).
<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">
... and in the controller ...
var model = {};
$scope.model = model;
// This property is bound to the checkbox in the table header
model.allItemsSelected = false;
// Fired when an entity in the table is checked
$scope.selectEntity = function () {
// If any entity is not checked, then uncheck the "allItemsSelected" checkbox
for (var i = 0; i < model.entities.length; i++) {
if (!model.entities[i].isChecked) {
model.allItemsSelected = false;
return;
}
}
// ... otherwise ensure that the "allItemsSelected" checkbox is checked
model.allItemsSelected = true;
};
Similarly, the "Check All" checkbox in the header:
<th>
<input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>
... and ...
// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
// Loop through all the entities and set their isChecked property
for (var i = 0; i < model.entities.length; i++) {
model.entities[i].isChecked = model.allItemsSelected;
}
};
CSS
What is the best way to... add a CSS class to the
<tr>
containing the entity to reflect its selected state?
If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr>
element to dynamically add or remove the class whenever the entity property changes:
<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">
See the full Plunker here.
Since C++11 std::regex_search
can also be used to provide even more complex expressions matching. The following example handles also floating numbers thorugh std::stof
and a subsequent cast to int
.
However the parseInt
method shown below could throw a std::invalid_argument
exception if the prefix is not matched; this can be easily adapted depending on the given application:
#include <iostream>
#include <regex>
int parseInt(const std::string &str, const std::string &prefix) {
std::smatch match;
std::regex_search(str, match, std::regex("^" + prefix + "([+-]?(?=\\.?\\d)\\d*(?:\\.\\d*)?(?:[Ee][+-]?\\d+)?)$"));
return std::stof(match[1]);
}
int main() {
std::cout << parseInt("foo=13.3", "foo=") << std::endl;
std::cout << parseInt("foo=-.9", "foo=") << std::endl;
std::cout << parseInt("foo=+13.3", "foo=") << std::endl;
std::cout << parseInt("foo=-0.133", "foo=") << std::endl;
std::cout << parseInt("foo=+00123456", "foo=") << std::endl;
std::cout << parseInt("foo=-06.12e+3", "foo=") << std::endl;
// throw std::invalid_argument
// std::cout << parseInt("foo=1", "bar=") << std::endl;
return 0;
}
The kind of magic of the regex pattern is well detailed in the following answer.
EDIT: the previous answer did not performed the conversion to integer.
And what something like this?
public class Carrier : Entity
{
public Carrier()
{
this.Id = Guid.NewGuid();
}
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
Install setuptools
and try again.
try command:
sudo apt-get install -y python-setuptools
If you are setting Styles in JavaScript as:
var cssLink = document.createElement("link");
cssLink.href = "./content.component.scss";
cssLink.rel = "stylesheet";
--> cssLink.type = "html/css";
(iframe as HTMLIFrameElement).contentDocument.head.appendChild(cssLink);
Then just change cssLint.type (denoted by arrow in above description) to "MIME":
cssLink.type = "MIME";
It will help you to get rid of the error.
document.getElementById("myh1id").innerHTML = "my text"
If all images are of the same format:
import cv2
import glob
images = [cv2.imread(file) for file in glob.glob('path/to/files/*.jpg')]
For reading images of different formats:
import cv2
import glob
imdir = 'path/to/files/'
ext = ['png', 'jpg', 'gif'] # Add image formats here
files = []
[files.extend(glob.glob(imdir + '*.' + e)) for e in ext]
images = [cv2.imread(file) for file in files]
This is the Method to get contact list Name and Number
private void getAllContacts() {
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id},
null);
if (phoneCursor != null) {
if (phoneCursor.moveToNext()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//At here You can add phoneNUmber and Name to you listView ,ModelClass,Recyclerview
phoneCursor.close();
}
}
}
}
}
}
If you're used to batch, you can call
$user=$(cmd.exe /c echo %username%)
This basically steals the output from what you would get if you had a batch file with just "echo %username%".
user1594322 gave a correct answer but when I tried it I ran into admin/permission problems. I was able to copy 'mingw32-make.exe' and paste it, over-ruling/by-passing admin issues and then editing the copy to 'make.exe'. On VirtualBox in a Win7 guest.
Volatile tells the compiler not to optimize anything that has to do with the volatile variable.
There are at least three common reasons to use it, all involving situations where the value of the variable can change without action from the visible code: When you interface with hardware that changes the value itself; when there's another thread running that also uses the variable; or when there's a signal handler that might change the value of the variable.
Let's say you have a little piece of hardware that is mapped into RAM somewhere and that has two addresses: a command port and a data port:
typedef struct
{
int command;
int data;
int isbusy;
} MyHardwareGadget;
Now you want to send some command:
void SendCommand (MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
Looks easy, but it can fail because the compiler is free to change the order in which data and commands are written. This would cause our little gadget to issue commands with the previous data-value. Also take a look at the wait while busy loop. That one will be optimized out. The compiler will try to be clever, read the value of isbusy just once and then go into an infinite loop. That's not what you want.
The way to get around this is to declare the pointer gadget as volatile. This way the compiler is forced to do what you wrote. It can't remove the memory assignments, it can't cache variables in registers and it can't change the order of assignments either:
This is the correct version:
void SendCommand (volatile MyHardwareGadget * gadget, int command, int data)
{
// wait while the gadget is busy:
while (gadget->isbusy)
{
// do nothing here.
}
// set data first:
gadget->data = data;
// writing the command starts the action:
gadget->command = command;
}
There are two kinds of cell reference, and it's really valuable to understand them well.
One is relative reference, which is what you get when you just type the cell: A5
. This reference will be adjusted when you paste or fill the formula into other cells.
The other is absolute reference, and you get this by adding dollar signs to the cell reference: $A$5
. This cell reference will not change when pasted or filled.
A cool but rarely used feature is that row and column within a single cell reference may be independent: $A5
and A$5
. This comes in handy for producing things like multiplication tables from a single formula.
Make sure you properly escape the quotes.
string line = "\"Text\",\"Text\",\"Text\",";
string result = line.Replace("\",\"", ";");
It is working for me.
etMsgDescription.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maximum_character)});
etMsgDescription.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
tvCharacterLimite.setText(" "+String.valueOf(maximum_character - etMsgDescription.getText().length()));
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Here is working code as per the author's Tips & Tricks blog post, put it in document ready:
$("#mybutton").click(function(){
$(".fancybox").trigger('click');
})
This triggers the smaller version of the currently displayed image or content, as if you had clicked on it manually. It avoids initializing the Fancybox again, but instead keeps the parameters you initialized it with on document ready. If you need to do something different when opening the box with a separate button compared to clicking on the box, you will need the parameters, but for many, this will be what they were looking for.
In Python 3, urllib.quote
has been moved to urllib.parse.quote
and it does handle unicode by default.
>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'
$(document).ready(function () {_x000D_
var form = $('#login_form')[0];_x000D_
form.onsubmit = function(e){_x000D_
var data = $("#login_form :input").serializeArray();_x000D_
console.log(data);_x000D_
$.ajax({_x000D_
url: "the url to post",_x000D_
data: data,_x000D_
processData: false,_x000D_
contentType: false,_x000D_
type: 'POST',_x000D_
success: function(data){_x000D_
alert(data);_x000D_
},_x000D_
error: function(xhrRequest, status, error) {_x000D_
alert(JSON.stringify(xhrRequest));_x000D_
}_x000D_
});_x000D_
return false;_x000D_
}_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Capturing sumit action</title>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<form method="POST" id="login_form">_x000D_
<label>Username:</label>_x000D_
<input type="text" name="username" id="username"/>_x000D_
<label>Password:</label>_x000D_
<input type="password" name="password" id="password"/>_x000D_
<input type="submit" value="Submit" name="submit" class="submit" id="submit" />_x000D_
</form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Another way to do it, using axes.get_xlim()
:
import matplotlib.pyplot as plt
import numpy as np
def scatter_plot_with_correlation_line(x, y, graph_filepath):
'''
http://stackoverflow.com/a/34571821/395857
x does not have to be ordered.
'''
# Create scatter plot
plt.scatter(x, y)
# Add correlation line
axes = plt.gca()
m, b = np.polyfit(x, y, 1)
X_plot = np.linspace(axes.get_xlim()[0],axes.get_xlim()[1],100)
plt.plot(X_plot, m*X_plot + b, '-')
# Save figure
plt.savefig(graph_filepath, dpi=300, format='png', bbox_inches='tight')
def main():
# Data
x = np.random.rand(100)
y = x + np.random.rand(100)*0.1
# Plot
scatter_plot_with_correlation_line(x, y, 'scatter_plot.png')
if __name__ == "__main__":
main()
#cProfile.run('main()') # if you want to do some profiling
put at the end it will reopen your console
start cmd
Not sure if anyone is having the same responsive issue, but it was just a simple css solution for me.
same example
... ng-init="isCollapsed = true" ng-click="isCollapsed = !isCollapsed"> ...
... div collapse="isCollapsed"> ...
with
@media screen and (min-width: 768px) {
.collapse{
display: block !important;
}
}
Two ways to read file into list in python (note these are not either or) -
with
- supported from python 2.5 and abovewith
This is the pythonic way of opening and reading files.
#Sample 1 - elucidating each step but not memory efficient
lines = []
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #or some other preprocessing
lines.append(line) #storing everything in memory!
#Sample 2 - a more pythonic and idiomatic way but still not memory efficient
with open("C:\name\MyDocuments\numbers") as file:
lines = [line.strip() for line in file]
#Sample 3 - a more pythonic way with efficient memory usage. Proper usage of with and file iterators.
with open("C:\name\MyDocuments\numbers") as file:
for line in file:
line = line.strip() #preprocess line
doSomethingWithThisLine(line) #take action on line instead of storing in a list. more memory efficient at the cost of execution speed.
the .strip()
is used for each line of the file to remove \n
newline character that each line might have. When the with
ends, the file will be closed automatically for you. This is true even if an exception is raised inside of it.
This could be considered inefficient as the file descriptor might not be closed immediately. Could be a potential issue when this is called inside a function opening thousands of files.
data = [line.strip() for line in open("C:/name/MyDocuments/numbers", 'r')]
Note that file closing is implementation dependent. Normally unused variables are garbage collected by python interpreter. In cPython (the regular interpreter version from python.org), it will happen immediately, since its garbage collector works by reference counting. In another interpreter, like Jython or Iron Python, there may be a delay.
This question is several years old, but I stumbled upon it, which means maybe others will.
The readr
library / package has some nice features to it. One of them is a nice way to interpret "messy" columns, like these.
library(readr)
read_csv("numbers\n800\n\"1,800\"\n\"3500\"\n6.5",
col_types = list(col_numeric())
)
This yields
Source: local data frame [4 x 1]
numbers
(dbl)
1 800.0
2 1800.0
3 3500.0
4 6.5
An important point when reading in files: you either have to pre-process, like the comment above regarding sed
, or you have to process while reading. Often, if you try to fix things after the fact, there are some dangerous assumptions made that are hard to find. (Which is why flat files are so evil in the first place.)
For instance, if I had not flagged the col_types
, I would have gotten this:
> read_csv("numbers\n800\n\"1,800\"\n\"3500\"\n6.5")
Source: local data frame [4 x 1]
numbers
(chr)
1 800
2 1,800
3 3500
4 6.5
(Notice that it is now a chr
(character
) instead of a numeric
.)
Or, more dangerously, if it were long enough and most of the early elements did not contain commas:
> set.seed(1)
> tmp <- as.character(sample(c(1:10), 100, replace=TRUE))
> tmp <- c(tmp, "1,003")
> tmp <- paste(tmp, collapse="\"\n\"")
(such that the last few elements look like:)
\"5\"\n\"9\"\n\"7\"\n\"1,003"
Then you'll find trouble reading that comma at all!
> tail(read_csv(tmp))
Source: local data frame [6 x 1]
3"
(dbl)
1 8.000
2 5.000
3 5.000
4 9.000
5 7.000
6 1.003
Warning message:
1 problems parsing literal data. See problems(...) for more details.
#config/app.php
'aliases' => [
...
'Input' => Illuminate\Support\Facades\Input::class,
...
],
#Use Controller file
use Illuminate\Support\Facades\Input;
==OR==
use Input;
Read full example: https://devnote.in/laravel-class-input-not-found
sumr
is implemented in terms of foldRight
:
final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append)
foldRight
is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.
My Solutions:
$("body").scrollspy({ target: ".target", offset: fix_header_height });
$(".target").click(function() {
$("body").animate(
{
scrollTop: $($(this).attr("href")).offset().top - fix_header_height
},
500
);
return;
});
It's all a perceptual thing. Git is generally rather good at recognising moves, because GIT is a content tracker
All that really depends is how your "stat" displays it. The only difference here is the -M flag.
git log --stat -M
commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date: Fri Jan 9 22:13:51 2009 +1300
Category Restructure
lib/Gentoo/Repository.pm | 10 +++++-----
lib/Gentoo/{ => Repository}/Base.pm | 2 +-
lib/Gentoo/{ => Repository}/Category.pm | 12 ++++++------
lib/Gentoo/{ => Repository}/Package.pm | 10 +++++-----
lib/Gentoo/{ => Repository}/Types.pm | 10 +++++-----
5 files changed, 22 insertions(+), 22 deletions(-)
git log --stat
commit 9c034a76d394352134ee2f4ede8a209ebec96288
Author: Kent Fredric
Date: Fri Jan 9 22:13:51 2009 +1300
Category Restructure
lib/Gentoo/Base.pm | 36 ------------------------
lib/Gentoo/Category.pm | 51 ----------------------------------
lib/Gentoo/Package.pm | 41 ---------------------------
lib/Gentoo/Repository.pm | 10 +++---
lib/Gentoo/Repository/Base.pm | 36 ++++++++++++++++++++++++
lib/Gentoo/Repository/Category.pm | 51 ++++++++++++++++++++++++++++++++++
lib/Gentoo/Repository/Package.pm | 41 +++++++++++++++++++++++++++
lib/Gentoo/Repository/Types.pm | 55 +++++++++++++++++++++++++++++++++++++
lib/Gentoo/Types.pm | 55 -------------------------------------
9 files changed, 188 insertions(+), 188 deletions(-)
git help log
-M
Detect renames.
-C
Detect copies as well as renames. See also --find-copies-harder.
As the following answer describes: Does pandas/scipy/numpy provide a cumulative standard deviation function? The Python Pandas module contains a method to calculate the running or cumulative standard deviation. For that you'll have to convert your data into a pandas dataframe (or a series if it is 1D), but there are functions for that.
Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.
I had the same problem. Try to make a bat-file to start the Qt Creator. Add something like this to the bat-file:
call "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
"C:\QTsdk\qtcreator\bin\qtcreator"
Now I can compile and get:
jom 1.0.8 - empower your cores
11:10:08: The process "C:\QTsdk\qtcreator\bin\jom.exe" exited normally.
Here is how you could create such a table:
SELECT LEVEL AS id, REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) AS data
FROM dual
CONNECT BY REGEXP_SUBSTR('A,B,C,D', '[^,]+', 1, LEVEL) IS NOT NULL;
With a little bit of tweaking (i.e., replacing the ,
in [^,]
with a variable) you could write such a function to return a table.
The problem is with your curl options – the RCurl
package doesn't seem to use internet2.dll
.
You need to specify the port separately, and will probably need to give your user login details as network credentials, e.g.,
opts <- list(
proxy = "999.999.999.999",
proxyusername = "mydomain\\myusername",
proxypassword = "mypassword",
proxyport = 8080
)
getURL("http://stackoverflow.com", .opts = opts)
Remember to escape any backslashes in your password. You may also need to wrap the URL in a call to curlEscape
.
System.Windows.Forms.MessageBox.Show("My message here");
Make sure the System.Windows.Forms
assembly is referenced your project.
In ASP.NET Core 2 Web API
, using Swashbuckle.AspNetCore package 2.1.0, implement a IDocumentFilter:
SwaggerSecurityRequirementsDocumentFilter.cs
using System.Collections.Generic;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
namespace api.infrastructure.filters
{
public class SwaggerSecurityRequirementsDocumentFilter : IDocumentFilter
{
public void Apply(SwaggerDocument document, DocumentFilterContext context)
{
document.Security = new List<IDictionary<string, IEnumerable<string>>>()
{
new Dictionary<string, IEnumerable<string>>()
{
{ "Bearer", new string[]{ } },
{ "Basic", new string[]{ } },
}
};
}
}
}
In Startup.cs, configure a security definition and register the custom filter:
public void ConfigureServices(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
// c.SwaggerDoc(.....
c.AddSecurityDefinition("Bearer", new ApiKeyScheme()
{
Description = "Authorization header using the Bearer scheme",
Name = "Authorization",
In = "header"
});
c.DocumentFilter<SwaggerSecurityRequirementsDocumentFilter>();
});
}
In Swagger UI, click on Authorize button and set value for token.
Result:
curl -X GET "http://localhost:5000/api/tenants" -H "accept: text/plain" -H "Authorization: Bearer ABCD123456"
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
Make sure MySQL binds to 0.0.0.0 and not 127.0.0.1 or it will not be accessible from outside the machine
You can ensure this by editing your my.conf file and looking for the bind-address
item--you want it to look like bind-address = 0.0.0.0
. Then save this and restart mysql:
sudo service mysql restart
If you are doing this on a production server, you want to be aware of the security implications, discussed here: https://serverfault.com/questions/257513/how-bad-is-setting-mysqls-bind-address-to-0-0-0-0
I know the accepted answer is great but for anyone who is looking for a hover like feel you can use setTimeout
on mouseover
and save the handle in a map (of let's say list ids to setTimeout Handle). On mouseover
clear the handle from setTimeout and delete it from the map
onMouseOver={() => this.onMouseOver(someId)}
onMouseOut={() => this.onMouseOut(someId)
And implement the map as follows:
onMouseOver(listId: string) {
this.setState({
... // whatever
});
const handle = setTimeout(() => {
scrollPreviewToComponentId(listId);
}, 1000); // Replace 1000ms with any time you feel is good enough for your hover action
this.hoverHandleMap[listId] = handle;
}
onMouseOut(listId: string) {
this.setState({
... // whatever
});
const handle = this.hoverHandleMap[listId];
clearTimeout(handle);
delete this.hoverHandleMap[listId];
}
And the map is like so,
hoverHandleMap: { [listId: string]: NodeJS.Timeout } = {};
I prefer onMouseOver
and onMouseOut
because it also applies to all the children in the HTMLElement
. If this is not required you may use onMouseEnter
and onMouseLeave
respectively.
It is not possible to use the RTMP protocol in HTML 5, because the RTMP protocol is only used between the server and the flash player. So you can use the other streaming protocols for viewing the streaming videos in HTML 5.
The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion
Cron is good for something that will run periodically, like every Saturday at 4am. There's also anacron, which works around power shutdowns, sleeps, and whatnot. As well as at.
But for a one-off solution, that doesn't require root or anything, you can just use date to compute the seconds-since-epoch of the target time as well as the present time, then use expr to find the difference, and sleep that many seconds.
just past this on head of your php page. before any code on this should be the top code.
<?php
header("Content-Type: application/vnd.ms-word");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("content-disposition: attachment;filename=Hawala.doc");
?>
this will convert all html to MSWORD, now you can customize it according to your client requirement.
The :before
pseudo element isn't needed for the clearfix hack itself.
It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.
display:table
is being used because display:block
doesn't do the trick. Using display:block
margins will collapse even with a :before
element.
There is one caveat: if vertical-align:baseline
is used in table cells with clearfixed <div>
elements, Firefox won't align well. Then you might prefer using display:block
despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.
Use Mysql
default CURDATE
function to get all the records of the day.
$records = DB::table('users')->select(DB::raw('*'))
->whereRaw('Date(created_at) = CURDATE()')->get();
dd($record);
Note
The difference between Carbon::now
vs Carbon::today
is just time.
e.g
Date printed through Carbon::now
will look like something:
2018-06-26 07:39:10.804786 UTC (+00:00)
While with Carbon::today
:
2018-06-26 00:00:00.0 UTC (+00:00)
To get the only records created today with now
can be fetched as:
Post::whereDate('created_at', Carbon::now()->format('m/d/Y'))->get();
while with today
:
Post::whereDate('created_at', Carbon::today())->get();
UPDATE
As of laravel 5.3, We have default where clause
whereDate / whereMonth / whereDay / whereYear
$users = User::whereDate('created_at', DB::raw('CURDATE()'))->get();
OR with DB
facade
$users = DB::table('users')->whereDate('created_at', DB::raw('CURDATE()'))->get();
Usage of the above listed where clauses
$users = User::whereMonth('created_at', date('m'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->month;
//select * from `users` where month(`created_at`) = "04"
$users = User::whereDay('created_at', date('d'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->day;
//select * from `users` where day(`created_at`) = "03"
$users = User::whereYear('created_at', date('Y'))->get();
//or you could also just use $carbon = \Carbon\Carbon::now(); $carbon->year;
//select * from `users` where year(`created_at`) = "2017"
You do not want to force the garbage collector to run.
However, if you ever did (as a purely academic exercise, of course):
GC.Collect()
This seems to work:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
var endpoint = socket.manager.handshaken[socket.id].address;
console.log('Client connected from: ' + endpoint.address + ":" + endpoint.port);
});
It's worked for me:
You aren't being very clear about what you want here, since I think @DWin's is technically correct, given your example code. I think what you really want is this:
y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
# first plot
plot(x, y1,ylim = range(c(y1,y2)))
# Add points
points(x, y2)
DWin's solution was operating under the implicit assumption (based on your example code) that you wanted to plot the second set of points overlayed on the original scale. That's why his image looks like the points are plotted at 1, 101, etc. Calling plot
a second time isn't what you want, you want to add to the plot using points
. So the above code on my machine produces this:
But DWin's main point about using ylim
is correct.
This works:
<img src="invalid_link"
onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>
Live demo: http://jsfiddle.net/oLqfxjoz/
As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;
.
You can simply use one line javascript in browser console to convert a hex map key to base64. Open console in latest browser (F12 on Windows, ? Option+? Command+I on macOS, Ctrl+? Shift+I on Linux) and paste the code and replace the SHA-1
, SHA-256
hex map that Google Play provides under Release Setup App signing:
> btoa('a7:77:d9:20:c8:01:dd:fa:2c:3b:db:b2:ef:c5:5a:1d:ae:f7:28:6f'.split(':').map(hc => String.fromCharCode(parseInt(hc, 16))).join(''))
< "p3fZIMgB3fosO9uy78VaHa73KG8="
You can also convert it here; run the below code snippet and paste hex map key and hit convert button:
document.getElementById('convert').addEventListener('click', function() {
document.getElementById('result').textContent = btoa(
document.getElementById('hex-map').value
.split(':')
.map(hc => String.fromCharCode(parseInt(hc, 16)))
.join('')
);
});
_x000D_
<textarea id="hex-map" placeholder="paste hex key map here" style="width: 100%"></textarea>
<button id="convert">Convert</button>
<p><code id="result"></code></p>
_x000D_
And if you want to reverse a key hash to check and validate it:
> atob('p3fZIMgB3fosO9uy78VaHa73KG8=').split('').map(c => c.charCodeAt(0).toString(16)).join(':')
< "a7:77:d9:20:c8:1:dd:fa:2c:3b:db:b2:ef:c5:5a:1d:ae:f7:28:6f"
document.getElementById('convert').addEventListener('click', function() {
document.getElementById('result').textContent = atob(document.getElementById('base64-hash').value)
.split('')
.map(c => c.charCodeAt(0).toString(16))
.join(':')
});
_x000D_
<textarea id="base64-hash" placeholder="paste base64 key hash here" style="width: 100%"></textarea>
<button id="convert">Convert</button>
<p><code id="result"></code></p>
_x000D_
you can find Java Communications API 2.0 in below link
There is a workaround which may help. You may "register" results for each set_fact iteration and then map that results to list:
---
- hosts: localhost
tasks:
- name: set fact
set_fact: foo_item="{{ item }}"
with_items:
- four
- five
- six
register: foo_result
- name: make a list
set_fact: foo="{{ foo_result.results | map(attribute='ansible_facts.foo_item') | list }}"
- debug: var=foo
Output:
< TASK: debug var=foo >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [localhost] => {
"var": {
"foo": [
"four",
"five",
"six"
]
}
}
You should watch session 147 from the WWDC 2010 Session videos. It is "Advanced Performance Optimization on iPhone OS, part 2".
There is a lot of good advice on memory optimizations.
Some of the tips are:
NSAutoReleasePool
s to make sure your memory usage does not spike.CGImageSource
when creating thumbnails from large images.If you've already installed Android Studio --
Add the following lines to the end of ~/.bashrc
or ~/.zshrc
(if using Oh My ZSH):
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Restart Terminal and you're good to go.
label
is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center
but since the label is only as wide as the text you don't notice.
The best thing to do is to apply a specific width to the label
that is greater than the width of the content - this will give you the results you want.
I've been bitten before by (someone else's) "clever" code that tries to modify a list while iterating over it. I resolved that I would never do it under any circumstance.
You can use the slice operator mylist[::3]
to skip across to every third item in your list.
mylist = [i for i in range(100)]
for i in mylist[::3]:
print(i)
Other points about my example relate to new syntax in python 3.0.
Python 3.0 range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.
You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read
public class MyClass implements MyInterface {
public void find(int x) throws A_Exception, B_Exception{
----
----
---
}
}
Then an interface would look like this
public interface MyInterface {
void find(int x) throws A_Exception, B_Exception;
}
This one of many ways, not tested, but should work.
$link = 'http://mydomain.com/index.php?id=115&Itemid=283&return=aHR0cDovL2NvbW11bml0';
$linkParts = explode('&return=', $link);
$link = $linkParts[0];
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
<Stack.Screen
name="SignInScreen"
component={Screens.SignInScreen}
options={{ headerShown: false }}
/>
options={{ headerShown: false }}
works for me.
** "@react-navigation/native": "^5.0.7",
"@react-navigation/stack": "^5.0.8",
If you want to use input instead of raw_input in python 2.x,then this trick will come handy
if hasattr(__builtins__, 'raw_input'):
input=raw_input
After which,
testVar = input("Ask user for something.")
will work just fine.
you can just do this:
string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();
I'll add that arrays are very low-level constructs in C++ and you should try to stay away from them as much as possible when "learning the ropes" -- even Bjarne Stroustrup recommends this (he's the designer of C++).
Vectors come very close to the same performance as arrays, but with a great many conveniences and safety features. You'll probably start using arrays when interfacing with API's that deal with raw arrays, or when building your own collections.
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_concat-ws
SELECT CONCAT_WS(" ", `first_name`, `last_name`) AS `whole_name` FROM `users`
public static bool IsPropertyExist(dynamic settings, string name)
{
if (settings is ExpandoObject)
return ((IDictionary<string, object>)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
var settings = new {Filename = @"c:\temp\q.txt"};
Console.WriteLine(IsPropertyExist(settings, "Filename"));
Console.WriteLine(IsPropertyExist(settings, "Size"));
Output:
True
False
@Maro For me it worked very simply!
After getting the error message alert, I executed 'eclipsec.exe' from a command prompt. This opened Eclipse. Then again I tried with 'eclipse.exe' and now it's working nice and well.
Unfortunately, it didn't give any technical reason for this.
Assuming you type in the full path to the bash script, use $0
and dirname
, e.g.:
#!/bin/bash
echo "$0"
dirname "$0"
Example output:
$ /a/b/c/myScript.bash
/a/b/c/myScript.bash
/a/b/c
If necessary, append the results of the $PWD
variable to a relative path.
EDIT: Added quotation marks to handle space characters.
docker ps -a
This command saves modified container state into a new image user/test_image
docker commit $CONTAINER_ID user/test_image
docker run -ti --entrypoint=sh user/test_image
Entrypoint argument description: https://docs.docker.com/engine/reference/run/#/entrypoint-default-command-to-execute-at-runtime
Steps above just start a stopped container with the same filesystem state. That is great for a quick investigation. But environment variables, network configuration, attached volumes and other staff is not inherited, you should specify all these arguments explicitly.
Steps to start a stopped container have been borrowed from here: (last comment) https://github.com/docker/docker/issues/18078
Please post your code,
<?php
echo $_GET['link'];
?>
or
<?php
echo $_REQUEST['link'];
?>
do work...
For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using Ad Hoc Helper available from the App Store. For further details on this method, see Craig Hockenberry's Beta testing on iPhone 2.0 article
For jailbroken iPhones, you can use the following method which I have personally tested using the AccelerometerGraph sample app on iPhone OS 3.0.
First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate:
Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.
Name: iPhone Developer
Certificate Type: Code Signing
Let me override defaults: Yes
Click Continue
Validity: 3650 days
Click Continue
Blank out the Email address field.
Click Continue until complete.
You should see "This root certificate is not trusted". This is expected.
Set the iPhone SDK to allow the self-signed certificate to be used:
sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist
If you have Xcode open, restart it for this change to take effect.
The following steps require openssh
, and uikittools
to be installed first. Replace jasoniphone.local
with the hostname of the target device. Be sure to set your own password on both the mobile
and root
users after installing SSH.
To manually compile and install your application on the phone as a system app (bypassing Apple's installation system):
Project, Set Active SDK, Device and Set Active Build Configuration, Release.
Compile your project normally (using Build, not Build & Go).
In the build/Release-iphoneos
directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device.
scp -r AccelerometerGraph.app root@jasoniphone:/Applications/
Let SpringBoard know the new application has been installed:
ssh [email protected] uicache
This only has to be done when you add or remove applications. Updated applications just need to be relaunched.
To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project.
Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard:
ssh [email protected] rm -r /Applications/AccelerometerGraph.app &&
ssh [email protected] uicache
To get this to work for me I had to drill down in the Python directory using the Python command prompt (on WIN10 from VS CODE). In my case it was in my "AppData\Local\Programs\Python\python35-32" directory. From there now I ran the command...
python -m pip install --upgrade pip
This worked and I'm good to go.
You can also cast an array to a string like...
newStr = String(aa);
I also agree with Tor Valamo's answer, console.log should have no problem with arrays, no need to convert to a string unless you're debugging something or just curious.
Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:
In your BrowserWindow declaration, add the following webPreferences field:
i.e, instead of plain mainWindow = new BrowserWindow()
, write
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
To unset the $_POST
variable, redeclare it as an empty array:
$_POST = array();
System.out.println(isLeapYear);
should work just fine.
Incidentally, in
else if ((year % 4 == 0) && (year % 100 == 0)) isLeapYear = false; else if ((year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)) isLeapYear = true;
the year % 400
part will never be reached because if (year % 4 == 0) && (year % 100 == 0) && (year % 400 == 0)
is true, then (year % 4 == 0) && (year % 100 == 0)
must have succeeded.
Maybe swap those two conditions or refactor them:
else if ((year % 4 == 0) && (year % 100 == 0))
isLeapYear = (year % 400 == 0);
you can use:
define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";
In a couple of experiments in my masters thesis (e.g. page 59), I found that the bias might be important for the first layer(s), but especially at the fully connected layers at the end it seems not to play a big role.
This might be highly dependent on the network architecture / dataset.
You need to set ulimit -c
. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited
and check if everything is correct ulimit -a
. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>
.
You can't call _doPostBack()
because it forces submition of the form. Why don't you disable the PostBack
on the UpdatePanel
?
I actually had solved this not long after posting but failed to post my solution. I honestly don't remember it. But, I had to re-visit the task when I was given a new project that faced the same challenge.
I used the ReceivedTime property of Outlook.MailItem to get the time-stamp, I was able to use this as a unique identifier for each file so they do not override one another.
Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\PathToDirectory\"
Dim dateFormat As String
dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
For Each objAtt In itm.Attachments
objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
Next
End Sub
Thanks a ton for the other solutions, many of them go above an beyond :)
Highly recommend something more like this:
public class Person {
public string Name {get; set;}
public string Email {get; set;}
}
var people = new List<Person>();
Easier to read, easy to code.
What you are seeing is a parameterized query. They are frequently used when executing dynamic SQL from a program.
For example, instead of writing this (note: pseudocode):
ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = 7")
result = cmd.Execute()
You write this:
ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = ?")
cmd.Parameters.Add(7)
result = cmd.Execute()
This has many advantages, as is probably obvious. One of the most important: the library functions which parse your parameters are clever, and ensure that strings are escaped properly. For example, if you write this:
string s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE (name = '" + s + "')"
cmd.Execute()
What happens when the user enters this?
Robert'); DROP TABLE students; --
(Answer is here)
Write this instead:
s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE name = ?"
cmd.Parameters.Add(s)
cmd.Execute()
Then the library will sanitize the input, producing this:
"SELECT * FROM students where name = 'Robert''); DROP TABLE students; --'"
Not all DBMS's use ?
. MS SQL uses named parameters, which I consider a huge improvement:
cmd.Text = "SELECT thingA FROM tableA WHERE thingB = @varname"
cmd.Parameters.AddWithValue("@varname", 7)
result = cmd.Execute()
I had the same issue since I changed my app ID in config.xml file.
I used to open my Android project by choosing among recent projects of Android Studio.
I just File > Open > My project to get it working again.
Your code works for me. Here is my test case:
mysql> CREATE TABLE carmake (country ENUM('Canada', 'United States'));
Query OK, 0 rows affected (0.00 sec)
mysql> SHOW CREATE TABLE carmake;
+---------+-------------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+-------------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Canada','United States') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+-------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE carmake CHANGE country country ENUM('Sweden','Malaysia');
Query OK, 0 rows affected (0.53 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> SHOW CREATE TABLE carmake;
+---------+--------------------------------------------------------------------------------------------------------------------+
| Table | Create Table |
+---------+--------------------------------------------------------------------------------------------------------------------+
| carmake | CREATE TABLE `carmake` (
`country` enum('Sweden','Malaysia') default NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1 |
+---------+--------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
What error are you seeing?
FWIW this would also work:
ALTER TABLE carmake MODIFY COLUMN country ENUM('Sweden','Malaysia');
I would actually recommend a country table rather than enum column. You may have hundreds of countries which would make for a rather large and awkward enum.
EDIT: Now that I can see your error message:
ERROR 1265 (01000): Data truncated for column 'country' at row 1.
I suspect you have some values in your country column that do not appear in your ENUM
. What is the output of the following command?
SELECT DISTINCT country FROM carmake;
ANOTHER EDIT: What is the output of the following command?
SHOW VARIABLES LIKE 'sql_mode';
Is it STRICT_TRANS_TABLES
or STRICT_ALL_TABLES
? That could lead to an error, rather than the usual warning MySQL would give you in this situation.
YET ANOTHER EDIT: Ok, I now see that you definitely have values in the table that are not in the new ENUM
. The new ENUM
definition only allows 'Sweden'
and 'Malaysia'
. The table has 'USA'
, 'India'
and several others.
LAST EDIT (MAYBE): I think you're trying to do this:
ALTER TABLE carmake CHANGE country country ENUM('Italy', 'Germany', 'England', 'USA', 'France', 'South Korea', 'Australia', 'Spain', 'Czech Republic', 'Sweden', 'Malaysia') DEFAULT NULL;
You can solve it very simple way just invoking the input. However, if you press Enter
then the console will disapper again. Simply use this Console.ReadLine();
or Console.Read();
The heading looks bold because of its large size, if you have applied bold or want to change behaviour, you can do:
h1 { font-weight:normal; }
In the width field of button, replace wrap-content
with 0dp
.
Use layout_weight attribute of a view.
android:layout_width="0dp"
This is how your code will look like:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:text="Register"
android:id="@+id/register"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_weight="1" />
<Button
android:text="Not this time"
android:id="@+id/cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:layout_weight="1" />
</LinearLayout>
layout_weight is used to distribute the whatever left space into proportions. In this case, the two buttons are taking "0dp" width. So, the remaining space will be divided into 1:1 proportion among them, i.e. the space will be divided equally between the Button Views.
You can't send email using javascript or html. You need server side scripts in php or other technologies to send email.
In the old console layout :
In the new cloud console layout :
In case of both procedures, you find your client ID and client secret at the same page. If you're using a different client ID and client secret, replace it with the ones you find here.
During my first experiments today, I've succesfully used the "Key for server apps" as a developer key for connecting with the "contacts", "userinfo" and "analytics" API. I did this using the PHP client.
Wading through the Google API docs certainly is a pain in the @$$... I hope this info will be useful to anyone.
All of these are kinds of indices.
primary: must be unique, is an index, is (likely) the physical index, can be only one per table.
unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.
index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.
fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.
Yep, why not?
fs.Write(myByteArray, 0, myByteArray.Length);
That'd be .delay()
.
If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.
As one of the possible codes
echo off
for /f "usebackq tokens=* delims= " %%x in (`chdir`) do set var=%var% %%x
echo The current directory is: "%var:~1%"
I've been using this in an Xcode JNI project to recursively build my test classes:
find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}
This might be useful for someone.
Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.
To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.
def compute_PMF(data):
import numpy as np
from collections import Counter
_, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
h = Counter(np.digitize(data,bins) - 1)
weights = np.asarray(list(h.values()))
weights = weights / weights.sum()
values = np.asarray(list(h.keys()))
return weights, values
####
Refs:
[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html
You can generate the WS proxy classes using WSCF (Web Services Contract First) tool from thinktecture.com. So essentially, YOU CAN create webservices from wsdl's. Creating the asmx's, maybe not, but that's the easy bit isn't it? This tool integrates brilliantly into VS2005-8 (new version for 2010/WCF called WSCF-blue). I've used it loads and always found it to be really good.
You can run OpenSSH on Cygwin, and even install it as a Windows service.
I once used it this way to easily add backups of a Unix system - it would rsync a bunch of files onto the Windows server, and the Windows server had full tape backups.
I think Chris Coyier has solution for that hashing problem, have a look at his screencast:
The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex
which is in the current version looks like:
module.exports = function (opts) {
opts = opts || {};
var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';
return opts.exact ? new RegExp('(?:^' + regex + '$)') :
new RegExp('(?:^|\\s)' + regex, 'g');
};
I can confirm this works:
class CSSImporter < Sass::Importers::Filesystem
def extensions
super.merge('css' => :scss)
end
end
view_context = ActionView::Base.new
css = Sass::Engine.new(
template,
syntax: :scss,
cache: false,
load_paths: Rails.application.assets.paths,
read_cache: false,
filesystem_importer: CSSImporter # Relevant option,
sprockets: {
context: view_context,
environment: Rails.application.assets
}
).render
Credit to Chriss Epstein: https://github.com/sass/sass/issues/193
If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:
var $list = $("#tableOrForm :input[type='text']");
$list.each(function(){
// Go on with your code.
});
What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:
var $currentItem = $(this);
This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.
Hope this helps anyone!
As far as I can tell, this is a bug in setuptools where it isn't removing the setuptools specific options before calling up to the base class in the standard library: https://bitbucket.org/pypa/setuptools/issue/29/avoid-userwarnings-emitted-when-calling
If you have an unconditional import setuptools
in your setup.py
(as you should if using the setuptools specific options), then the fact the script isn't failing with ImportError
indicates that setuptools is properly installed.
You can silence the warning as follows:
python -W ignore::UserWarning:distutils.dist setup.py <any-other-args>
Only do this if you use the unconditional import that will fail completely if setuptools isn't installed :)
(I'm seeing this same behaviour in a checkout from the post-merger setuptools repo, which is why I'm confident it's a setuptools bug rather than a system config problem. I expect pre-merge distribute would have the same problem)
What I did is to use a hidden field and put the timestamp on it and then compared it to the timestamp on the Server using PHP.
If it was faster than 15 seconds (depends on how big or small is your forms) that was a bot.
Hope this help
I agree with Icarus (would have commented if I could), but instead of using a CustomObject class, I would use a Dictionary (in case Facebook adds something).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
or
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
Simply put, Git is a version control system that lets you manage and keep track of your source code history. GitHub is a cloud-based hosting service that lets you manage Git repositories. If you have open-source projects that use Git, then GitHub is designed to help you better manage them.
Things seems a little confused in the code in your question, so I am going to give you an example of what I think you are try to do.
First considerations are about mixing HTML, Javascript and CSS:
Why is using onClick() in HTML a bad practice?
I will be removing inline content and splitting these into their appropriate files.
Next, I am going to go with the "click" event and displose of the "change" event, as it is not clear that you want or need both.
Your function changeBackground
sets both the backround color and the text color to the same value (your text will not be seen), so I am caching the color value as we don't need to look it up in the DOM twice.
CSS
#TheForm {
margin-left: 396px;
}
#submitColor {
margin-left: 48px;
margin-top: 5px;
}
HTML
<form id="TheForm">
<input id="color" type="text" />
<br/>
<input id="submitColor" value="Submit" type="button" />
</form>
<span id="coltext">This text should have the same color as you put in the text box</span>
Javascript
function changeBackground() {
var color = document.getElementById("color").value; // cached
// The working function for changing background color.
document.bgColor = color;
// The code I'd like to use for changing the text simultaneously - however it does not work.
document.getElementById("coltext").style.color = color;
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Source: w3schools
CSS colors are defined using a hexadecimal (hex) notation for the combination of Red, Green, and Blue color values (RGB). The lowest value that can be given to one of the light sources is 0 (hex 00). The highest value is 255 (hex FF).
Hex values are written as 3 double digit numbers, starting with a # sign.
Update: as pointed out by @Ian
Hex can be either 3 or 6 characters long
Source: W3C
The format of an RGB value in hexadecimal notation is a ‘#’ immediately followed by either three or six hexadecimal characters. The three-digit RGB notation (#rgb) is converted into six-digit form (#rrggbb) by replicating digits, not by adding zeros. For example, #fb0 expands to #ffbb00. This ensures that white (#ffffff) can be specified with the short notation (#fff) and removes any dependencies on the color depth of the display.
Here is an alternative function that will check that your input is a valid CSS Hex Color, it will set the text color only or throw an alert if it is not valid.
For regex testing, I will use this pattern
/^#(?:[0-9a-f]{3}){1,2}$/i
but if you were regex matching and wanted to break the numbers into groups then you would require a different pattern
function changeBackground() {
var color = document.getElementById("color").value.trim(),
rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i;
if (rxValidHex.test(color)) {
document.getElementById("coltext").style.color = color;
} else {
alert("Invalid CSS Hex Color");
}
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Here is a further modification that will allow colours by name along with by hex.
function changeBackground() {
var names = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond", "Blue", "BlueViolet", "Brown", "BurlyWood", "CadetBlue", "Chartreuse", "Chocolate", "Coral", "CornflowerBlue", "Cornsilk", "Crimson", "Cyan", "DarkBlue", "DarkCyan", "DarkGoldenRod", "DarkGray", "DarkGrey", "DarkGreen", "DarkKhaki", "DarkMagenta", "DarkOliveGreen", "Darkorange", "DarkOrchid", "DarkRed", "DarkSalmon", "DarkSeaGreen", "DarkSlateBlue", "DarkSlateGray", "DarkSlateGrey", "DarkTurquoise", "DarkViolet", "DeepPink", "DeepSkyBlue", "DimGray", "DimGrey", "DodgerBlue", "FireBrick", "FloralWhite", "ForestGreen", "Fuchsia", "Gainsboro", "GhostWhite", "Gold", "GoldenRod", "Gray", "Grey", "Green", "GreenYellow", "HoneyDew", "HotPink", "IndianRed", "Indigo", "Ivory", "Khaki", "Lavender", "LavenderBlush", "LawnGreen", "LemonChiffon", "LightBlue", "LightCoral", "LightCyan", "LightGoldenRodYellow", "LightGray", "LightGrey", "LightGreen", "LightPink", "LightSalmon", "LightSeaGreen", "LightSkyBlue", "LightSlateGray", "LightSlateGrey", "LightSteelBlue", "LightYellow", "Lime", "LimeGreen", "Linen", "Magenta", "Maroon", "MediumAquaMarine", "MediumBlue", "MediumOrchid", "MediumPurple", "MediumSeaGreen", "MediumSlateBlue", "MediumSpringGreen", "MediumTurquoise", "MediumVioletRed", "MidnightBlue", "MintCream", "MistyRose", "Moccasin", "NavajoWhite", "Navy", "OldLace", "Olive", "OliveDrab", "Orange", "OrangeRed", "Orchid", "PaleGoldenRod", "PaleGreen", "PaleTurquoise", "PaleVioletRed", "PapayaWhip", "PeachPuff", "Peru", "Pink", "Plum", "PowderBlue", "Purple", "Red", "RosyBrown", "RoyalBlue", "SaddleBrown", "Salmon", "SandyBrown", "SeaGreen", "SeaShell", "Sienna", "Silver", "SkyBlue", "SlateBlue", "SlateGray", "SlateGrey", "Snow", "SpringGreen", "SteelBlue", "Tan", "Teal", "Thistle", "Tomato", "Turquoise", "Violet", "Wheat", "White", "WhiteSmoke", "Yellow", "YellowGreen"],
color = document.getElementById("color").value.trim(),
rxValidHex = /^#(?:[0-9a-f]{3}){1,2}$/i,
formattedName = color.charAt(0).toUpperCase() + color.slice(1).toLowerCase();
if (names.indexOf(formattedName) !== -1 || rxValidHex.test(color)) {
document.getElementById("coltext").style.color = color;
} else {
alert("Invalid CSS Color");
}
}
document.getElementById("submitColor").addEventListener("click", changeBackground, false);
On jsfiddle
Solution for Ruby 1.8 when you have an arbitrary DateTime object:
1.8.7-p374 :001 > require 'date'
=> true
1.8.7-p374 :002 > DateTime.new(2012, 1, 15).strftime('%s')
=> "1326585600"
Quoting MDN
The
ChildNode.after()
method inserts a set of Node orDOMString
objects in the children list of thisChildNode
's parent, just after thisChildNode
. DOMString objects are inserted as equivalent Text nodes.
The browser support is Chrome(54+), Firefox(49+) and Opera(39+). It doesn't support IE and Edge.
var elm=document.getElementById('div1');
var elm1 = document.createElement('p');
var elm2 = elm1.cloneNode();
elm.append(elm1,elm2);
//added 2 paragraphs
elm1.after("This is sample text");
//added a text content
elm1.after(document.createElement("span"));
//added an element
console.log(elm.innerHTML);
_x000D_
<div id="div1"></div>
_x000D_
In the snippet, I used another term append too
I came up with this simple and straight-forward (i hope so) code example which should explain itself!
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
/* function header definitions */
char* getString(); //<- with malloc (good practice)
char * getStringNoMalloc(); //<- without malloc (fails! don't do this!)
void getStringCallByRef(char* reference); //<- callbyref (good practice)
/* the main */
int main(int argc, char*argv[]) {
//######### calling with malloc
char * a = getString();
printf("MALLOC ### a = %s \n", a);
free(a);
//######### calling without malloc
char * b = getStringNoMalloc();
printf("NO MALLOC ### b = %s \n", b); //this doesnt work, question to yourself: WHY?
//HINT: the warning says that a local reference is returned. ??!
//NO free here!
//######### call-by-reference
char c[100];
getStringCallByRef(c);
printf("CALLBYREF ### c = %s \n", c);
return 0;
}
//WITH malloc
char* getString() {
char * string;
string = malloc(sizeof(char)*100);
strcat(string, "bla");
strcat(string, "/");
strcat(string, "blub");
printf("string : '%s'\n", string);
return string;
}
//WITHOUT malloc (watch how it does not work this time)
char* getStringNoMalloc() {
char string[100] = {};
strcat(string, "bla");
strcat(string, "/");
strcat(string, "blub");
//INSIDE this function "string" is OK
printf("string : '%s'\n", string);
return string; //but after returning.. it is NULL? :)
}
// ..and the call-by-reference way to do it (prefered)
void getStringCallByRef(char* reference) {
strcat(reference, "bla");
strcat(reference, "/");
strcat(reference, "blub");
//INSIDE this function "string" is OK
printf("string : '%s'\n", reference);
//OUTSIDE it is also OK because we hand over a reference defined in MAIN
// and not defined in this scope (local), which is destroyed after the function finished
}
When compiling it, you get the [intended] warning:
me@box:~$ gcc -o example.o example.c
example.c: In function ‘getStringNoMalloc’:
example.c:58:16: warning: function returns address of local variable [-Wreturn-local-addr]
return string; //but after returning.. it is NULL? :)
^~~~~~
...basically what we are discussing here!
running my example yields this output:
me@box:~$ ./example.o
string : 'bla/blub'
MALLOC ### a = bla/blub
string : 'bla/blub'
NO MALLOC ### b = (null)
string : 'bla/blub'
CALLBYREF ### c = bla/blub
Theory:
This has been answered very nicely by User @phoxis. Basically think about it this way: Everything inbetween { and } is local scope, thus by the C-Standard is "undefined" outside. By using malloc you take memory from the HEAP (programm scope) and not from the STACK (function scope) - thus its 'visible' from outside. The second correct way to do it is call-by-reference. Here you define the var inside the parent-scope, thus it is using the STACK (because the parent scope is the main()).
Summary:
3 Ways to do it, One of them false. C is kind of to clumsy to just have a function return a dynamically sized String. Either you have to malloc and then free it, or you have to call-by-reference. Or use C++ ;)
Use this function: http://br.php.net/json_decode This will automatically create PHP arrays.
You can just run
git config --global credential.helper wincred
after installing and logging into GIT for windows in your system.
This worked for me:
openssl s_client -help 2>&1 > /dev/null | egrep "\-(ssl|tls)[^a-z]"
Please let me know if this is wrong.
Since my directory was in C:\users I had to run my powershell as administrator,
del ./[your Folder name] -Force -Recurse
this command worked for me.
You want to count the number of itemids in your array. Simply use:
int counter=list.size();
Less code increases efficiency. Do not re-invent the wheel...
You would never want to run that, but you may want to source it.
. ~/.bash_profile
source ~/.bash_profile
both should work. But this is an odd request, because that file should be sourced automatically when you start bash, unless you're explicitly starting it non-interactively. From the man page:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behavior.
For me what worked was:
git fetch
Which pulls all the refs down to your machine for all the branches on remote. Then I could do
git checkout <branchname>
and that worked perfectly. Similar to the top voted answer, but a little more simple.
For me, the problem was in my IBAction with a UIButton.
When you Ctrl+Drag to create an IBAction from a UIButton, make sure to select "UIButton" from the Type dropdown. The default selection of AnyObject causes the app to crash when you tap on the UIButton.
In C# 7.1 and later, type can be inferred by using the default
literal instead of the default
operator so it can be written as below:
v2 = v1 ?? default;
Maybe also try this? PDF Focus
This .Net library allows you to solve the problem :)
This code will help (Convert 1000 PDF files to 300-dpi TIFF files in C#):
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
string[] pdfFiles = Directory.GetFiles(@"d:\Folder with 1000 pdfs\", "*.pdf");
string folderWithTiffs = @"d:\Folder with TIFFs\";
foreach (string pdffile in pdfFiles)
{
f.OpenPdf(pdffile);
if (f.PageCount > 0)
{
//save all pages to tiff files with 300 dpi
f.ToImage(folderWithTiffs, Path.GetFileNameWithoutExtension(pdffile), System.Drawing.Imaging.ImageFormat.Tiff, 300);
}
f.ClosePdf();
}
You can change from the "build.gradle" file the line:
compileSdkVersion 18
to the sdk that you want to be used.
You can access this hello function anywhere in the module
Controller one
$scope.save = function() {
$scope.hello();
}
second controller
$rootScope.hello = function() {
console.log('hello');
}
Add the column and update all rows in the DataTable
, for example:
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("ID", typeof(Int32)));
tbl.Columns.Add(new DataColumn("Name", typeof(string)));
for (Int32 i = 1; i <= 10; i++) {
DataRow row = tbl.NewRow();
row["ID"] = i;
row["Name"] = i + ". row";
tbl.Rows.Add(row);
}
DataColumn newCol = new DataColumn("NewColumn", typeof(string));
newCol.AllowDBNull = true;
tbl.Columns.Add(newCol);
foreach (DataRow row in tbl.Rows) {
row["NewColumn"] = "You DropDownList value";
}
//if you don't want to allow null-values'
newCol.AllowDBNull = false;
First off, your code is a bit off. aes()
is an argument in ggplot()
, you don't use ggplot(...)
+ aes(...) + layers
Second, from the help file ?geom_bar
:
By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.
You want the second case, where the height of the bar is equal to the conversion_rate
So what you want is...
data_country <- data.frame(country = c("China", "Germany", "UK", "US"),
conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")
Result:
If you also need the index, use random.randrange
from random import randrange
random_index = randrange(len(foo))
print(foo[random_index])
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
Please do not use NSDate
, CFAbsoluteTimeGetCurrent
, or gettimeofday
to measure elapsed time. These all depend on the system clock, which can change at any time due to many different reasons, such as network time sync (NTP) updating the clock (happens often to adjust for drift), DST adjustments, leap seconds, and so on.
This means that if you're measuring your download or upload speed, you will get sudden spikes or drops in your numbers that don't correlate with what actually happened; your performance tests will have weird incorrect outliers; and your manual timers will trigger after incorrect durations. Time might even go backwards, and you end up with negative deltas, and you can end up with infinite recursion or dead code (yeah, I've done both of these).
Use mach_absolute_time
. It measures real seconds since the kernel was booted. It is monotonically increasing (will never go backwards), and is unaffected by date and time settings. Since it's a pain to work with, here's a simple wrapper that gives you NSTimeInterval
s:
// LBClock.h
@interface LBClock : NSObject
+ (instancetype)sharedClock;
// since device boot or something. Monotonically increasing, unaffected by date and time settings
- (NSTimeInterval)absoluteTime;
- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute;
@end
// LBClock.m
#include <mach/mach.h>
#include <mach/mach_time.h>
@implementation LBClock
{
mach_timebase_info_data_t _clock_timebase;
}
+ (instancetype)sharedClock
{
static LBClock *g;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
g = [LBClock new];
});
return g;
}
- (id)init
{
if(!(self = [super init]))
return nil;
mach_timebase_info(&_clock_timebase);
return self;
}
- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute
{
uint64_t nanos = (machAbsolute * _clock_timebase.numer) / _clock_timebase.denom;
return nanos/1.0e9;
}
- (NSTimeInterval)absoluteTime
{
uint64_t machtime = mach_absolute_time();
return [self machAbsoluteToTimeInterval:machtime];
}
@end
Try changing
git checkout -- a
to
git checkout -- `git ls-files -m -- a`
Since version 1.7.0, Git's ls-files
honors the skip-worktree flag.
Running your test script (with some minor tweaks changing git commit
... to git commit -q
and git status
to git status --short
) outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/c/ac
a/b/ab
b/a/ba
Running your test script with the proposed checkout
change outputs:
Initialized empty Git repository in /home/user/repo/.git/
After read-tree:
a/a/aa
a/b/ab
b/a/ba
After modifying:
b/a/ba
D a/a/aa
D a/b/ab
M b/a/ba
After checkout:
M b/a/ba
a/a/aa
a/b/ab
b/a/ba
You can do this to bubble events to parent document:
$('iframe').load(function() {
var eventlist = 'click dblclick \
blur focus focusin focusout \
keydown keypress keyup \
mousedown mouseenter mouseleave mousemove mouseover mouseout mouseup mousemove \
touchstart touchend touchcancel touchleave touchmove';
var iframe = $('iframe').contents().find('html');
// Bubble events to parent
iframe.on(eventlist, function(event) {
$('html').trigger(event);
});
});
Just extend the eventlist for more events.
I guess you're searching for this custom function. It takes a data-toggle attribute and creates dynamically the necessary div to place the remote content. Just place the data-toggle="ajaxModal" on any link you want to load via AJAX.
The JS part:
$('[data-toggle="ajaxModal"]').on('click',
function(e) {
$('#ajaxModal').remove();
e.preventDefault();
var $this = $(this)
, $remote = $this.data('remote') || $this.attr('href')
, $modal = $('<div class="modal" id="ajaxModal"><div class="modal-body"></div></div>');
$('body').append($modal);
$modal.modal({backdrop: 'static', keyboard: false});
$modal.load($remote);
}
);
Finally, in the remote content, you need to put the entire structure to work.
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<a href="#" class="btn btn-white" data-dismiss="modal">Close</a>
<a href="#" class="btn btn-primary">Button</a>
<a href="#" class="btn btn-primary">Another button...</a>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
Comment from answer: "make sure you use the same open connection for all the database calls inside the transaction. – Magnus"
Our users are stored in a separate db from the data I was working with in the transactions. Opening the db connection to get the user was causing this error for me. Moving the other db connection and user lookup outside of the transaction scope fixed the error.
No. To do it just once you would simply write the delete statement for the table you want to cascade.
DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);
DELETE FROM some_table;
You can also use awk:
awk 'END {print NR,"lines"}' filename
Or
awk 'END {print NR}' filename
Thanks to yojimbo for his answer. To add to his sample, I wanted to use the jquery method $.getJSON which puts a random callback in the query string so I also wanted to parse that out in the Node.js. I also wanted to pass an object back and use the stringify function.
This is my Client Side code.
$.getJSON("http://localhost:8124/dummy?action=dostuff&callback=?",
function(data){
alert(data);
},
function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
});
This is my Server side Node.js
var http = require('http');
var querystring = require('querystring');
var url = require('url');
http.createServer(function (req, res) {
//grab the callback from the query string
var pquery = querystring.parse(url.parse(req.url).query);
var callback = (pquery.callback ? pquery.callback : '');
//we probably want to send an object back in response to the request
var returnObject = {message: "Hello World!"};
var returnObjectString = JSON.stringify(returnObject);
//push back the response including the callback shenanigans
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(callback + '(\'' + returnObjectString + '\')');
}).listen(8124);
The following code snippet is doing it for me (lat and lng are doubles declared above this bit):
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
Use shell=True
if you're passing a string to subprocess.call
.
From docs:
If passing a single string, either
shell
must beTrue
or else the string must simply name the program to be executed without specifying any arguments.
subprocess.call(crop, shell=True)
or:
import shlex
subprocess.call(shlex.split(crop))
Place the following HTML redirect code between the and tags of your HTML code.
<meta HTTP-EQUIV="REFRESH" content="3; url=http://www.yourdomain.com/index.html">
The above HTML redirect code will redirect your visitors to another web page instantly. The content="3; may be changed to the number of seconds you want the browser to wait before redirecting. 4, 5, 8, 10 or 15 seconds, etc.
My version using variables in a bash script:
Find any backslashes and replace with forward slashes:
input="This has a backslash \\"
output=$(echo "$input" | sed 's,\\,/,g')
echo "$output"
You could use a colormap such as HSV to generate a set of colors. For example:
cc=hsv(12);
figure;
hold on;
for i=1:12
plot([0 1],[0 i],'color',cc(i,:));
end
MATLAB has 13 different named colormaps ('doc colormap' lists them all).
Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.
I am using husky and git-branch-is:
As of husky v1+:
// package.json
{
"husky": {
"hooks": {
"post-merge": "(git-branch-is master && npm version minor ||
(git-branch-is dev && npm --no-git-tag-version version patch)",
}
}
}
Prior to husky V1:
"scripts": {
...
"postmerge": "(git-branch-is master && npm version minor ||
(git-branch-is dev && npm --no-git-tag-version version patch)",
...
},
Read more about npm version
Webpack or Vue.js
If you are using webpack or Vue.js, you can display this in the UI using Auto inject version - Webpack plugin
NUXT
In nuxt.config.js
:
var WebpackAutoInject = require('webpack-auto-inject-version');
module.exports = {
build: {
plugins: [
new WebpackAutoInject({
// options
// example:
components: {
InjectAsComment: false
},
}),
]
},
}
Inside your template
for example in the footer:
<p> All rights reserved © 2018 [v[AIV]{version}[/AIV]]</p>
The function mb_strlen()
is not enabled by default in PHP. Please read the manual for installation details:
Based on the answer from Luis, you can do something more like the default findBy method.
First, create a default repository class that is going to be used by all your entities.
/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );
Or you can edit this in config.yml
doctrine: orm: default_repository_class: MyCompany\Repository
Then:
<?php
namespace MyCompany;
use Doctrine\ORM\EntityRepository;
class Repository extends EntityRepository {
public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
{
$qb = $this->getEntityManager()->createQueryBuilder();
$expr = $this->getEntityManager()->getExpressionBuilder();
$qb->select( 'entity' )
->from( $this->getEntityName(), 'entity' );
foreach ( $criteria as $field => $value ) {
// IF INTEGER neq, IF NOT notLike
if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
$qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
} else {
$qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );
}
}
if ( $orderBy ) {
foreach ( $orderBy as $field => $order ) {
$qb->addOrderBy( 'entity.' . $field, $order );
}
}
if ( $limit )
$qb->setMaxResults( $limit );
if ( $offset )
$qb->setFirstResult( $offset );
return $qb->getQuery()
->getResult();
}
}
The usage is the same than the findBy method, example:
$entityManager->getRepository( 'MyRepo' )->findByNot(
array( 'status' => Status::STATUS_DISABLED )
);
The correct solution is to store the ZIP Code in the database as a STRING. Despite the fact that it may look like a number, it isn't. It's a code, where each part has meaning.
A number is a thing you do arithmetic on. A ZIP Code is not that.
jQuery has the following signature for the .on()
method: .on( events [, selector ] [, data ], handler )
Events could be anyone of the ones listed on this reference:
https://developer.mozilla.org/en-US/docs/Web/Events
Though, they are not all supported by every browser.
Mozilla states the following about the input event:
The DOM input event is fired synchronously when the value of an or element is changed. Additionally, it fires on contenteditable editors when its contents are changed.
The syntax of ng-style
is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:
<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
And then in your controller:
$scope.width = '900px';
$scope.bgColor = 'red';
This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.
Interestingly enough, the foreach loop is actually the most efficient way of doing this.
Since the OP specifically asked about efficiency, it should be pointed out that all the current answers are in fact much less efficient than a foreach.
I did a benchmark on this with php 5.4, and the reset/key pointer method (accepted answer) seems to be about 7 times slower than a foreach. Other approaches manipulating the entire array (array_keys, array_flip) are obviously even slower than that and become much worse when working with a large array.
Foreach is not inefficient at all, feel free to use it!
Edit 2015-03-03:
Benchmark scripts have been requested, I don't have the original ones but made some new tests instead. This time I found the foreach only about twice as fast as reset/key. I used a 100-key array and ran each method a million times to get some noticeable difference, here's code of the simple benchmark:
$array = [];
for($i=0; $i < 100; $i++)
$array["key$i"] = $i;
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
foreach ($array as $firstKey => $firstValue) {
break;
}
}
echo "foreach to get first key and value: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
$firstValue = reset($array);
$firstKey = key($array);
}
echo "reset+key to get first key and value: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
reset($array);
$firstKey = key($array);
}
echo "reset+key to get first key: " . (microtime(true) - $start) . " seconds <br />";
for($i=0, $start = microtime(true); $i < 1000000; $i++) {
$firstKey = array_keys($array)[0];
}
echo "array_keys to get first key: " . (microtime(true) - $start) . " seconds <br />";
On my php 5.5 this outputs:
foreach to get first key and value: 0.15501809120178 seconds
reset+key to get first key and value: 0.29375791549683 seconds
reset+key to get first key: 0.26421809196472 seconds
array_keys to get first key: 10.059751987457 seconds
reset+key http://3v4l.org/b4DrN/perf#tabs
foreach http://3v4l.org/gRoGD/perf#tabs
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
I prefer to work with the PSDrive WSMan:\
.
Get TrustedHosts
Get-Item WSMan:\localhost\Client\TrustedHosts
Set TrustedHosts
provide a single, comma-separated, string of computer names
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineA,machineB'
or (dangerous) a wild-card
Set-Item WSMan:\localhost\Client\TrustedHosts -Value '*'
to append to the list, the -Concatenate
parameter can be used
Set-Item WSMan:\localhost\Client\TrustedHosts -Value 'machineC' -Concatenate
Might be late to answer - if you don't want to modify your current code a lot and still be able to have similar validation code all over your project, you may try this one too - https://github.com/vishalvisd/react-validator.
You can find some demos and plugins here.
If you are using the fluent API, you need to set it up via the Executor
:
Executor.unregisterScheme("https");
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext,
SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Executor.registerScheme(new Scheme("https", 443, sslSocketFactory));
... where sslContext
is the SSLContext created as shown in the ZZ Coder's answer.
After that, you can do your http requests as:
String responseAsString = Request.Get("https://192.168.1.0/whatever.json")
.execute().getContent().asString();
Note: tested with HttpClient 4.2
My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.
This did not resolve my problem:
set echo off
This resolved my problem:
set verify off
As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:
If the server uses Pure-FTP as the FTP server:
421 Can't change directory to /var/ftp/ error message.
If the server uses ProFTP as the FTP server:
530 Login Authentication Failed error message.
When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:
User name: [email protected]
In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.
For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:
When users log in to FTP anonymously, they must format usernames as
[email protected]
, whereexample.com
represents the user's domain name. This requirement directs your server to the correctpublic_ftp
directory.
If you happen to be using PyTorch already, you should go with their CosineSimilarity implementation.
Suppose you have two n
-dimensional numpy.ndarray
s, v1
and v2
, i.e. their shapes are both (n,)
. Here's how you get their cosine similarity:
import torch
import torch.nn as nn
cos = nn.CosineSimilarity()
cos(torch.tensor([v1]), torch.tensor([v2])).item()
Or suppose you have two numpy.ndarray
s w1
and w2
, whose shapes are both (m, n)
. The following gets you a list of cosine similarities, each being the cosine similarity between a row in w1
and the corresponding row in w2
:
cos(torch.tensor(w1), torch.tensor(w2)).tolist()
This is what i did:
c1 = a1 - b1;
d1 = Math.Ceiling(c1 * 100) / 100;
subtracting two inputted numbers without rounding up or down the decimals. because the other solutions does not work for me. don't know if it will work for others, i just want to share this :) Hope it works tho for those who's finding solution to a problem similar to mine. Thanks
PS: i'm a beginner so feel free to point out something on this. :D this is good if you're actually dealing with money, cause of the cents right? it only have 2 decimal places and rounding it is a no no.
The old way:
xcopy [source] [destination] /E
xcopy is deprecated. Robocopy replaces Xcopy. It comes with Windows 8, 8.1 and 10.
robocopy [source] [destination] /E
robocopy has several advantages:
More details here.
Just to add another flavor from the Reuben response, I use it like this to add or remove this rule according to a condition:
RelativeLayout.LayoutParams layoutParams =
(RelativeLayout.LayoutParams) holder.txtGuestName.getLayoutParams();
if (SOMETHING_THAT_WOULD_LIKE_YOU_TO_CHECK) {
// if true center text:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
holder.txtGuestName.setLayoutParams(layoutParams);
} else {
// if false remove center:
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
holder.txtGuestName.setLayoutParams(layoutParams);
}
What about:
if($('.class.class2.class3').length > 0){
//...
}
print "Number of lines: $nids\n";
print "Content: $ids\n";
How did Perl complain? print $ids
should work, though you probably want a newline at the end, either explicitly with print
as above or implicitly by using say
or -l/$\.
If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}
:
print "foo${ids}bar";
In Android 8.1 it is must to turned Location on to get SSID, if not you can get connection state but not SSID
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = null;
if (wifiManager != null)
wifiInfo = wifiManager.getConnectionInfo();
String ssid = null;
if (wifiInfo != null)
ssid = wifiInfo.getSSID(); /*you will get SSID <unknown ssid> if location turned off*/
Update 2: My solution is based on disabling the browser's native scrolling altogether (when cursor is inside the DIV) and then manually scrolling the DIV with JavaScript (by setting its .scrollTop
property). An alternative and IMO better approach would be to only selectively disable the browser's scrolling in order to prevent the page scroll, but not the DIV scroll. Check out Rudie's answer below which demonstrates this solution.
Here you go:
$( '.scrollable' ).on( 'mousewheel DOMMouseScroll', function ( e ) {
var e0 = e.originalEvent,
delta = e0.wheelDelta || -e0.detail;
this.scrollTop += ( delta < 0 ? 1 : -1 ) * 30;
e.preventDefault();
});
Live demo: https://jsbin.com/howojuq/edit?js,output
So you manually set the scroll position and then just prevent the default behavior (which would be to scroll the DIV or whole web-page).
Update 1: As Chris noted in the comments below, in newer versions of jQuery, the delta information is nested within the .originalEvent
object, i.e. jQuery does not expose it in its custom Event object anymore and we have to retrieve it from the native Event object instead.
Visit https://www.tutorialspoint.com/python/string_join.htm
s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))
ab cd ef
s="."
print(s.join(seq))
ab.cd.ef
Short Extension Method:
public static TResult IfNotNull<TInput, TResult>(this TInput o, Func<TInput, TResult> evaluator)
where TResult : class where TInput : class
{
if (o == null) return null;
return evaluator(o);
}
Using
PropertyC value = ObjectA.IfNotNull(x => x.PropertyA).IfNotNull(x => x.PropertyB).IfNotNull(x => x.PropertyC);
This simple extension method and much more you can find on http://devtalk.net/csharp/chained-null-checks-and-the-maybe-monad/
EDIT:
After using it for moment I think the proper name for this method should be IfNotNull() instead of original With().
After long search I found a working solution. My database does not use the sys.foreign_key_columns and the information_schema.key_column_usage only contain primary keys.
I use SQL Server 2015
SOLUTION 1 (rarely used)
If other solutions does not work, this will work fine:
WITH CTE AS
(
SELECT
TAB.schema_id,
TAB.name,
COL.name AS COLNAME,
COl.is_identity
FROM
sys.tables TAB INNER JOIN sys.columns COL
ON TAB.object_id = COL.object_id
)
SELECT
DB_NAME() AS [Database],
SCHEMA_NAME(Child.schema_id) AS 'Schema',
Child.name AS 'ChildTable',
Child.COLNAME AS 'ChildColumn',
Parent.name AS 'ParentTable',
Parent.COLNAME AS 'ParentColumn'
FROM
cte Child INNER JOIN CTE Parent
ON
Child.COLNAME=Parent.COLNAME AND
Child.name<>Parent.name AND
Child.is_identity+1=Parent.is_identity
SOLUTION 2 (commonly used)
In most of the cases this will work just fine:
SELECT
DB_NAME() AS [Database],
SCHEMA_NAME(fk.schema_id) AS 'Schema',
fk.name 'Name',
tp.name 'ParentTable',
cp.name 'ParentColumn',
cp.column_id,
tr.name 'ChildTable',
cr.name 'ChildColumn',
cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
WHERE
-- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tp.name, '.', cp.name) LIKE '%my_table_name%' OR
-- CONCAT(SCHEMA_NAME(fk.schema_id), '.', tr.name, '.', cr.name) LIKE '%my_table_name%'
ORDER BY
tp.name, cp.column_id
As a complement to other answers note that you can also put the lang
attribute on various HTML tags inside a page.
For example to give a hint to the spellchecker that the input text should be in english:
<input ... spellcheck="true" lang="en"> ...
See: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
I love the JavaScript solution and have some updates to work with dynamic ajax loading:
$(document).on("click", "a", function () {
if (this.innerHTML.indexOf("Delete") == 0) {
return confirm("Are you sure you want to delete this record?");
}
});
Hope it help ;)
Pretty sure this solves what you're looking for:
HTML:
<table>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
<tr><td><button class="editbtn">edit</button></td></tr>
</table>
Javascript (using jQuery):
$(document).ready(function(){
$('.editbtn').click(function(){
$(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
});
});
Edit:
Apparently I should have looked at your sample code first ;)
You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.
By using classes, you can apply the same logic to multiple elements without any conflicts.
SELECT column1 FROM table WHERE ISNUMERIC(column1) = 1
Note, as Damien_The_Unbeliever has pointed out, this will include any valid numeric type.
To filter out columns containing non-digit characters (and empty strings), you could use
SELECT column1 FROM table WHERE column1 not like '%[^0-9]%' and column1 != ''
All the information is in the existing answers, but I personally wished for a concise summary, so here's an attempt at it; the commands use int
variables for brevity, but they apply analogously to any type, including string
.
To declare multiple variables and:
int i = 0, j = 1; // declare and initialize each; `var` is NOT supported as of C# 8.0
int i, j; // *declare* first (`var` is NOT supported)
i = j = 42; // then *initialize*
// Single-statement alternative that is perhaps visually less obvious:
// Initialize the first variable with the desired value, then use
// the first variable to initialize the remaining ones.
int i = 42, j = i, k = i;
What doesn't work:
You cannot use var
in the above statements, because var
only works with (a) a declaration that has an initialization value (from which the type can be inferred), and (b), as of C# 8.0, if that declaration is the only one in the statement (otherwise you'll get compilation error error CS0819: Implicitly-typed variables cannot have multiple declarators
).
Placing an initialization value only after the last variable in a multiple-declarations statement initializes the last variable only:
int i, j = 1;
// initializes *only* j