as @Jörg W Mittag pointed out: in jruby, fix num size is always 8 bytes long. This code snippet shows the truth:
fmax = ->{
if RUBY_PLATFORM == 'java'
2**63 - 1
else
2**(0.size * 8 - 2) - 1
end
}.call
p fmax.class # Fixnum
fmax = fmax + 1
p fmax.class #Bignum
this works for me:
public static class eSound_Def
{
private static Android.Media.MediaPlayer mpBeep;
public static void InitSounds( Android.Content.Res.AssetManager Assets )
{
mpBeep = new Android.Media.MediaPlayer();
InitSound_Beep( Assets );
}
private static void InitSound_Beep( Android.Content.Res.AssetManager Assets )
{
Android.Content.Res.AssetFileDescriptor AFD;
AFD = Assets.OpenFd( "Sounds/beep-06.mp3" );
mpBeep.SetDataSource( AFD.FileDescriptor, AFD.StartOffset, AFD.Length );
AFD.Close();
mpBeep.Prepare();
mpBeep.SetVolume( 1f, 1f );
mpBeep.Looping = false;
}
public static void PlaySound_Beep()
{
if (mpBeep.IsPlaying == true)
{
mpBeep.Stop();
mpBeep.Reset();
InitSound_Beep();
}
mpBeep.Start();
}
}
In main activity, on create:
protected override void OnCreate( Bundle savedInstanceState )
{
base.OnCreate( savedInstanceState );
SetContentView( Resource.Layout.lmain_activity );
...
eSound_Def.InitSounds( Assets );
...
}
how to use in code (on button click):
private void bButton_Click( object sender, EventArgs e )
{
eSound_Def.PlaySound_Beep();
}
Run CMD in admistrator mode and type this:
NUL > file_name.extention
or you type this
echo .> file_name.extention
It happened to me that the file .git/index was in use by another process (my local development web server). I shut down the process and then it worked.
To produce the same results:
MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");
AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);
byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);
letter = ["a", "b", "c", "d"]
letter.extend(["e", "f", "g", "h"])
letter.extend(("e", "f", "g", "h"))
print(letter)
...
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'e', 'f', 'g', 'h']
Initialy both dropdown have same option ,the option you select in firstdropdown is hidden in seconddropdown."value" is custom attribute which is unique.
$(".seconddropdown option" ).each(function() {
if(($(this).attr('value')==$(".firstdropdown option:selected").attr('value') )){
$(this).hide();
$(this).siblings().show();
}
});
If you ever wondered how to do it using the new BDD style of Mockito:
willThrow(new Exception()).given(mockedObject).methodReturningVoid(...));
And for future reference one may need to throw exception and then do nothing:
willThrow(new Exception()).willDoNothing().given(mockedObject).methodReturningVoid(...));
Paxdiablo's answer is absolutely correct.
To avoid writing the return value 1
twice, I would use this instead:
=IF(OR(ISBLANK(A1),TRIM(A1)=""),1,0)
based on several answers here, i found something that worked for me and i wanted to generalize and explain what's going on.
convert:
LEFT JOIN table2 t2 ON (t2.thing = t1.thing)
to:
LEFT JOIN table2 t2 ON (t2.p_key = (SELECT MIN(t2_.p_key)
FROM table2 t2_ WHERE (t2_.thing = t1.thing) LIMIT 1))
the condition that connects t1 and t2 is moved from the ON
and into the inner query WHERE
. the MIN(primary key)
or LIMIT 1
makes sure that only 1 row is returned by the inner query.
after selecting one specific row we need to tell the ON
which row it is. that's why the ON
is comparing the primary key of the joined tabled.
you can play with the inner query (i.e. order+limit) but it must return one primary key of the desired row that will tell the ON
the exact row to join.
Update - for MySQL 5.7+
another option relevant to MySQL 5.7+ is to use ANY_VALUE
+GROUP BY
. it will select an artist name that is not necessarily the first one.
SELECT feeds.*,ANY_VALUE(feeds_artists.name) artist_name
FROM feeds
LEFT JOIN feeds_artists ON feeds.id = feeds_artists.feed_id
GROUP BY feeds.id
more info about ANY_VALUE: https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html
Wrapping Richy's code I created a custom UIScrollView class that automates content resizing completely!
SBScrollView.h
@interface SBScrollView : UIScrollView
@end
SBScrollView.m:
@implementation SBScrollView
- (void) layoutSubviews
{
CGFloat scrollViewHeight = 0.0f;
self.showsHorizontalScrollIndicator = NO;
self.showsVerticalScrollIndicator = NO;
for (UIView* view in self.subviews)
{
if (!view.hidden)
{
CGFloat y = view.frame.origin.y;
CGFloat h = view.frame.size.height;
if (y + h > scrollViewHeight)
{
scrollViewHeight = h + y;
}
}
}
self.showsHorizontalScrollIndicator = YES;
self.showsVerticalScrollIndicator = YES;
[self setContentSize:(CGSizeMake(self.frame.size.width, scrollViewHeight))];
}
@end
How to use:
Simply import the .h file to your view controller and
declare a SBScrollView instance instead of the normal UIScrollView one.
How about just using:
result = [VLOOKUP(DATA!AN2, DATA!AA9:AF20, 5, FALSE)]
Note the [ and ].
try canvas measureText solution
css:
input{
min-width:10px!important;
max-width:99.99%!important;
transition: width 0.1s;
border-width:1px;
}
javascript:
function getWidthOfInput(input){
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var text = input.value.length ? input.value : input.placeholder;
var style = window.getComputedStyle(input);
ctx.lineWidth = 1;
ctx.font = style.font;
var text_width = ctx.measureText(text).width;
return text_width;
}
function resizable (el, factor) {
function resize() {
var width = getWidthOfInput(el);
el.style.width = width + 'px';
}
var e = 'keyup,keypress,focus,blur,change'.split(',');
for (var i in e){
el.addEventListener(e[i],resize,false);
}
resize();
}
$( "input" ).each( function(i){
resizable(this);
});
This is because strings are immutable in Python.
Which means that X.replace("hello","goodbye")
returns a copy of X
with replacements made. Because of that you need replace this line:
X.replace("hello", "goodbye")
with this line:
X = X.replace("hello", "goodbye")
More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace
,strip
,translate
,lower
/upper
,join
,...
You must assign their output to something if you want to use it and not throw it away, e.g.
X = X.strip(' \t')
X2 = X.translate(...)
Y = X.lower()
Z = X.upper()
A = X.join(':')
B = X.capitalize()
C = X.casefold()
and so on.
This regex will split word by space like space, tab, line break:
String[] str = s.split("\\s+");
I got this error using PHP7 / Apache 2.4 on a windows platform. curl_init
worked from CLI but not with Apache 2.4. I resolved it by adding LoadFile
directives for libeay32.dll and ssleay32.dll:
LoadFile "C:/path/to/Php7/libeay32.dll"
LoadFile "C:/path/to/Php7/ssleay32.dll"
LoadFile "C:/path/to/Php7/php7ts.dll"
LoadModule php7_module "C:/path/to/Php7/php7apache2_4.dll"
Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.
You don't need to harcode android:debuggable="false"
in your application tag. Infact for me studio complaints -
Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)
It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.
The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.
Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.
Now you should see a prompt to select release build or debug build
.
For production always select release build!
And you are done. Signed APK exported.
PS : Don't forget to increment your versionCode
in manifest file before uploading to playstore :)
This is a recursive algorithm in C++11.
#include <iostream>
#include <array>
#include <list>
std::array<std::string, 10> pm = {
"0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};
void generate_mnemonic(const std::string& numbers, size_t i, std::string& m,
std::list<std::string>& mnemonics)
{
// Base case
if (numbers.size() == i) {
mnemonics.push_back(m);
return;
}
for (char c : pm[numbers[i] - '0']) {
m[i] = c;
generate_mnemonic(numbers, i + 1, m, mnemonics);
}
}
std::list<std::string> phone_number_mnemonics(const std::string& numbers)
{
std::list<std::string> mnemonics;
std::string m(numbers.size(), 0);
generate_mnemonic(numbers, 0, m, mnemonics);
return mnemonics;
}
int main() {
std::list<std::string> result = phone_number_mnemonics("2276696");
for (const std::string& s : result) {
std::cout << s << std::endl;
}
return 0;
}
The Document is here (in Chinese)please click.
you can use
git stash list
git stash drop stash@{0}
onclick="history.go(-1)"
Simply
JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.
Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .
To stop this behaviour we need to return the function to onClick.
The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!
Use -
onClick={() => { this.props.removeTaskFunction(todo) }}
which means-
var onClick = function() {
return this.props.removeTaskFunction(todo);
}.bind(this);
this looks like PHP to me. I'll delete if it's some other language.
Simply unset($arr[1]);
If you have initialized the form like this
form = CustomForm()
then the correct way as of Jan 2019, is to use .initial
to replace the data. This will replace the data in the intial
dict that goes along with the form. It also works if you have initialized using some instance such as form = CustomForm(instance=instance)
To replace data in the form, you need to
form.initial['Email'] = GetEmailString()
Generalizing this it would be,
form.initial['field_name'] = new_value
sudo apt-get install libcurl4-openssl-dev
{{ (ability.id in company_abilities) ? 'selected' : '' }}
The ternary operator is documented under 'other operators'
<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
"dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
Component is the template(view) + a class (Typescript code) containing some logic for the view + metadata(to tell angular about from where to get data it needs to display the template)
.
Modules basically group the related components, services together
so that you can have chunks of functionality which can then run independently. For example, an app can have modules for features, for grouping components for a particular feature of your app, such as a dashboard, which you can simply grab and use inside another application.
Another useful command would be git diff-tree <hash>
where hash can be also a hash range (denoted by <old>..<new>
notation). An output example:
$ git diff-tree HEAD
:040000 040000 8e09a be406 M myfile
The fields are:
source mode, dest mode, source hash, dest hash, status, filename
Statuses are the ones you would expect: D (deleted), A (added), M (modified) etc. See man page for full description.
If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.
In Linux terminal: lscpu
In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%
In Mac terminal: sysctl -n hw.ncpu
You could use JavaScript and trigger the hidden file input when the button input has been clicked.
http://jsfiddle.net/gregorypratt/dhyzV/ - simple
http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery
Or, you could style a div directly over the file input and set pointer-events
in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events
Link statically to libstdc++ with -static-libstdc++
gcc option.
You can use a simple regular expression:
function isInt(value) {
var er = /^-?[0-9]+$/;
return er.test(value);
}
Or you can use the below functions too, according your needs. They are developed by the PHPJS Project.
is_int()
=> Check if variable type is integer and if its content is integer
is_float()
=> Check if variable type is float and if its content is float
ctype_digit()
=> Check if variable type is string and if its content has only decimal digits
Update 1
Now it checks negative numbers too, thanks for @ChrisBartley comment!
You probably want ANSI color codes. Most *nix terminals support them.
A simple way by manipulating string.
$str = stripStr($str, '<script', '</script>');
function stripStr($str, $ini, $fin)
{
while(($pos = mb_stripos($str, $ini)) !== false)
{
$aux = mb_substr($str, $pos + mb_strlen($ini));
$str = mb_substr($str, 0, $pos).mb_substr($aux, mb_stripos($aux, $fin) + mb_strlen($fin));
}
return $str;
}
Self executing function are used to manage the scope of a Variable.
The scope of a variable is the region of your program in which it is defined.
A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.
As shown below, you can access the global variables variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.
var globalvar = "globalvar"; // this var can be accessed anywhere within the script
function scope() {
alert(globalvar);
var localvar = "localvar"; //can only be accessed within the function scope
}
scope();
So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.
If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.
My favourites have always been
use constant FALSE => 1==0;
use constant TRUE => not FALSE;
which is completely independent from the internal representation.
select 'one'||'&'||'two' from dual
Traditionally daemon processes in UNIX were those that were constantly running in background, much like services in Windows.
A daemon thread in Java is one that doesn't prevent the JVM from exiting. Specifically the JVM will exit when only daemon threads remain. You create one by calling the setDaemon()
method on Thread
.
Have a read of Daemon threads.
The easiest way use screen with name
screen -S 'name' 'application'
Return to screen:
screen -r 'name'
for example using lynx with screen
Create screen:
screen -S lynx lynx
Ctrl+a, d =exit
later you can return with:
screen -r lynx
Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary
You can use the following:
return Redirect::back()->withInput(Input::all());
If you're using Form Request Validation, this is exactly how Laravel will redirect you back with errors and the given input.
Excerpt from \Illuminate\Foundation\Validation\ValidatesRequests
:
return redirect()->to($this->getRedirectUrl()) ->withInput($request->input()) ->withErrors($errors, $this->errorBag());
Imskull's answer almost worked for me, but I had to make some changes. The only real change is adding username, password, and setting rejectUnauthorized to false. I couldn't comment so I put this in an answer.
If you run the code it'll get you the titles of the current stories on Hacker News, per this tutorial: http://smalljs.org/package-managers/npm/
var cheerio = require('cheerio');
var request = require('request');
request({
'url': 'https://news.ycombinator.com/',
'proxy': 'http://Username:Password@YourProxy:Port/',
'rejectUnauthorized': false
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
if (response.body) {
var $ = cheerio.load(response.body);
$('td.title a').each(function() {
console.log($(this).text());
});
}
} else {
console.log('Error or status not equal 200.');
}
});
List<Long> actual = Arrays.asList(1L, 2L);
List<Long> expected = Arrays.asList(2L, 1L);
assertThat(actual, containsInAnyOrder(expected.toArray()));
Shorter version of @Joe's answer without redundant parameters.
I don't know probably is too late to answer to this question. But if someone is in my situation and struggling with this problem will useful.
Few antivirus programs detect adb.exe as a virus. You should take a look in the place where antivirus is putting your detected threats and restore it from there. For Avast Antivirus
is inside of virus chest
Hope it will be useful for someone !
It's just shorthand for "constructor" - and it's what the constructor is called in IL, too. For example, open up Reflector and look at a type and you'll see members called .ctor
for the various constructors.
Java 8 does bring the
Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
method, that is nullsafe by using prefix + suffix
for null values.
It can be used in the following manner:
String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))
The Collectors.joining(CharSequence delimiter)
method just calls joining(delimiter, "", "")
internally.
Two ways to position a tag in the middle of screen or its parent tag:
Set the parent tag position
to relative
(if the target tag has a parent tag) and then set the target tag style like this:
#center {
...
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
The parent tag style should looks like this:
#parent-tag {
display: flex;
align-items: center;
justify-content: center;
}
Python 3.7 is now available to be installed, but many packages have not been updated yet. As noted by another answer here, there is a GitHub issue tracking the progress of Anaconda building all the updated packages.
Until someone creates a conda package for Python 3.7, you can't install it. Unfortunately, something like 3500 packages show up in a search for "python" on Anaconda.org (https://anaconda.org/search?q=%22python%22) so I couldn't see if anyone has done that yet.
You might be able to build your own package, depending on what OS you want it for. You can start with the recipe that conda-forge uses to build Python: https://github.com/conda-forge/python-feedstock/
In the past, I think Continuum have generally waited until a stable release to push out packages for new Pythons, but I don't work there, so I don't know what their actual policy is.
I wish to complement the accepted answer and contribute to the discussion with my late answer.
@ChrisVanOpstal shared this regex tutorial which is a great resource for learning regex.
However, it was really time consuming to read through.
I made a cheatsheet for mnemonic convenience.
This reference is based on the braces []
, ()
, and {}
leading each class, and I find it easy to recall.
Regex = {
'single_character': ['[]', '.', {'negate':'^'}],
'capturing_group' : ['()', '|', '\\', 'backreferences and named group'],
'repetition' : ['{}', '*', '+', '?', 'greedy v.s. lazy'],
'anchor' : ['^', '\b', '$'],
'non_printable' : ['\n', '\t', '\r', '\f', '\v'],
'shorthand' : ['\d', '\w', '\s'],
}
You can use the function subset
inside ggplot2
. Try this
library(ggplot2)
data("iris")
iris$Sepal.Length[5:10] <- NA # create some NAs for this example
ggplot(data=subset(iris, !is.na(Sepal.Length)), aes(x=Sepal.Length)) +
geom_bar(stat="bin")
the MySQL service on local computer started and then stopped
This Error happen when you modified my.ini in C:\ProgramData\MySQL\MySQL Server 8.0\my.ini not correct.
You can search my.ini original configuration or checking yours to make sure everything is OK
2 Here a short ES6 variadic version:
function objectsHaveSameKeys(...objects) {
const allKeys = objects.reduce((keys, object) => keys.concat(Object.keys(object)), []);
const union = new Set(allKeys);
return objects.every(object => union.size === Object.keys(object).length);
}
A little performance test (MacBook Pro - 2,8 GHz Intel Core i7, Node 5.5.0):
var x = {};
var y = {};
for (var i = 0; i < 5000000; ++i) {
x[i] = i;
y[i] = i;
}
Results:
objectsHaveSameKeys(x, y) // took 4996 milliseconds
compareKeys(x, y) // took 14880 milliseconds
hasSameProps(x,y) // after 10 minutes I stopped execution
I wish I still had a link to the source that lead me in this direction, but this is the code that ended up working for me. By looking over the JavaDoc for X509TrustManager it looks like the way the TrustManager
s work is by returning nothing on successful validation, otherwise throwing an exception. Thus, with a null implementation, it is treated as a successful validation. Then you remove all other implementations.
import javax.net.ssl.*;
import java.security.*;
import java.security.cert.X509Certificate;
public final class SSLUtil{
private static final TrustManager[] UNQUESTIONING_TRUST_MANAGER = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers(){
return null;
}
public void checkClientTrusted( X509Certificate[] certs, String authType ){}
public void checkServerTrusted( X509Certificate[] certs, String authType ){}
}
};
public static void turnOffSslChecking() throws NoSuchAlgorithmException, KeyManagementException {
// Install the all-trusting trust manager
final SSLContext sc = SSLContext.getInstance("SSL");
sc.init( null, UNQUESTIONING_TRUST_MANAGER, null );
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
public static void turnOnSslChecking() throws KeyManagementException, NoSuchAlgorithmException {
// Return it to the initial state (discovered by reflection, now hardcoded)
SSLContext.getInstance("SSL").init( null, null, null );
}
private SSLUtil(){
throw new UnsupportedOperationException( "Do not instantiate libraries.");
}
}
If you are sure you are going to get at most a single element that passed the filter (which is guaranteed by your filter), you can use findFirst
:
Optional<List> o = id1.entrySet()
.stream()
.filter( e -> e.getKey() == 1)
.map(Map.Entry::getValue)
.findFirst();
In the general case, if the filter may match multiple Lists, you can collect them to a List of Lists :
List<List> list = id1.entrySet()
.stream()
.filter(.. some predicate...)
.map(Map.Entry::getValue)
.collect(Collectors.toList());
To the extent that interfaces represent "contracts", it seems quiet reasonable for static classes to implement interfaces.
The above arguments all seem to miss this point about contracts.
It's Very Easy To Install By Following Below Steps In Eclipse JUNO version
Help-->Eclipse Marketplace-->Find: beside Textbox u can type "Egit"-->select Egit-git team provider intall button-->follow next steps and finally click finish
LINQ one-line solution:
myArray = myArray.Where((source, index) => index != 1).ToArray();
The 1
in that example is the index of the element to remove -- in this example, per the original question, the 2nd element (with 1
being the second element in C# zero-based array indexing).
A more complete example:
string[] myArray = { "a", "b", "c", "d", "e" };
int indexToRemove = 1;
myArray = myArray.Where((source, index) => index != indexToRemove).ToArray();
After running that snippet, the value of myArray
will be { "a", "c", "d", "e" }
.
Read-Host
is a simple option for getting string input from a user.
$name = Read-Host 'What is your username?'
To hide passwords you can use:
$pass = Read-Host 'What is your password?' -AsSecureString
To convert the password to plain text:
[Runtime.InteropServices.Marshal]::PtrToStringAuto(
[Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))
As for the type returned by $host.UI.Prompt()
, if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member
(for example, $results | gm
). The result is a Dictionary where the key is the name of a FieldDescription
object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field']
.
To access information without invoking a method, leave the parentheses off:
PS> $Host.UI.Prompt
MemberType : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
ompt(string caption, string message, System.Collections.Ob
jectModel.Collection[System.Management.Automation.Host.Fie
ldDescription] descriptions)}
TypeNameOfValue : System.Management.Automation.PSMethod
Value : System.Collections.Generic.Dictionary[string,psobject] Pro
mpt(string caption, string message, System.Collections.Obj
ectModel.Collection[System.Management.Automation.Host.Fiel
dDescription] descriptions)
Name : Prompt
IsInstance : True
$Host.UI.Prompt.OverloadDefinitions
will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>)
.
Doesn't answer the "why" (has to be something w/ collapsing margin), but seems like the easiest/most logical way to do what you're trying to do would be to just add padding-top
to the outer div:
Minor note - it shouldn't be necessary to set a div to display:block;
unless there's something else in your code telling it not to be block.
I was having the same issue and this works excellently.
Private Sub DataGridView17_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView17.CellFormatting
'Display complete contents in tooltip even though column display cuts off part of it.
DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).ToolTipText = DataGridView17.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
End Sub
dancavallaro has it right, %*
for all command line parameters (excluding the script name itself). You might also find these useful:
%0
- the command used to call the batch file (could be foo
, ..\foo
, c:\bats\foo.bat
, etc.)
%1
is the first command line parameter,
%2
is the second command line parameter,
and so on till %9
(and SHIFT
can be used for those after the 9th).
%~nx0
- the actual name of the batch file, regardless of calling method (some-batch.bat)
%~dp0
- drive and path to the script (d:\scripts)
%~dpnx0
- is the fully qualified path name of the script (d:\scripts\some-batch.bat)
More info examples at https://www.ss64.com/nt/syntax-args.html and https://www.robvanderwoude.com/parameters.html
Note that this can happen even when the user has NOT bookmarked the site to their iOS home screen - for example, any time you open a page using Chrome for iOS, it does a GET "/apple-touch-icon-precomposed.png"
.
I've handled this and other non-HTML 404 requests in my ApplicationController as follows:
respond_to do |format|
format.html { render :template => "error_404", :layout => "errors", :status => 404 }
format.all { render :nothing => true, :status => 404 }
end
The format.all
response takes care of images such as this PNG file (which does not exist for my site).
You can use the below line. In my case it was working: System.Configuration.ConfigurationSettings.AppSettings["yourKeyName"]
You must take care that the above line of code is also the old version and it's deprecated in new libraries.
select * from tbl
where exists (select 1 from all_likes where all_likes.value = substr(tbl.my_col,0, length(tbl.my_col)))
Python 3:
import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()
Python 2:
import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()
Documentation for urllib.request
and read
.
I think the following should work. I'm not sure about win32
though.
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
# ...
elif [[ "$OSTYPE" == "darwin"* ]]; then
# Mac OSX
elif [[ "$OSTYPE" == "cygwin" ]]; then
# POSIX compatibility layer and Linux environment emulation for Windows
elif [[ "$OSTYPE" == "msys" ]]; then
# Lightweight shell and GNU utilities compiled for Windows (part of MinGW)
elif [[ "$OSTYPE" == "win32" ]]; then
# I'm not sure this can happen.
elif [[ "$OSTYPE" == "freebsd"* ]]; then
# ...
else
# Unknown.
fi
in fact, you can, but not that way.
Sub MySub( Optional Byval Counter as Long=1 , Optional Byval Events as Boolean= True)
'code...
End Sub
And you can set the variables differently when calling the sub, or let them at their default values.
Why is everybody using jQuery for something simple as this.
<body OnLoad="document.myform.mytextfield.focus();">
Import the jquery CDN as a first
(e.g)
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Here is an answer: http://www.dba-oracle.com/concepts/synonyms.htm
An Oracle synonym basically allows you to create a pointer to an object that exists somewhere else. You need Oracle synonyms because when you are logged into Oracle, it looks for all objects you are querying in your schema (account). If they are not there, it will give you an error telling you that they do not exist.
A Stacked bar chart should suffice:
Setup data as follows
Name Start End Duration (End - Start)
Fred 1/01/1981 1/06/1985 1612
Bill 1/07/1985 1/11/2000 5602
Joe 1/01/1980 1/12/2001 8005
Jim 1/03/1999 1/01/2000 306
Start
and Duration
as a stacked bar chartX-Axis minimum
to the desired start date Fill
Colour of thestart
range to no fill
Fill
of individual bars to suit(example prepared in Excel 2010)
Nothing worked for me except, I loggined using pgAdmin4 and on the Dashboard I disconnected all connections except pgAdmin4 and then was able to rename by right lick on the database and properties and typed new name.
The best way which works now on all Major Browsers is the following Script:
(function () {
var displayOnlineStatus = document.getElementById("online-status"),
isOnline = function () {
displayOnlineStatus.innerHTML = "Online";
displayOnlineStatus.className = "online";
},
isOffline = function () {
displayOnlineStatus.innerHTML = "Offline";
displayOnlineStatus.className = "offline";
};
if (window.addEventListener) {
/*
Works well in Firefox and Opera with the
Work Offline option in the File menu.
Pulling the ethernet cable doesn't seem to trigger it.
Later Google Chrome and Safari seem to trigger it well
*/
window.addEventListener("online", isOnline, false);
window.addEventListener("offline", isOffline, false);
}
else {
/*
Works in IE with the Work Offline option in the
File menu and pulling the ethernet cable
*/
document.body.ononline = isOnline;
document.body.onoffline = isOffline;
}
})();
Source: http://robertnyman.com/html5/offline/online-offline-events.html
If you are in Windows OS you can do:
install the module pywin32 by launching:
pip install pywin32
and then coding the following:
import win32com.client as com
def get_folder_size(path):
try:
fso = com.Dispatch("Scripting.FileSystemObject")
folder = fso.GetFolder(path)
size = str(round(folder.Size / 1048576))
print("Size: " + size + " MB")
except Exception as e:
print("Error --> " + str(e))
SELECT contactid, Count(*)
FROM <YOUR_TABLE> WHERE flag in ('Volunteer','Uploaded')
GROUP BY contactid
HAVING count(*)>1;
I have used the following before:
var my_form = $('#form-id');
var data = {};
$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
function() {
var name = $(this).attr('name');
var val = $(this).val();
if (!data.hasOwnProperty(name)) {
data[name] = new Array;
}
data[name].push(val);
}
);
This is just written from memory, so might contain mistakes, but this should make an object called data
that contains the values for all your inputs.
Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.
Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).
The method find will return the character position in a string. Then, if you want remove every thing from the character, do this:
mystring = "123?567"
mystring[ 0 : mystring.index("?")]
>> '123'
If you want to keep the character, add 1 to the character position.
// Try this to download any file. laravel 5.*
// you need to use facade "use Illuminate\Http\Response;"
public function getDownload()
{
//PDF file is stored under project/public/download/info.pdf
$file= public_path(). "/download/info.pdf";
return response()->download($file);
}
Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations (Wikipedia)
This feature is not possible in JS - the last defined function is taken in case of multiple declarations:
function foo(a1, a2) { return `${a1}, ${a2}` }
function foo(a1) { return `${a1}` } // replaces above `foo` declaration
foo(42, "foo") // "42"
Overloads are a compile-time construct with no impact on the JS runtime:
function foo(s: string): string // overload #1 of foo
function foo(s: string, n: number): number // overload #2 of foo
function foo(s: string, n?: number): string | number {/* ... */} // foo implementation
A duplicate implementation error is triggered, if you use above code (safer than JS). TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad.
Overloaded class method types can be used in a similar way to function overloading:
class LayerFactory {
createFeatureLayer(a1: string, a2: number): string
createFeatureLayer(a1: number, a2: boolean, a3: string): number
createFeatureLayer(a1: string | number, a2: number | boolean, a3?: string)
: number | string { /*... your implementation*/ }
}
const fact = new LayerFactory()
fact.createFeatureLayer("foo", 42) // string
fact.createFeatureLayer(3, true, "bar") // number
The vastly different overloads are possible, as the function implementation is compatible to all overload signatures - enforced by the compiler.
More infos:
Firebase Notifications doesn't have an API to send messages. Luckily it is built on top of Firebase Cloud Messaging, which has precisely such an API.
With Firebase Notifications and Cloud Messaging, you can send so-called downstream messages to devices in three ways:
You'll note that there is no way to send to all devices explicitly. You can build such functionality with each of these though, for example: by subscribing the app to a topic when it starts (e.g. /topics/all
) or by keeping a list of all device IDs, and then sending the message to all of those.
For sending to a topic you have a syntax error in your command. Topics are identified by starting with /topics/
. Since you don't have that in your code, the server interprets allDevices
as a device id. Since it is an invalid format for a device registration token, it raises an error.
From the documentation on sending messages to topics:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to": "/topics/foo-bar",
"data": {
"message": "This is a Firebase Cloud Messaging Topic Message!",
}
}
Here's a utility class I use to convert the newer java.time
classes to java.util.Date
objects and vice versa:
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class DateUtils {
public static Date asDate(LocalDate localDate) {
return Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
}
public static Date asDate(LocalDateTime localDateTime) {
return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}
public static LocalDate asLocalDate(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate();
}
public static LocalDateTime asLocalDateTime(Date date) {
return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
}
Edited based on @Oliv comment.
myDataTable.Columns.Contains("col_name")
If you are looking for other type of constraint, e.g. defaults, you should use different query (From How do I find a default constraint using INFORMATION_SCHEMA? answered by devio). Use:
SELECT * FROM sys.objects WHERE type = 'D' AND name = @name
to find a default constraint by name.
I've put together different 'IF not Exists" checks in my post "DDL 'IF not Exists" conditions to make SQL scripts re-runnable"
I know this is an old question however I've found a much neater way of doing this conversion.
Java
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics());
Kotlin
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65f, resources.displayMetrics)
mysql> SELECT '1234aaaa578' REGEXP '^[a-z]';
This was happening in my app because I was passing a list of search results in a fragment's arguments, assigning that list to a property of the fragment - which is actually a reference to the same location in memory pointed to by the fragment's arguments - then adding new items to the list, which also changed the size of the fragment's arguments. When the activity is suspended, the base fragment class tries to save the fragment's arguments in onSaveInstanceState, which crashes if the arguments are larger than 1MB. For example:
private ArrayList<SearchResult> mSearchResults;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null && getArguments().getSerializable("SearchResults") != null) {
mSearchResults = (ArrayList) getArguments().getSerializable("SearchResults");
}
}
private void onSearchResultsObtained(ArrayList<SearchResult> pSearchResults) {
// Because mSearchResults points to the same location in memory as the fragment's arguments
// this will also increase the size of the arguments!
mSearchResults.addAll(pSearchResults);
}
The easiest solution in this case was to assign a copy of the list to the fragment's property instead of assigning a reference:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (getArguments() != null && getArguments().getSerializable("SearchResults") != null) {
// Copy value of array instead of reference
mSearchResults = new ArrayList((ArrayList) getArguments().getSerializable("SearchResults"));
}
}
An even better solution would be to not pass around so much data in the arguments.
I probably never would have found this without the help of this answer and TooLargeTool.
Try this one:
Color color = new Color (10,10,10)
myPaint.setColor(color.getRGB());
It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute
. If so, you should make sure that you inherit that, and not ActionFilterAttribute
, in order to let ASP.NET MVC do more of the work for you.
Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Do whatever checking you need here
// If you want the base check as well (against users/roles) call
base.OnAuthorization(filterContext);
}
}
There is a good question with an answer with more details here on SO.
Have a look at insertAdjacentHTML
var element = document.getElementById("one");
var newElement = '<div id="two">two</div>'
element.insertAdjacentHTML( 'afterend', newElement )
// new DOM structure: <div id="one">one</div><div id="two">two</div>
position is the position relative to the element you are inserting adjacent to:
'beforebegin' Before the element itself
'afterbegin' Just inside the element, before its first child
'beforeend' Just inside the element, after its last child
'afterend' After the element itself
Right click in the project explorer on whichever module is giving errors. Go to PyDev->Remove Error Markers.
use Request.Form
to get the Data
Controller:
[HttpPost]
public ActionResult Index(int? id)
{
string jsonData= Request.Form[0]; // The data from the POST
}
I write this to try
View:
<input type="button" value="post" id="btnPost" />
<script type="text/javascript">
$(function () {
var test = {
number: 456,
name: "Ryu"
}
$("#btnPost").click(function () {
$.post('@Url.Action("Index", "Home")', JSON.stringify(test));
});
});
</script>
and write Request.Form[0]
or Request.Params[0]
in controller can get the data.
I don't write <form> tag
in view.
You need to use cp -t /home/shantanu/tosend
in order to tell it that the argument is the target directory and not a source. You can then change it to -exec ... +
in order to get cp
to copy as many files as possible at once.
This solution produces a result list, that contains all differences from both input lists. You can compare your objects by any property, in my example it is ID. The only restriction is that the lists should be of the same type:
var DifferencesList = ListA.Where(x => !ListB.Any(x1 => x1.id == x.id))
.Union(ListB.Where(x => !ListA.Any(x1 => x1.id == x.id)));
As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.
I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (
The correct version, with the space before the bracket, would be
If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
start "\\filer\repo\lab\software\myapp\setup.exe"
pause
)
There is one more option now ( January-2015 )
This is guesswork, but you may need to supply some or all of the floating point related switches for the link stage as well.
With Postgres, you may use
select * from users where active
or
select * from users where active = 't'
If you want to use integer value, you have to consider it as a string. You can't use integer value.
select * from users where active = 1 -- Does not work
select * from users where active = '1' -- Works
That would be the tempfile module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
For completeness, here's how it searches for the temporary directory, according to the documentation:
TMPDIR
environment variable.TEMP
environment variable.TMP
environment variable.Wimp$ScrapDir
environment variable.C:\TEMP
, C:\TMP
, \TEMP
, and \TMP
, in that order./tmp
, /var/tmp
, and /usr/tmp
, in that order.Imagine you are designing a programming language. You decide that Strings are enclosed in quotes ("Apple"). Then you hit your first snag: how to represent quotation marks since you've already used them ? Just out of convention you decide to use \"
to represent quotation marks. Then you have a second problem: how to represent \
? Again, out of convention you decide to use \\
instead. Thankfully, the process ends there and this is sufficient. You can also use what is called an escape sequence to represent other characters such as the carriage return (\n
).
You can also use HSL available on every good browser (http://caniuse.com/#feat=css3-colors)
function randomHsl() {
return 'hsla(' + (Math.random() * 360) + ', 100%, 50%, 1)';
}
This will give you only bright colors, you can play around with the brightness, saturation and alpha.
// es6
const randomHsl = () => `hsla(${Math.random() * 360}, 100%, 50%, 1)`
Follow these steps by the method SOAP
From the WSDL file,
create SOAP Request templates for each Request.
Then substitute the values to be passed in code.
POST this data to the service end point using DefaultHttpClient instance.
Get the response stream and finally
Parse the Response Stream using an XML Pull parser.
HTML provide only input type="time"
If you are using bootstrap then you can use timepicker.
You can get code from this URL http://jdewit.github.io/bootstrap-timepicker
May be it will help you
Here are the default settings
default-username is root
default-password is null/empty //mean nothing
default-url is localhost or 127.0.0.1 for apache and
localhost/phpmyadmin for mysql // if you are using xampp/wamp/mamp
default-port = 3306
To add a new remote, use the git remote add
command on the terminal, in the directory your repository is stored at.
The git remote set-url
command changes an existing remote repository URL.
So basicly, remote add
is to add a new one, remote set-url
is to update an existing one
In IE 5.5+, you can use the contentWindow property:
iframe.height = iframe.contentWindow.document.scrollHeight;
In Netscape 6 (assuming firefox as well), contentDocument property:
iframe.height = iframe.contentDocument.scrollHeight
You can use boost::optional
(or std::optional
for newer versions), which was developed in particular for decision of your problem:
boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
if(y[i]) { //check for null
p[i].SetPoint(Recto.Height()-x,*y[i]);
....
}
}
P.S. Do not use C-type array -> use std::array or std::vector:
std::array<int, 50> y; //not int y[50] !!!
Invariant's answer is a good resource for how everything was started and what was the state of JavaFX on embedded and mobile in beginning of 2014. But, a lot has changed since then and the users who stumble on this thread do not get the updated information.
Most of my points are related to Invariant's answer, so I would suggest to go through it first.
UPDATE
JavaFXPorts has been deprecated. Gluon Mobile now uses GraalVM underneath. There are multiple advantages of using GraalVM. Please check this blogpost from Gluon. The IDE plugins have been updated to use Gluon Client plugins which leverages GraalVM to AOT compile applications for Android/iOS.
Old answer with JavaFXPorts
Some bad news first:
Now, some good news:
If you are not the DIY kind, I would suggest to install the IDE plugin on your favourite IDE and get started.
Most of the documentation on how to get started can be found here and some of the samples can be found here.
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.
The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.
first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]
print( set( first_list + second_list ) )
$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
'method' => 'POST',
'content' => 'username=admin195&password=d123456789'
));
$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
throw new Exception("Problem with $sUrl, $php_errormsg");
}
$response = @stream_get_contents($fp);
if($response === false) {
throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}
numpy.ndarray
can contain any type of element, e.g. int
, float
, string
etc. Check the type an do a conversion if neccessary.
You can enable whitespace trimming at file save time from settings:
"files.trimTrailingWhitespace": true
setting to the User Settings document if it's not already there. This is so you aren't editing the Default Setting directly, but instead adding to it.We also added a new command to trigger this manually (Trim Trailing Whitespace from the command palette).
Windows API and Windows SDK if you want to build everything yourself (or) Windows API and Visual C Express. Get the 2008 edition. This is a full blown IDE and a remarkable piece of software by Microsoft for Windows development.
All operating systems are written in C. So, any application, console/GUI you write in C is the standard way of writing for the operating system.
So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:
>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"
#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width 1080
#define window_height 720
void drawFilledSun(){
//static float angle;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef(0, 0, -10);
int i, x, y;
double radius = 0.30;
//glColor3ub(253, 184, 19);
glColor3ub(255, 0, 0);
double twicePi = 2.0 * 3.142;
x = 0, y = 0;
glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
glVertex2f(x, y); // center of circle
for (i = 0; i <= 20; i++) {
glVertex2f (
(x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
);
}
glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
glBegin(GL_LINE_LOOP);
for (int ii = 0; ii < num_segments; ii++) {
float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle
float x = r * cosf(theta);//calculate the x component
float y = r * sinf(theta);//calculate the y component
glVertex2f(x + cx, y + cy);//output vertex
}
glEnd();
}
void main_loop_function() {
int c;
drawFilledSun();
DrawCircle(0, 0, 0.7, 100);
glutSwapBuffers();
c = getchar();
}
void GL_Setup(int width, int height) {
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glEnable(GL_DEPTH_TEST);
gluPerspective(45, (float)width / height, .1, 100);
glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
glutInit(&argc, argv);
glutInitWindowSize(window_width, window_height);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("GLUT Example!!!");
glutIdleFunc(main_loop_function);
GL_Setup(window_width, window_height);
glutMainLoop();
}
This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.
While viewWillAppear()
and viewDidDisappear()
are called when the back button is tapped, they are also called at other times. See end of answer for more on that.
Detecting the back button is better done when the VC is removed from it's parent (the NavigationController) with the help of willMoveToParentViewController(_:)
OR didMoveToParentViewController()
If parent is nil, the view controller is being popped off the navigation stack and dismissed. If parent is not nil, it is being added to the stack and presented.
// Objective-C
-(void)willMoveToParentViewController:(UIViewController *)parent {
[super willMoveToParentViewController:parent];
if (!parent){
// The back button was pressed or interactive gesture used
}
}
// Swift
override func willMove(toParent parent: UIViewController?) {
super.willMove(toParent: parent)
if parent == nil {
// The back button was pressed or interactive gesture used
}
}
Swap out willMove
for didMove
and check self.parent to do work after the view controller is dismissed.
Do note, checking the parent doesn't allow you to "pause" the transition if you need to do some sort of async save. To do that you could implement the following. Only downside here is you lose the fancy iOS styled/animated back button. Also be careful here with the interactive swipe gesture. Use the following to handle this case.
var backButton : UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Disable the swipe to make sure you get your chance to save
self.navigationController?.interactivePopGestureRecognizer.enabled = false
// Replace the default back button
self.navigationItem.setHidesBackButton(true, animated: false)
self.backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: self, action: "goBack")
self.navigationItem.leftBarButtonItem = backButton
}
// Then handle the button selection
func goBack() {
// Here we just remove the back button, you could also disabled it or better yet show an activityIndicator
self.navigationItem.leftBarButtonItem = nil
someData.saveInBackground { (success, error) -> Void in
if success {
self.navigationController?.popViewControllerAnimated(true)
// Don't forget to re-enable the interactive gesture
self.navigationController?.interactivePopGestureRecognizer.enabled = true
}
else {
self.navigationItem.leftBarButtonItem = self.backButton
// Handle the error
}
}
}
If you didn't get the viewWillAppear
viewDidDisappear
issue, Let's run through an example. Say you have three view controllers:
Lets follow the calls on the detailVC
as you go from the listVC
to settingsVC
and back to listVC
List > Detail (push detailVC) Detail.viewDidAppear
<- appear
Detail > Settings (push settingsVC) Detail.viewDidDisappear
<- disappear
And as we go back...
Settings > Detail (pop settingsVC) Detail.viewDidAppear
<- appear
Detail > List (pop detailVC) Detail.viewDidDisappear
<- disappear
Notice that viewDidDisappear
is called multiple times, not only when going back, but also when going forward. For a quick operation that may be desired, but for a more complex operation like a network call to save, it may not.
setState is asynchronous. You can see in this documentation by Reactjs
React intentionally “waits” until all components call setState() in their event handlers before starting to re-render. This boosts performance by avoiding unnecessary re-renders.
However, you might still be wondering why React doesn’t just update this.state immediately without re-rendering.
The reason is this would break the consistency between props and state, causing issues that are very hard to debug.
You can still perform functions if it is dependent on the change of the state value:
Option 1: Using callback function with setState
this.setState({
value: newValue
},()=>{
// It is an callback function.
// Here you can access the update value
console.log(this.state.value)
})
Option 2: using componentDidUpdate This function will be called whenever the state of that particular class changes.
componentDidUpdate(prevProps, prevState){
//Here you can check if value of your desired variable is same or not.
if(this.state.value !== prevState.value){
// this part will execute if your desired variable updates
}
}
Try this to get dynamic data. You can convert code for List<>
public object GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result.FirstOrDefault();
}
dynamic dogInfo=GetDogsWithBreedNames();
var name = dogInfo.GetType().GetProperty("Name").GetValue(dogInfo, null);
var breedName = dogInfo.GetType().GetProperty("BreedName").GetValue(dogInfo, null);
If you are using Bootstrap 3 and Less you could apply the responsive tables to all resolutions by updatingthe file:
tables.less
or overwriting this part:
@media (max-width: @screen-xs) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
overflow-x: scroll;
border: 1px solid @table-border-color;
// Tighten up spacing and give a background color
> .table {
margin-bottom: 0;
background-color: #fff;
// Ensure the content doesn't wrap
> thead,
> tbody,
> tfoot {
> tr {
> th,
> td {
white-space: nowrap;
}
}
}
}
// Special overrides for the bordered tables
> .table-bordered {
border: 0;
// Nuke the appropriate borders so that the parent can handle them
> thead,
> tbody,
> tfoot {
> tr {
> th:first-child,
> td:first-child {
border-left: 0;
}
> th:last-child,
> td:last-child {
border-right: 0;
}
}
> tr:last-child {
> th,
> td {
border-bottom: 0;
}
}
}
}
}
}
With:
@media (max-width: @screen-lg) {
.table-responsive {
width: 100%;
...
Note how I changed the first line @screen-XX value.
I know making all tables responsive may not sound that good, but I found it extremely useful to have this enabled up to LG on large tables (lots of columns).
Hope it helps someone.
if you are using target sdk as 23 add below code in your build.gradle
android{
useLibrary 'org.apache.http.legacy'
}
additional note here: dont try using the gradle versions of those files. they are broken (28.08.15). I tried over 5 hours to get it to work. it just doesnt. not working:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
another thing dont use:
'org.apache.httpcomponents:httpclient-android:4.3.5.1'
its referring 21 api level.
This can actually be done with only CSS, but the content inside the div must be absolutely positioned. The key is to use padding as a percentage and the box-sizing: border-box
CSS attribute:
div {_x000D_
border: 1px solid red;_x000D_
width: 40%;_x000D_
padding: 40%;_x000D_
box-sizing: border-box;_x000D_
position: relative;_x000D_
}_x000D_
p {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
}
_x000D_
<div>_x000D_
<p>Some unnecessary content.</p>_x000D_
</div>
_x000D_
Adjust percentages to your liking. Here is a JSFiddle
Actually now you can use generics in Python 3.5+. See PEP-484 and typing module documentation.
According to my practice it is not very seamless and clear especially for those who are familiar with Java Generics, but still usable.
Do you want to match a class exactly, e.g. only matching FileInputStream
instead of any subclass of FileInputStream
? If so, use getClass()
and ==
. I would typically do this in an equals
, so that an instance of X isn't deemed equal to an instance of a subclass of X - otherwise you can get into tricky symmetry problems. On the other hand, that's more usually useful for comparing that two objects are of the same class than of one specific class.
Otherwise, use instanceof
. Note that with getClass()
you will need to ensure you have a non-null reference to start with, or you'll get a NullPointerException
, whereas instanceof
will just return false
if the first operand is null.
Personally I'd say instanceof
is more idiomatic - but using either of them extensively is a design smell in most cases.
not right way
git remote set-url origin [email protected]:erhandemirciinstagram/..
right way
git remote set-url origin https://[email protected]/..
The following should work. The lambda function filter out the duplicated words.
inputs=[]
input = raw_input("Word: ").strip()
while input:
inputs.append(input)
input = raw_input("Word: ").strip()
uniques=reduce(lambda x,y: ((y in x) and x) or x+[y], inputs, [])
print 'There are', len(uniques), 'unique words'
the equivalent to the batch program would be
#include<iostream>
int main()
{
std::cout<<"Hello, World!\n";
std::cin.get();
return 0;
}
The additional line does exactly what PAUSE
does, waits for a single character input
As an example, I am using a login modal window, where the modal window is the parent, the login form is the child and the login button calls back to the modal parent's close function.
The parent modal contains the function to close the modal. This parent passes the close function to the login child component.
import { Component} from '@angular/core';
import { LoginFormComponent } from './login-form.component'
@Component({
selector: 'my-modal',
template: `<modal #modal>
<login-form (onClose)="onClose($event)" ></login-form>
</modal>`
})
export class ParentModalComponent {
modal: {...};
onClose() {
this.modal.close();
}
}
After the child login component submits the login form, it closes the parent modal using the parent's callback function
import { Component, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'login-form',
template: `<form (ngSubmit)="onSubmit()" #loginForm="ngForm">
<button type="submit">Submit</button>
</form>`
})
export class ChildLoginComponent {
@Output() onClose = new EventEmitter();
submitted = false;
onSubmit() {
this.onClose.emit();
this.submitted = true;
}
}
This error is caused by:
Y = Dataset.iloc[:,18].values
Indexing is out of bounds here most probably because there are less than 19 columns in your Dataset, so column 18 does not exist. The following code you provided doesn't use Y at all, so you can just comment out this line for now.
It's valid and very useful in some cases.
Consider the following code:
switch(poll(fds, 1, 1000000)){
default:
// here goes the normal case : some events occured
break;
case 0:
// here goes the timeout case
break;
case -1:
// some error occurred, you have to check errno
}
The point is that the above code is more readable and efficient than cascaded if
. You could put default
at the end, but it is pointless as it will focus your attention on error cases instead of normal cases (which here is the default
case).
Actually, it's not such a good example, in poll
you know how many events may occur at most. My real point is that there are cases with a defined set of input values where there are 'exceptions' and normal cases. If it's better to put exceptions or normal cases at front is a matter of choice.
In software field I think of another very usual case: recursions with some terminal values. If you can express it using a switch, default
will be the usual value that contains recursive call and distinguished elements (individual cases) the terminal values. There is usually no need to focus on terminal values.
Another reason is that the order of the cases may change the compiled code behavior, and that matters for performances. Most compilers will generate compiled assembly code in the same order as the code appears in the switch. That makes the first case very different from the others: all cases except the first one will involve a jump and that will empty processor pipelines. You may understand it like branch predictor defaulting to running the first appearing case in the switch. If a case if much more common that the others then you have very good reasons to put it as the first case.
Reading comments it's the specific reason why the original poster asked that question after reading Intel compiler Branch Loop reorganisation about code optimisation.
Then it will become some arbitration between code readability and code performance. Probably better to put a comment to explain to future reader why a case appears first.
To those who upgraded from 5.7 to 8.0 via homebrew, this error is likely caused by the upgrade not being complete. In my case, mysql.server start
got me the following error:
ERROR! The server quit without updating PID file
I then checked the log file via cat /usr/local/var/mysql/YOURS.err | tail -n 50
, and found the following:
InnoDB: Upgrade after a crash is not supported.
If you are on the same boat, first install [email protected]
via homebrew, stop the server, and then start the 8.0 system again.
brew install [email protected]
/usr/local/opt/[email protected]/bin/mysql.server start
/usr/local/opt/[email protected]/bin/mysql.server stop
Then,
mysql.server start
This would get your MySQL (8.0) working again.
If you want to use less code, you can also use the norm
in the stats
package (the 'F' stands for Forbenius, which is the Euclidean norm):
norm(matrix(x1-x2), 'F')
While this may look a bit neater, it's not faster. Indeed, a quick test on very large vectors shows little difference, though so12311's method is slightly faster. We first define:
set.seed(1234)
x1 <- rnorm(300000000)
x2 <- rnorm(300000000)
Then testing for time yields the following:
> system.time(a<-sqrt(sum((x1-x2)^2)))
user system elapsed
1.02 0.12 1.18
> system.time(b<-norm(matrix(x1-x2), 'F'))
user system elapsed
0.97 0.33 1.31
Two more options:
// Int Age to Date as string YYY-mm-dd
function age_to_date(age)
{
try {
var d = new Date();
var new_d = '';
d.setFullYear(d.getFullYear() - Math.abs(age));
new_d = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate();
return new_d;
} catch(err) {
console.log(err.message);
}
}
// Date string (YYY-mm-dd) to Int age (years old)
function date_to_age(date)
{
try {
var today = new Date();
var d = new Date(date);
var year = today.getFullYear() - d.getFullYear();
var month = today.getMonth() - d.getMonth();
var day = today.getDate() - d.getDate();
var carry = 0;
if (year < 0)
return 0;
if (month <= 0 && day <= 0)
carry -= 1;
var age = parseInt(year);
age += carry;
return Math.abs(age);
} catch(err) {
console.log(err.message);
}
}
See jquery docs example: http://api.jquery.com/jQuery.ajax/ (about 2/3 the page)
You may be looking for following code:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Same page...lower down.
You can try with this, it worked for me
WebView wb_previewSurvey=new WebView(this);
wb_previewSurvey.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//Required functionality here
return super.onJsAlert(view, url, message, result);
}
});
In this particular case, I would not store Maps into the HttpSession directly, but instead an instance of my own class, which in turn contains a Map (an implementation detail of the class). Then you can be sure that the elements in the map are of the right type.
But if you anyways want to check that the contents of the Map are of right type, you could use a code like this:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.put("b", 2);
Object obj = map;
Map<String, Integer> ok = safeCastMap(obj, String.class, Integer.class);
Map<String, String> error = safeCastMap(obj, String.class, String.class);
}
@SuppressWarnings({"unchecked"})
public static <K, V> Map<K, V> safeCastMap(Object map, Class<K> keyType, Class<V> valueType) {
checkMap(map);
checkMapContents(keyType, valueType, (Map<?, ?>) map);
return (Map<K, V>) map;
}
private static void checkMap(Object map) {
checkType(Map.class, map);
}
private static <K, V> void checkMapContents(Class<K> keyType, Class<V> valueType, Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
checkType(keyType, entry.getKey());
checkType(valueType, entry.getValue());
}
}
private static <K> void checkType(Class<K> expectedType, Object obj) {
if (!expectedType.isInstance(obj)) {
throw new IllegalArgumentException("Expected " + expectedType + " but was " + obj.getClass() + ": " + obj);
}
}
INSERT INTO Test([col1],[col2]) (
SELECT
a.Name AS [col1],
b.sub AS [col2]
FROM IdTable b
INNER JOIN Nametable a ON b.no = a.no
)
Use:
byte[] data = Base64.encode(base64str);
Encoding converts to Base64
You would need to reference commons codec from your project in order for that code to work.
For java8:
import java.util.Base64
i did it like this android:background="@color/colorAccent" i just go to folder res then click on folder values and then on colors.xml in colors.xml I just change the color of colorAccent and call it in android:background and its done
publisher: where the events happen. Publisher should specify which delegate the class is using and generate necessary arguments, pass those arguments and itself to the delegate.
subscriber: where the response happen. Subscriber should specify methods to respond to events. These methods should take the same type of arguments as the delegate. Subscriber then add this method to publisher's delegate.
Therefore, when the event happen in publisher, delegate will receive some event arguments (data, etc), but publisher has no idea what will happen with all these data. Subscribers can create methods in their own class to respond to events in publisher's class, so that subscribers can respond to publisher's events.
import { Injectable,OpaqueToken } from '@angular/core';
export const localStorage = new OpaqueToken('localStorage');
Place these lines in the top of the file, it should resolve the issue.
Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.
You can kill a detached session which is not responding within the screen session by doing the following.
Type screen -list
to identify the detached screen session.
~$ screen -list There are screens on: 20751.Melvin_Peter_V42 (Detached)
Note: 20751.Melvin_Peter_V42
is your session id.
Get attached to the detached screen session
screen -r 20751.Melvin_Peter_V42
Once connected to the session press Ctrl + A then type :quit
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).:
is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]
[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"
Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.
Works with tuples and strings, too.
My variant: stored procedure that takes table name, field names and delimiter as arguments. Inspired by post http://www.marcogoncalves.com/2011/03/mysql-split-column-string-into-rows/
delimiter $$
DROP PROCEDURE IF EXISTS split_value_into_multiple_rows $$
CREATE PROCEDURE split_value_into_multiple_rows(tablename VARCHAR(20),
id_column VARCHAR(20), value_column VARCHAR(20), delim CHAR(1))
BEGIN
DECLARE id INT DEFAULT 0;
DECLARE value VARCHAR(255);
DECLARE occurrences INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE splitted_value VARCHAR(255);
DECLARE done INT DEFAULT 0;
DECLARE cur CURSOR FOR SELECT tmp_table1.id, tmp_table1.value FROM
tmp_table1 WHERE tmp_table1.value IS NOT NULL AND tmp_table1.value != '';
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET @expr = CONCAT('CREATE TEMPORARY TABLE tmp_table1 (id INT NOT NULL, value VARCHAR(255)) ENGINE=Memory SELECT ',
id_column,' id, ', value_column,' value FROM ',tablename);
PREPARE stmt FROM @expr;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
DROP TEMPORARY TABLE IF EXISTS tmp_table2;
CREATE TEMPORARY TABLE tmp_table2 (id INT NOT NULL, value VARCHAR(255) NOT NULL) ENGINE=Memory;
OPEN cur;
read_loop: LOOP
FETCH cur INTO id, value;
IF done THEN
LEAVE read_loop;
END IF;
SET occurrences = (SELECT CHAR_LENGTH(value) -
CHAR_LENGTH(REPLACE(value, delim, '')) + 1);
SET i=1;
WHILE i <= occurrences DO
SET splitted_value = (SELECT TRIM(SUBSTRING_INDEX(
SUBSTRING_INDEX(value, delim, i), delim, -1)));
INSERT INTO tmp_table2 VALUES (id, splitted_value);
SET i = i + 1;
END WHILE;
END LOOP;
SELECT * FROM tmp_table2;
CLOSE cur;
DROP TEMPORARY TABLE tmp_table1;
END; $$
delimiter ;
Usage example (normalization):
CALL split_value_into_multiple_rows('my_contacts', 'contact_id', 'interests', ',');
CREATE TABLE interests (
interest_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
interest VARCHAR(30) NOT NULL
) SELECT DISTINCT value interest FROM tmp_table2;
CREATE TABLE contact_interest (
contact_id INT NOT NULL,
interest_id INT NOT NULL,
CONSTRAINT fk_contact_interest_my_contacts_contact_id FOREIGN KEY (contact_id) REFERENCES my_contacts (contact_id),
CONSTRAINT fk_contact_interest_interests_interest_id FOREIGN KEY (interest_id) REFERENCES interests (interest_id)
) SELECT my_contacts.contact_id, interests.interest_id
FROM my_contacts, tmp_table2, interests
WHERE my_contacts.contact_id = tmp_table2.id AND interests.interest = tmp_table2.value;
No, the String.isEmpty()
method looks as following:
public boolean isEmpty() {
return this.value.length == 0;
}
as you can see it checks the length of the string so you definitely have to check if the string is null before.
@DanDan's answer, using C++11 is:
using namespace std;
vector<int> keys;
transform(begin(map_in), end(map_in), back_inserter(keys),
[](decltype(map_in)::value_type const& pair) {
return pair.first;
});
and using C++14 (as noted by @ivan.ukr) we can replace decltype(map_in)::value_type
with auto
.
No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.
XML has only one definition for a comment:
'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
XML forbids --
in comments to maintain compatibility with SGML.
This XPath will give you all nodes that have attributes containing 'Foo' regardless of node name or attribute name:
//attribute::*[contains(., 'Foo')]/..
Of course, if you're more interested in the contents of the attribute themselves, and not necessarily their parent node, just drop the /..
//attribute::*[contains(., 'Foo')]
You'd need to create a class with CSS -
.greenclass {color:green;}
Then you could add that to elements with
$('selector').addClass("greenclass");
and remove it with -
$('selector').removeClass("greenclass");
Solution
id
is unsigned integer, auto_incrementid
columnBam, immediate 10x+ insert improvement.
The XML is invalid.
<![CDATA[
{INVALID XML}
]]>
CDATA should be wrapped around all special XML characters, as per W3C
Here is a simple function that wraps around Sunil's code so that it takes a File as a parameter. The function does not need any external libraries, but it does require Java 7.
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.bind.DatatypeConverter;
public class Checksum {
/**
* Generates an MD5 checksum as a String.
* @param file The file that is being checksummed.
* @return Hex string of the checksum value.
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static String generate(File file) throws NoSuchAlgorithmException,IOException {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(Files.readAllBytes(file.toPath()));
byte[] hash = messageDigest.digest();
return DatatypeConverter.printHexBinary(hash).toUpperCase();
}
public static void main(String argv[]) throws NoSuchAlgorithmException, IOException {
File file = new File("/Users/foo.bar/Documents/file.jar");
String hex = Checksum.generate(file);
System.out.printf("hex=%s\n", hex);
}
}
Example output:
hex=B117DD0C3CBBD009AC4EF65B6D75C97B
take look at this example
class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
}
class Pet
{
public string Name { get; set; }
public Person Owner { get; set; }
}
public static void LeftOuterJoinExample()
{
Person magnus = new Person {ID = 1, FirstName = "Magnus", LastName = "Hedlund"};
Person terry = new Person {ID = 2, FirstName = "Terry", LastName = "Adams"};
Person charlotte = new Person {ID = 3, FirstName = "Charlotte", LastName = "Weiss"};
Person arlene = new Person {ID = 4, FirstName = "Arlene", LastName = "Huff"};
Pet barley = new Pet {Name = "Barley", Owner = terry};
Pet boots = new Pet {Name = "Boots", Owner = terry};
Pet whiskers = new Pet {Name = "Whiskers", Owner = charlotte};
Pet bluemoon = new Pet {Name = "Blue Moon", Owner = terry};
Pet daisy = new Pet {Name = "Daisy", Owner = magnus};
// Create two lists.
List<Person> people = new List<Person> {magnus, terry, charlotte, arlene};
List<Pet> pets = new List<Pet> {barley, boots, whiskers, bluemoon, daisy};
var query = from person in people
where person.ID == 4
join pet in pets on person equals pet.Owner into personpets
from petOrNull in personpets.DefaultIfEmpty()
select new { Person=person, Pet = petOrNull};
foreach (var v in query )
{
Console.WriteLine("{0,-15}{1}", v.Person.FirstName + ":", (v.Pet == null ? "Does not Exist" : v.Pet.Name));
}
}
// This code produces the following output:
//
// Magnus: Daisy
// Terry: Barley
// Terry: Boots
// Terry: Blue Moon
// Charlotte: Whiskers
// Arlene:
now you are able to include elements from the left
even if that element has no matches in the right
, in our case we retrived Arlene
even he has no matching in the right
here is the reference
The query execution happens on all get methods like
$this->db->get('table_name');
$this->db->get_where('table_name',$array);
While last_query contains the last query which was run
$this->db->last_query();
If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now you can write query and get it in a variable
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
Now reset query so if you want to write another query the object will be cleared.
$this->db->_reset_select();
And the thing is done. Cheers!!! Note : While using this way you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
In the connection properties window I changed my selection from "SID" to "Service Name", and copied my SID into the Service Name field. No idea why this change happened or why it worked, but it got me back on Oracle.
On iOS 7, if you want to use UIViewControllerBasedStatusBarAppearance == YES, and your root view controller is UINavigationController, you should subclass it and overload childViewControllerForStatusBarStyle, for example, like this:
- (UIViewController*) childViewControllerForStatusBarStyle
{
return self.viewControllers.lastObject;
}
After this, preferredStatusBarStyle will be called on pushed view controllers.
Many of the solutions have focused on complicating things.
Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.
If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.
This ensures you are maintaining shared state / context without reloading your entire app as is done with
import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)
// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
{link.label}
</NavLink>
// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
Button without using withRouter
</NavLink>
Spring has built-in support for this with an AbstractRequestLoggingFilter
:
@Bean
public Filter loggingFilter(){
final AbstractRequestLoggingFilter filter = new AbstractRequestLoggingFilter() {
@Override
protected void beforeRequest(final HttpServletRequest request, final String message) {
}
@Override
protected void afterRequest(final HttpServletRequest request, final String message) {
}
};
filter.setIncludePayload(true);
filter.setIncludeQueryString(false);
filter.setMaxPayloadLength(1000000);
return filter;
}
Unfortunately you still won't be able to read the payload directly off the request, but the String message parameter will include the payload so you can grab it from there as follows:
String body = message.substring(message.indexOf("{"), message.lastIndexOf("]"));
Don't checksum the entire file, create checksums every 100mb or so, so each file has a collection of checksums.
Then when comparing checksums, you can stop comparing after the first different checksum, getting out early, and saving you from processing the entire file.
It'll still take the full time for identical files.
Unique, as requested, (but not sorted);
uses fewer system resources for less than ~70 elements (as tested with time);
written to take input from stdin,
(or modify and include in another script):
(Bash)
bag2set () {
# Reduce a_bag to a_set.
local -i i j n=${#a_bag[@]}
for ((i=0; i < n; i++)); do
if [[ -n ${a_bag[i]} ]]; then
a_set[i]=${a_bag[i]}
a_bag[i]=$'\0'
for ((j=i+1; j < n; j++)); do
[[ ${a_set[i]} == ${a_bag[j]} ]] && a_bag[j]=$'\0'
done
fi
done
}
declare -a a_bag=() a_set=()
stdin="$(</dev/stdin)"
declare -i i=0
for e in $stdin; do
a_bag[i]=$e
i=$i+1
done
bag2set
echo "${a_set[@]}"
head -10 log.txt | grep -A 2 -B 2 pattern_to_search
-A 2
: print two lines before the pattern.
-B 2
: print two lines after the pattern.
head -10 log.txt # read the first 10 lines of the file.
in Spring Boot you can get the full request/response by setting this in properties (or other 12 factor method)
logging.level.org.apache.http=DEBUG
this outputs
-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connecting to localhost/127.0.0.1:41827
-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connection established 127.0.0.1:39546<->127.0.0.1:41827
-DEBUG o.a.http.impl.execchain.MainClientExec : Executing request POST /v0/users HTTP/1.1
-DEBUG o.a.http.impl.execchain.MainClientExec : Target auth state: UNCHALLENGED
-DEBUG o.a.http.impl.execchain.MainClientExec : Proxy auth state: UNCHALLENGED
-DEBUG org.apache.http.headers : http-outgoing-0 >> POST /v0/users HTTP/1.1
-DEBUG org.apache.http.headers : http-outgoing-0 >> Content-Type: application/json;charset=UTF-8
-DEBUG org.apache.http.headers : http-outgoing-0 >> Content-Length: 56
-DEBUG org.apache.http.headers : http-outgoing-0 >> Host: localhost:41827
-DEBUG org.apache.http.headers : http-outgoing-0 >> Connection: Keep-Alive
-DEBUG org.apache.http.headers : http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)
-DEBUG org.apache.http.headers : http-outgoing-0 >> Accept-Encoding: gzip,deflate
-DEBUG org.apache.http.wire : http-outgoing-0 >> "POST /v0/users HTTP/1.1[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Content-Type: application/json;charset=UTF-8[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Content-Length: 56[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Host: localhost:41827[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "{"id":null,"email":"[email protected]","new":true}"
and response
-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connecting to localhost/127.0.0.1:41827
-DEBUG .i.c.DefaultHttpClientConnectionOperator : Connection established 127.0.0.1:39546<->127.0.0.1:41827
-DEBUG o.a.http.impl.execchain.MainClientExec : Executing request POST /v0/users HTTP/1.1
-DEBUG o.a.http.impl.execchain.MainClientExec : Target auth state: UNCHALLENGED
-DEBUG o.a.http.impl.execchain.MainClientExec : Proxy auth state: UNCHALLENGED
-DEBUG org.apache.http.headers : http-outgoing-0 >> POST /v0/users HTTP/1.1
-DEBUG org.apache.http.headers : http-outgoing-0 >> Content-Type: application/json;charset=UTF-8
-DEBUG org.apache.http.headers : http-outgoing-0 >> Content-Length: 56
-DEBUG org.apache.http.headers : http-outgoing-0 >> Host: localhost:41827
-DEBUG org.apache.http.headers : http-outgoing-0 >> Connection: Keep-Alive
-DEBUG org.apache.http.headers : http-outgoing-0 >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)
-DEBUG org.apache.http.headers : http-outgoing-0 >> Accept-Encoding: gzip,deflate
-DEBUG org.apache.http.wire : http-outgoing-0 >> "POST /v0/users HTTP/1.1[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Content-Type: application/json;charset=UTF-8[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Content-Length: 56[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Host: localhost:41827[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Connection: Keep-Alive[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_102)[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "Accept-Encoding: gzip,deflate[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "[\r][\n]"
-DEBUG org.apache.http.wire : http-outgoing-0 >> "{"id":null,"email":"[email protected]","new":true}"
or just logging.level.org.apache.http.wire=DEBUG
which seems to contain all of the relevant information
Just to share what @jnewton mentioned. I started an nginx and an embedded tomcat process on my mac. I can see both process runninng at 8080.
LT<XXXX>-MAC:~ b0<XXX>$ sudo netstat -anp tcp | grep LISTEN
tcp46 0 0 *.8080 *.* LISTEN
tcp4 0 0 *.8080 *.* LISTEN
I think Scapy is what are you looking for.
http://www.secdev.org/projects/scapy/
you can build and send frames (packets) with it
Using String.prototype.replace
with regex, as mentioned in the other answers, is certainly the best solution.
But, just for fun, you can also remove all whitespaces from a text by using String.prototype.split
and String.prototype.join
:
const text = ' a b c d e f g ';_x000D_
const newText = text.split(/\s/).join('');_x000D_
_x000D_
console.log(newText); // prints abcdefg
_x000D_
Two UE Boom Bluetooth speakers can form a stereo, which means the phone can stream simultaneously to two Bluetooth devices. The reason is Bluetooth 4.0 can support up to two synchronous connection oriented (SCO) links on the same piconet, and A2DP is based on SCO link.
Your demand "bluetooth chat" is based on SPP profile, and SPP is based on RFCOMM protocol. Luckily even Bluetooth 2.1 can support multiple RFCOMM channels, so yes, you can have multiple bluetooth connection to chat with each other.
you can use the following code:
if(Platform.Equals("WinCE"))
{
m_CurrentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
}
else if(Platform.Equals("Win32NT"))
{
m_CurrentPath = Directory.GetCurrentDirectory();
}
more information see: Get Current Directory Path in both WinXP and WinCE with C#
If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.
Refer to the ".Source" of the image in the binding statement.
XAML
<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>
View Model Field
private Image _imageOpenClose;
public Image ImageOpenClose
{
get
{
return _imageOpenClose;
}
set
{
_imageOpenClose = value;
OnPropertyChanged();
}
}
As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though
If you want to send a text to specific device when multiple devices connected. First look for the attached devices using adb devices
adb devices
List of devices attached
3004e25a57192200 device
31002d9e592b7300 device
then get your specific device id and try the following
adb -s 31002d9e592b7300 shell input text 'your text'
:unchecked
is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.
In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked)
, it's safe to assume that there is no corresponding :unchecked
pseudo. Browser support for :not()
and :checked
is identical, so that shouldn't be a problem.
This may seem inconsistent with the :enabled
and :disabled
states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.
(:indeterminate
does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)
Install the CSS Usage add-on for Firebug and run it on that page. It will tell you which styles are being used and not used by that page.
def revstr(a):
b=''
if len(a)%2==0:
for i in range(0,len(a),2):
b += a[i + 1] + a[i]
a=b
else:
c=a[-1]
for i in range(0,len(a)-1,2):
b += a[i + 1] + a[i]
b=b+a[-1]
a=b
return b
a=raw_input('enter a string')
n=revstr(a)
print n
Use grep or grepl to find observations with white spaces and sub to get rid of them.
names<-c("Ganga Din\t", "Shyam Lal", "Bulbul ")
grep("[[:space:]]+$", names)
[1] 1 3
grepl("[[:space:]]+$", names)
[1] TRUE FALSE TRUE
sub("[[:space:]]+$", "", names)
[1] "Ganga Din" "Shyam Lal" "Bulbul"
Variable scope in Ruby is controlled by sigils to some degree. Variables starting with $
are global, variables with @
are instance variables, @@
means class variables, and names starting with a capital letter are constants. All other variables are locals. When you open a class or method, that's a new scope, and locals available in the previous scope aren't available.
I generally prefer to avoid creating global variables. There are two techniques that generally achieve the same purpose that I consider cleaner:
Create a constant in a module. So in this case, you would put all the classes that need the offset in the module Foo
and create a constant Offset
, so then all the classes could access Foo::Offset
.
Define a method to access the value. You can define the method globally, but again, I think it's better to encapsulate it in a module or class. This way the data is available where you need it and you can even alter it if you need to, but the structure of your program and the ownership of the data will be clearer. This is more in line with OO design principles.
I have at least one situation where the data is not automatically cleaned up, which would eventually lead to "Out of Memory" errors. In a UserForm I had:
Public mainPicture As StdPicture
...
mainPicture = LoadPicture(PAGE_FILE)
When UserForm was destroyed (after Unload Me
) the memory allocated for the data loaded in the mainPicture
was not being de-allocated. I had to add an explicit
mainPicture = Nothing
in the terminate event.
You can pass thru outside the dynamic statement using User-Defined Variables
Server version: 5.6.25-log MySQL Community Server (GPL)
mysql> PREPARE stmt FROM 'select "AAAA" into @a';
Query OK, 0 rows affected (0.01 sec)
Statement prepared
mysql> EXECUTE stmt;
Query OK, 1 row affected (0.01 sec)
DEALLOCATE prepare stmt;
Query OK, 0 rows affected (0.01 sec)
mysql> select @a;
+------+
| @a |
+------+
|AAAA |
+------+
1 row in set (0.01 sec)
There are many other ways to accomplish this, I would do something like this.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textRight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="30dp"
android:text="YOUR TEXT ON THE RIGHT"
android:textSize="16sp"
android:textStyle="italic" />
<TextView
android:id="@+id/textLeft"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginTop="30dp"
android:text="YOUR TEXT ON THE LEFT"
android:textSize="16sp" />
</RelativeLayout>
You can use
Trace.WriteLine("text");
This will output to the "Output" window in Visual Studio (when debugging).
make sure to have the Diagnostics assembly included:
using System.Diagnostics;
You want the path.join() function from os.path.
>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'
This builds your path with os.sep (instead of the less portable '/'
) and does it more efficiently (in general) than using +
.
However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:
start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
os.makedirs (final_path)
I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket>
connection settings.
I set the headers object on my client-side script with the following options:
/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
method: 'OPTIONS',
credentials: "include",
body: JSON.stringify(data),
cors: 'cors',
headers: head, //could be object literal too
cache: 'default'
})
.then(response=>{
....
}).catch(err=>{...});
And on my express server I setup my router as follows:
router.head('absolute or regex', (request, response, next)=>{
req.setTimeout(1000*60*5, ()=>{
console.info("socket timed out");
});
console.info("Proceeding down the middleware chain link...\n\n");
next();
});
/*Keep the socket alive by enabling it on the server, with an optional
delay on the last packet sent
*/
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))
WARNING
Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.
I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.
Your issue is not really with Angular, but with Array methods. The proper way to remove a particularly item from an array is with Array.splice
. Also, when using ng-repeat, you have access to the special $index
property, which is the current index of the array you passed in.
The solution is actually pretty straightforward:
View:
<a ng-click="delete($index)">Delete</a>
Controller:
$scope.delete = function ( idx ) {
var person_to_delete = $scope.persons[idx];
API.DeletePerson({ id: person_to_delete.id }, function (success) {
$scope.persons.splice(idx, 1);
});
};
You can create with javascript some css-rules
, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/
var addRule = (function (sheet) {
if(!sheet) return;
return function (selector, styles) {
if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
if (sheet.addRule) return sheet.addRule(selector, styles);
}
}(document.styleSheets[document.styleSheets.length - 1]));
var i = 101;
while (i--) {
addRule("[data-width='" + i + "%']", "width:" + i + "%");
}
This creates 100 pseudo-selectors like this:
[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }
Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.
This generates random ids:
CREATE TABLE Persons (
ID Integer PRIMARY KEY AUTOINCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);
I worked on Access Denied for User 'root'@'localhost' (using password: YES) for several hours, I have found following solution,
The answer to this problem was that in the my.cnf located within
/etc/mysql/my.cnf
the line was either
bind-address = 127.0.0.1
(or)
bind-address = localhost
(or)
bind-address = 0.0.0.0
I should prefer that 127.0.0.1
I should also prefer 0.0.0.0, it is more flexible
because which will allow all connections
If you use the static method and load the properties file from the classpath folder so you can use the below code :
//load a properties file from class path, inside static method
Properties prop = new Properties();
prop.load(Classname.class.getClassLoader().getResourceAsStream("foo.properties"));
You need to download the java-openjfx package from the official Arch Linux repos. (Also, make sure you have the openjdk8-openjdk package). After doing that, open your project in Intellij and go to Project-Structure -> SDKs -> 1.8 -> Classpath and try removing the old JDK you had and clicking on the directory for the new JDK that will now contain jfxrt.jar.
In CodeIgniter 3.0-dev (get it from github) this is not working because the CI is search as first letter uppercase.
You can find the code on system/core/Loader.php line 282 or bellow:
$model = ucfirst(strtolower($model));
foreach ($this->_ci_model_paths as $mod_path)
{
if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
{
continue;
}
require_once($mod_path.'models/'.$path.$model.'.php');
$CI->$name = new $model();
$this->_ci_models[] = $name;
return $this;
}
This mean that we need to create the file with the following name on application/models/Logon_mode.php
As the question is Chrome-specific, you can get the Postman extension which allows you to set the request content type.
Use below one,
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
s = "eFdss"
s = list(s)
all(i.islower() for i in s ) # FALSE
any(i.islower() for i in s ) # TRUE
I had the very same issue. The answer is that you are doing it right already. It is the problem of MS Excel. Try opening the file with another editor and you will notice that your encoding was successful already. To make MS Excel happy, move from UTF-8 to UTF-16. This should work:
class UnicodeWriter:
def __init__(self, f, dialect=csv.excel_tab, encoding="utf-16", **kwds):
# Redirect output to a queue
self.queue = StringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
# Force BOM
if encoding=="utf-16":
import codecs
f.write(codecs.BOM_UTF16)
self.encoding = encoding
def writerow(self, row):
# Modified from original: now using unicode(s) to deal with e.g. ints
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = data.encode(self.encoding)
# strip BOM
if self.encoding == "utf-16":
data = data[2:]
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
If you don't want to use a separate JS library to create a custom control for that, you could use two confirm
dialogs to do the checks:
if (confirm("Are you sure you want to quit?") ) {
if (confirm("Save your work before leaving?") ) {
// code here for save then leave (Yes)
} else {
//code here for no save but leave (No)
}
} else {
//code here for don't leave (Cancel)
}
Create a foreign key to the existing SQLLite table:
There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.
CREATE TABLE STUDENTS (
STUDENT_ID INT NOT NULL,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
CITY VARCHAR(50) DEFAULT NULL,
BADGE_NO INT DEFAULT NULL
PRIMARY KEY(STUDENT_ID)
);
Insert data into STUDENTS table.
Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table
BEGIN;
CREATE TABLE STUDENTS_new (
STUDENT_ID INT NOT NULL,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
CITY VARCHAR(50) DEFAULT NULL,
BADGE_NO INT DEFAULT NULL,
PRIMARY KEY(STUDENT_ID) ,
FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)
);
INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
DROP TABLE STUDENTS;
ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
COMMIT;
we can add the foreign key from any other table as well.