Just use a bytearray
(Python 2.6 and later) which represents a mutable sequence of bytes
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
Indexing get and sets the individual bytes
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00\x08\x00')
and if you need it as a str
(or bytes
in Python 3), it's as simple as
>>> bytes(key)
'\x13\xff\x00\x00\x08\x00'
Requests natively supports basic auth only with user-pass params, not with tokens.
You could, if you wanted, add the following class to have requests support token based basic authentication:
import requests
from base64 import b64encode
class BasicAuthToken(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
r.headers['Authorization'] = authstr
return r
Then, to use it run the following request :
r = requests.get(url, auth=BasicAuthToken(api_token))
An alternative would be to formulate a custom header instead, just as was suggested by other users here.
setSize()
or setBounds()
can be used when no layout manager is being used.
However, if you are using a layout manager you can provide hints to the layout manager using the setXXXSize()
methods like setPreferredSize()
and setMinimumSize()
etc.
And be sure that the component's container uses a layout manager that respects the requested size. The FlowLayout
, GridBagLayout
, and SpringLayout
managers use the component's preferred size (the latter two depending on the constraints you set), but BorderLayout
and GridLayout
usually don't.If you specify new size hints for a component that's already visible, you need to invoke the revalidate method on it to make sure that its containment hierarchy is laid out again. Then invoke the repaint method.
You should look at the specialisations of the numeric_limits<> template for a given type. Its in the header.
reload the app and the cause of this error is the changes of files location made in react-native dependency which other libraries like native-base point to.
To solve it you need to view the mentioned file and change the file location to the correct location.
Yes, there are a number of ways that you can do this. The "fastest" way would be to add CSS to the div similar to the following
#term-defs {
height: 300px;
overflow: scroll; }
This will force the div to be scrollable, but this might not get the best effect. Another route would be to absolute fix the position of the items at the top, you can play with this by doing something like this.
#top {
position: fixed;
top: 0;
left: 0;
z-index: 999;
width: 100%;
height: 23px;
}
This will fix it to the top, on top of other content with a height of 23px.
The final implementation will depend on what effect you really want.
I have a similar table styled like so:
<table style="width:100%; table-layout:fixed">
<tr>
<td style="width: 150px">Hello, World!</td>
<td>
<div>
<pre style="margin:0; overflow:scroll">My preformatted content</pre>
</div>
</td>
</tr>
</table>
I agree with @Lukasz Rzanek that we can use git plugin
But, I use option: checkout to a sub-direction what is enable as follow:
In Source Code Management, tick Git
click add button, choose checkout to a sub-directory
what version of sonar are you using? There is one option called "sonar.skippedModules=yourmodulename".
This will skip the whole module. So be aware of it.
var x = 2;
x % 2 ? oddFunction() : evenFunction();
SELECT train, dest, time FROM (
SELECT train, dest, time,
RANK() OVER (PARTITION BY train ORDER BY time DESC) dest_rank
FROM traintable
) where dest_rank = 1
<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
<TR style="vertical-align:top">
<TD>
<!-- The log text-box -->
<div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
Log:
</div>
</TD>
<TD>
<!-- The 2nd column -->
</TD>
<TD>
<!-- The 3rd column -->
</TD>
</TR>
</TABLE>
Deprecated in general means "don't use it".
A deprecated function may or may not work, but it is not guaranteed to work.
Using pathlib
(added in Python 3.4 or a backport available on PyPI):
from pathlib import Path
file = Path() / 'doc.txt' # or Path('./doc.txt')
size = file.stat().st_size
This is really only an interface around os.stat
, but using pathlib
provides an easy way to access other file related operations.
Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.
Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.
This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.
Well those Data Annotations should do the trick, maybe is something related with the PostgreSQL Provider.
From EF Core documentation:
Depending on the database provider being used, values may be generated client side by EF or in the database. If the value is generated by the database, then EF may assign a temporary value when you add the entity to the context. This temporary value will then be replaced by the database generated value during
SaveChanges
.
You could also try with this Fluent Api configuration:
modelBuilder.Entity<Foo>()
.Property(f => f.Id)
.ValueGeneratedOnAdd();
But as I said earlier, I think this is something related with the DB provider. Try to add a new row to your DB and check later if was generated a value to the Id
column.
You can just forgo the quotes for alphanumeric attributes:
echo "<font color=red> XHTML is not a thing anymore. </font>";
echo "<div class=editorial-note> There, I said it. </div>";
Is perfectly valid in HTML, and though still shunned, absolutely en vogue since HTML5.
CAVEATS
htmlspecialchars
or some whitelisting).<font>
specifically is somewhat outdated however.Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so
<project>
...
<dependencies>
<dependency>
<groupId>yourgroup</groupId>
<artifactId>myejbproject</artifactId>
<version>2.0</version>
<scope>system</scope>
<systemPath>path/to/myejbproject.jar</systemPath>
</dependency>
</dependencies>
...
</project>
That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.
If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:
parent
|- pom.xml
|- MyEJBProject
| `- pom.xml
`- MyWarProject
`- pom.xml
The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)
<project>
...
<artifactId>myparentproject</artifactId>
<groupId>...</groupId>
<version>...</version>
<packaging>pom</packaging>
...
<modules>
<module>MyEJBModule</module>
<module>MyWarModule</module>
</modules>
...
</project>
That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects
Finally, if your projects are not in related directories, you might try to give them as relative modules:
filesystem
|- mywarproject
| `pom.xml
|- myejbproject
| `pom.xml
`- parent
`pom.xml
now you could just do this (worked in maven 2, just tried it):
<!--parent-->
<project>
<modules>
<module>../mywarproject</module>
<module>../myejbproject</module>
</modules>
</project>
This occurs when any other flutter command is running in background. To solve this you can run for mac
killall -9 dart
and for windows open task manager. Then in processes tab, search for dart process and kill all of them. Hope this helps you.
Here is an input box with a search icon on the right.
<div class="input-group">
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
<div class="input-group-append">
<div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
</div>
</div>
Here is an input box with a search icon on the left.
<div class="input-group">
<div class="input-group-prepend">
<div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
</div>
<input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
</div>
You didn't specified what JAXB-IMPL version are you using, but once I had the same problem (with jaxb-impl 2.0.5) and solved it using the annotation at the getter level instead of using it at the member level.
you have workaround by setting background color instead of this missing icon. Here are the steps to follow:
That will probably work
You can define attributes for your properties.
[StringLength(100)]
public string Body { get; set; }
This is known as System.ComponentModel.DataAnnotations
.
If you can't find the ValidationAttribute
that you need you can allways define custom attributes.
Best Regards, Carlos
>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')
/* https://ideone.com/saBPIe */
function search($search, $string) {
$pos = strpos($string, $search);
if ($pos === false) {
return "not found";
} else {
return "found in " . $pos;
}
}
echo search("world", "hello world");
Embed PHP online:
body, html, iframe { _x000D_
width: 100% ;_x000D_
height: 100% ;_x000D_
overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/saBPIe" ></iframe>
_x000D_
list.clear() is documented for clearing the ArrayList.
list.removeAll() has no documentation at all in Eclipse.
Since this was asked there were a bit of new developments: it is important to know that std::isnan()
is part of C++11
Defined in header <cmath>
bool isnan( float arg ); (since C++11)
bool isnan( double arg ); (since C++11)
bool isnan( long double arg ); (since C++11)
Determines if the given floating point number arg is not-a-number (NaN
).
Parameters
arg
: floating point value
Return value
true
if arg is NaN
, false
otherwise
Reference
http://en.cppreference.com/w/cpp/numeric/math/isnan
Please note that this is incompatible with -fast-math if you use g++, see below for other suggestions.
For C99, in C, this is implemented as a macro isnan(c)
that returns an int value. The type of x
shall be float, double or long double.
Various vendors may or may not include or not a function isnan()
.
The supposedly portable way to check for NaN
is to use the IEEE 754 property that NaN
is not equal to itself: i.e. x == x
will be false for x
being NaN
.
However the last option may not work with every compiler and some settings (particularly optimisation settings), so in last resort, you can always check the bit pattern ...
Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:
If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"
The only time I've wanted to do this is for code golf, and then I've just copied my code out of the file and pasted it into an echo -n 'content'>file
statement.
$eval
and $parse
don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.
Q: What exactly is $eval doing? Why does it need its own mini parsing language?
From the docs:
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.
It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).
Q: Why isn't plain old javascript "eval" being used?
Because it's not actually evaluating JavaScript. As the docs say:
If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
The docs linked to above have a lot more information.
Another good library for managing multiple versions of Node is N: https://github.com/visionmedia/n
After a lot of time and getting help from a friend who knows a lot more than me about android: app/build.gradle
android {
compileSdkVersion 27
// org.gradle.caching = true
defaultConfig {
applicationId "com.cryptoviewer"
minSdkVersion 16
targetSdkVersion 23
versionCode 196
versionName "16.83"
// ndk {
// abiFilters "armeabi-v7a", "x86"
// }
}
and dependencies
dependencies {
implementation project(':react-native-camera')
//...
implementation "com.android.support:appcompat-v7:26.1.0" // <= YOU CARE ABOUT THIS
implementation "com.facebook.react:react-native:+" // From node_modules
}
in build.gradle
allprojects {
//...
configurations.all {
resolutionStrategy.force "com.android.support:support-v4:26.1.0"
}
in gradle.properties
android.useDeprecatedNdk=true
android.enableAapt2=false
org.gradle.jvmargs=-Xmx4608M
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
The delete with the cascade option only applied to tables with foreign keys defined. If you do a delete, and it says you cannot because it would violate the foreign key constraint, the cascade will cause it to delete the offending rows.
If you want to delete associated rows in this way, you will need to define the foreign keys first. Also, remember that unless you explicitly instruct it to begin a transaction, or you change the defaults, it will do an auto-commit, which could be very time consuming to clean up.
Check Safari developer reference on Touch class.
According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX
and not PageX
It's the end statement for the alternative syntax:
foreach ($foo as $bar) :
...
endforeach;
Useful to make code more readable if you're breaking out of PHP:
<?php foreach ($foo as $bar) : ?>
<div ...>
...
</div>
<?php endforeach; ?>
The following will create a simple stored procedure that uses a cursor to kill all processes one by one except for the process currently being used:
DROP PROCEDURE IF EXISTS kill_other_processes;
DELIMITER $$
CREATE PROCEDURE kill_other_processes()
BEGIN
DECLARE finished INT DEFAULT 0;
DECLARE proc_id INT;
DECLARE proc_id_cursor CURSOR FOR SELECT id FROM information_schema.processlist;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
OPEN proc_id_cursor;
proc_id_cursor_loop: LOOP
FETCH proc_id_cursor INTO proc_id;
IF finished = 1 THEN
LEAVE proc_id_cursor_loop;
END IF;
IF proc_id <> CONNECTION_ID() THEN
KILL proc_id;
END IF;
END LOOP proc_id_cursor_loop;
CLOSE proc_id_cursor;
END$$
DELIMITER ;
It can be run with SELECT
s to show the processes before and after as follows:
SELECT * FROM information_schema.processlist;
CALL kill_other_processes();
SELECT * FROM information_schema.processlist;
Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.
Contacts is here for example.
Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.
To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.
And others:
Once upon a time there was Unix and in this good old Unix there was lots of overhead for processes, so what some clever people did was to create threads, which would share the same address space with the parent process and they only needed a reduced context switch, which would make the context switch more efficient.
In a contemporary Linux (2.6.x) there is not much difference in performance between a context switch of a process compared to a thread (only the MMU stuff is additional for the thread). There is the issue with the shared address space, which means that a faulty pointer in a thread can corrupt memory of the parent process or another thread within the same address space.
A process is protected by the MMU, so a faulty pointer will just cause a signal 11 and no corruption.
I would in general use processes (not much context switch overhead in Linux, but memory protection due to MMU), but pthreads if I would need a real-time scheduler class, which is a different cup of tea all together.
Why do you think threads are have such a big performance gain on Linux? Do you have any data for this, or is it just a myth?
i have this error using datatables.net
i fixed changing the default ajax Get to POST in te properties of the DataTable()
"ajax": {
"url": "../ControllerName/MethodJson",
"type": "POST"
},
Make your audioSounds
and minTime
variables as static variables, as you are using them in a static method (playSound
).
Marking a method as static
prevents the usage of non-static (instance) members in that method.
To understand more , please read this SO QA:
You might need to uninstall antivirus (in my case I had to get rid of Avast).
This makes sure that crypto::cng
command will work. Otherwise it was giving me errors:
mimikatz $ crypto::cng
ERROR kull_m_patch_genericProcessOrServiceFromBuild ; OpenProcess (0x00000005)
After removing Avast:
mimikatz $ crypto::cng
"KeyIso" service patched
Magic. (:
Windows Defender is another program blocking the program to work, so you will need also to disable it for the time of using program at least.
The silly mistake I had done was keeping mysql.py
in same dir. Try renaming mysql.py
to another name so python
don't consider that as module.
Here is HexToBin and BinToHex relatively clean and readable. (Note originally there were returned enum error codes through an error logging system not a simple -1 or -2.)
typedef unsigned char ByteData;
ByteData HexChar (char c)
{
if ('0' <= c && c <= '9') return (ByteData)(c - '0');
if ('A' <= c && c <= 'F') return (ByteData)(c - 'A' + 10);
if ('a' <= c && c <= 'f') return (ByteData)(c - 'a' + 10);
return (ByteData)(-1);
}
ssize_t HexToBin (const char* s, ByteData * buff, ssize_t length)
{
ssize_t result = 0;
if (!s || !buff || length <= 0) return -2;
while (*s)
{
ByteData nib1 = HexChar(*s++);
if ((signed)nib1 < 0) return -3;
ByteData nib2 = HexChar(*s++);
if ((signed)nib2 < 0) return -4;
ByteData bin = (nib1 << 4) + nib2;
if (length-- <= 0) return -5;
*buff++ = bin;
++result;
}
return result;
}
void BinToHex (const ByteData * buff, ssize_t length, char * output, ssize_t outLength)
{
char binHex[] = "0123456789ABCDEF";
if (!output || outLength < 4) return (void)(-6);
*output = '\0';
if (!buff || length <= 0 || outLength <= 2 * length)
{
memcpy(output, "ERR", 4);
return (void)(-7);
}
for (; length > 0; --length, outLength -= 2)
{
ByteData byte = *buff++;
*output++ = binHex[(byte >> 4) & 0x0F];
*output++ = binHex[byte & 0x0F];
}
if (outLength-- <= 0) return (void)(-8);
*output++ = '\0';
}
txt = txt.Trim();
In later versions, the plugin has changed name to:
apply plugin: 'com.android.library'
And as already mentioned by some of the other answers, you need the gradle tools in order to use it. Using 3.0.1, you have to use the google repo, not mavenCentral or jcenter:
buildscript {
repositories {
...
//In IntelliJ or older versions of Android Studio
//maven {
// url 'https://maven.google.com'
//}
google()//in newer versions of Android Studio
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
I agree that enumerating through the registry key is the best way.
Note, however, that the key given, @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
, will list all applications in a 32-bit Windows installation, and 64-bit applications in a Windows 64-bit installation.
In order to also see 32-bit applications installed on a Windows 64-bit installation, you would also need to enumeration the key @"SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall"
.
For me the .crash file was enough. Without .dSYM file and .app file.
I ran these two commands on the mac where I build the archive and it worked:
export DEVELOPER_DIR="/Applications/Xcode.app/Contents/Developer"
/Applications/Xcode.app/Contents/SharedFrameworks/DVTFoundation.framework/Versions/A/Resources/symbolicatecrash /yourPath/crash1.crash > /yourPath/crash1_symbolicated.crash
This can be achieved with greater cross-browser support than the accepted answer by using pseudo-elements as exemplified by this answer: https://stackoverflow.com/a/19818268/2602816
Yes, this is possible. One of the main pros for using Swing is the ease with which the abstract controls can be created and manipulates.
Here is a quick and dirty way to extend the existing JButton class to draw a circle to the right of the text.
package test;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
public class MyButton extends JButton {
private static final long serialVersionUID = 1L;
private Color circleColor = Color.BLACK;
public MyButton(String label) {
super(label);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension originalSize = super.getPreferredSize();
int gap = (int) (originalSize.height * 0.2);
int x = originalSize.width + gap;
int y = gap;
int diameter = originalSize.height - (gap * 2);
g.setColor(circleColor);
g.fillOval(x, y, diameter, diameter);
}
@Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width += size.height;
return size;
}
/*Test the button*/
public static void main(String[] args) {
MyButton button = new MyButton("Hello, World!");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
frame.setVisible(true);
}
}
Note that by overriding paintComponent that the contents of the button can be changed, but that the border is painted by the paintBorder method. The getPreferredSize method also needs to be managed in order to dynamically support changes to the content. Care needs to be taken when measuring font metrics and image dimensions.
For creating a control that you can rely on, the above code is not the correct approach. Dimensions and colours are dynamic in Swing and are dependent on the look and feel being used. Even the default Metal look has changed across JRE versions. It would be better to implement AbstractButton and conform to the guidelines set out by the Swing API. A good starting point is to look at the javax.swing.LookAndFeel and javax.swing.UIManager classes.
http://docs.oracle.com/javase/8/docs/api/javax/swing/LookAndFeel.html
http://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html
Understanding the anatomy of LookAndFeel is useful for writing controls: Creating a Custom Look and Feel
The severity level 16 in your example code is typically used for user-defined (user-detected) errors. The SQL Server DBMS itself emits severity levels (and error messages) for problems it detects, both more severe (higher numbers) and less so (lower numbers).
The state should be an integer between 0 and 255 (negative values will give an error), but the choice is basically the programmer's. It is useful to put different state values if the same error message for user-defined error will be raised in different locations, e.g. if the debugging/troubleshooting of problems will be assisted by having an extra indication of where the error occurred.
This Wikipedia article states:
On 64-bit versions of Windows, there are two folders for application files; the
"Program Files"
folder contains 64-bit programs, and the"Program Files (x86)"
folder contains 32-bit programs.
So if the program is installed under C:\Program Files
it is a 64-bit version. If it is installed under C:\Program Files (x86)
it is a 32-bit installation.
Yes.
If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably div
s and span
s) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).
The specifics depend on the DOM structure used.
Here it goes an example:
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Hope it helps.
Any other places you use TimerEventProcessor or Counter?
Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.
So instead of _Counter, you should use:
// when starting the timer:
DateTime _started = DateTime.UtcNow;
// in TimerEventProcessor:
seconds = (DateTime.UtcNow-started).TotalSeconds;
Label.Text = seconds.ToString();
Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.
In linux you can use this commande :
for exemple i want to delete "*.py~" so my command should be ==>
find . -name "*.py~" -exec rm -f {} \;
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
:::
works only with lists, while ++
can be used with any traversable. In the current implementation (2.9.0), ++
falls back on :::
if the argument is also a List
.
patchFor(answer @gary) :
$ git diff JSONObject.java
diff --git a/JSONObject.java b/JSONObject.java
index e28c9cd..e12b7a0 100755
--- a/JSONObject.java
+++ b/JSONObject.java
@@ -32,7 +32,7 @@ import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.Enumeration;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
@@ -152,7 +152,9 @@ public class JSONObject {
* Construct an empty JSONObject.
*/
public JSONObject() {
- this.map = new HashMap<String, Object>();
+// this.map = new HashMap<String, Object>();
+ // I want to keep order of the given data:
+ this.map = new LinkedHashMap<String, Object>();
}
/**
@@ -243,7 +245,7 @@ public class JSONObject {
* @throws JSONException
*/
public JSONObject(Map<String, Object> map) {
- this.map = new HashMap<String, Object>();
+ this.map = new LinkedHashMap<String, Object>();
if (map != null) {
Iterator<Entry<String, Object>> i = map.entrySet().iterator();
while (i.hasNext()) {
Decode to Unicode, encode the results to UTF8.
apple.decode('latin1').encode('utf8')
There is nothing that char array gives you vs String unless you clean it up manually after use, and I haven't seen anyone actually doing that. So to me the preference of char[] vs String is a bit exaggerated.
Take a look at the widely used Spring Security library here and ask yourself - are Spring Security guys incompetent or char[] passwords just don't make much sense. When some nasty hacker grabs memory dumps of your RAM be sure s/he'll get all the passwords even if you use sophisticated ways to hide them.
However, Java changes all the time, and some scary features like String Deduplication feature of Java 8 might intern String objects without your knowledge. But that's a different conversation.
public class MainActivity extends Activity {
Bitmap b;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView)findViewById(R.id.imageView1);
information info = new information();
info.execute("");
}
public class information extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... arg0) {
try
{
URL url = new URL("http://10.119.120.10:80/img.jpg");
InputStream is = new BufferedInputStream(url.openStream());
b = BitmapFactory.decodeStream(is);
} catch(Exception e){}
return null;
}
@Override
protected void onPostExecute(String result) {
img.setImageBitmap(b);
}
}
}
The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.
This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
With Java 8, you actually can
List<TestB> variable = collectionOfListA
.stream()
.map(e -> (TestB) e)
.collect(Collectors.toList());
for logical && both the parameters must be true , then it ll be entered in if {} clock otherwise it ll execute else {}. for logical || one of parameter or condition is true is sufficient to execute if {}.
if( (A) && (B) ){
//if A and B both are true
}else{
}
if( (A) ||(B) ){
//if A or B is true
}else{
}
Fast functional solution for non-bijective maps (values not unique):
from itertools import imap, groupby
def fst(s):
return s[0]
def snd(s):
return s[1]
def inverseDict(d):
"""
input d: a -> b
output : b -> set(a)
"""
return {
v : set(imap(fst, kv_iter))
for (v, kv_iter) in groupby(
sorted(d.iteritems(),
key=snd),
key=snd
)
}
In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.
Unfortunately the values have to be sortable, the sorting is required by groupby.
For those of you out there that are encountering this, use the time.RFC3339 versus the string constant of "2006-01-02T15:04:05.000Z"
. And here is the reason why:
regDate := "2007-10-09T22:50:01.23Z"
layout1 := "2006-01-02T15:04:05.000Z"
t1, err := time.Parse(layout1, regDate)
if err != nil {
fmt.Println("Static format doesn't work")
} else {
fmt.Println(t1)
}
layout2 := time.RFC3339
t2, err := time.Parse(layout2, regDate)
if err != nil {
fmt.Println("RFC format doesn't work") // You shouldn't see this at all
} else {
fmt.Println(t2)
}
This will produce the following result:
Static format doesn't work
2007-10-09 22:50:01.23 +0000 UTC
Here is the Playground Link
Go a simple way to do this :-
Created one class to hold following information
Go the list of sites stored on a ArrayList object. And executed following query to sort it in descending order by Level.
var query = from MyClass object in objCollection
orderby object.Level descending
select object
Once I got the collection sorted in descending order, I wrote following code to get the Object that comes as top row
MyClass topObject = query.FirstRow<MyClass>()
This worked like charm.
Work for arrays and lists only, not for set.
Linking to express issue #3330
You may set the timeout either globally for entire server:
var server = app.listen();
server.setTimeout(500000);
or just for specific route:
app.post('/xxx', function (req, res) {
req.setTimeout(500000);
});
To get the difference between two-moment format dates or javascript Date format indifference of minutes the most optimum solution is
const timeDiff = moment.duration((moment(apptDetails.end_date_time).diff(moment(apptDetails.date_time)))).asMinutes()
you can change the difference format as you need by just replacing the asMinutes() function
I might approach it like so (CSS and HTML):
html,_x000D_
body {_x000D_
margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
position: absolute; /* Reposition logo from the natural layout */_x000D_
left: 75px;_x000D_
top: 0px;_x000D_
width: 300px;_x000D_
height: 200px;_x000D_
z-index: 2;_x000D_
}_x000D_
#content {_x000D_
margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
#links {_x000D_
height: 75px;_x000D_
margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}
_x000D_
<div id="logo">_x000D_
<img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
_x000D_
<div id="links">dssdfsdfsdfsdf</div>_x000D_
</div>
_x000D_
This solution works nice when using Latin American accents, such as 'ñ'.
I have solved this problem just by adding
df = pd.read_csv(fileName,encoding='latin1')
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
I use this simple pattern on dart and previously on Swift. I like that it's terse and only one way of using it.
class Singleton {
static Singleton shared = Singleton._init();
Singleton._init() {
// init work here
}
void doSomething() {
}
}
Singleton.shared.doSomething();
oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.
olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..
This is what I have done. (Adapt from all of your answers)
<input name="textbox1" type="text" id="txt1"/>
<input name="buttonExecute" onclick="execute(document.getElementById('txt1').value)" type="button" value="Execute" />
It works. Thanks to all of you. :)
I agree with previous comment that might be best to consider a different approach. My suggest would be write a console application and use the windows scheduler:
This will:
For me the following worked
- php artisan config:cache
- php artisan config:clear
- php artisan cache:clear
If you are using Xcode 8.0 and swift 3.0 or 2.2
Just paste
Debugger.Break();
any where in you code.
For Example ,
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
private static void Main()
{
Debugger.Break();
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
}
}
It will hit Debugger.Break();
when you run your program.
Check this one
StackTrace st = new StackTrace(ex, true);
//Get the first stack frame
StackFrame frame = st.GetFrame(0);
//Get the file name
string fileName = frame.GetFileName();
//Get the method name
string methodName = frame.GetMethod().Name;
//Get the line number from the stack frame
int line = frame.GetFileLineNumber();
//Get the column number
int col = frame.GetFileColumnNumber();
$location / switching between html5 and hashbang mode / link rewriting
Heaptrack is KDE tool that has a GUI and text interface. I find it more suitable than valgrind to understand the memory usage of a process because it provides more details and flamegraphs. It's also faster because it does less checking that valgrind. And it gives you the peak memory usage.
Anyway, tracking rss and vss is misleading because pages could be shared, that's why that memusg
. What you should really do is track the sum of Pss
in /proc/[pid]/smaps
or use pmap
. GNOME system-monitor used to do so but it was too expensive.
Try below code
I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.
Private Sub ComboBox1_Change()
On Error Resume Next
Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
On Error GoTo 0
If Ret <> "" Then MsgBox Ret
End Sub
OR
On Error Resume Next
Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
If Result = "Error 2042" Then
'nothing found
ElseIf cell <> Result Then
MsgBox cell.Value
End If
On Error GoTo 0
This is what I am doing:
string tStamp = String.Format("{0:yyyyMMdd.HHmmss}", DateTime.Now); string ProcID = Process.GetCurrentProcess().Id.ToString(); string tmpFolder = System.IO.Path.GetTempPath(); string outFile = tmpFolder + ProcID + "_" + tStamp + ".txt";
I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html
This is all I know how to do though sorry.
#!/usr/local/bin/python2.7
import dpkt
counter=0
ipcounter=0
tcpcounter=0
udpcounter=0
filename='sampledata.pcap'
for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):
counter+=1
eth=dpkt.ethernet.Ethernet(pkt)
if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
continue
ip=eth.data
ipcounter+=1
if ip.p==dpkt.ip.IP_PROTO_TCP:
tcpcounter+=1
if ip.p==dpkt.ip.IP_PROTO_UDP:
udpcounter+=1
print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter
Update:
I know this is kind of old thread, however, this can be achieved with min-height
CSS property in a clean way, so I'll leave this here for future references:
I made a fiddle based on the OP posted code here: http://jsfiddle.net/U5x4T/1/, as you remove and add divs inside, you'll notice how does the container expands or reduces in size
The only 2 things you need to achieve this, additional to the OP code is:
*Overflow in the main container (required for the floating divs)
*min-height css property, more info available here: http://www.w3schools.com/cssref/pr_dim_min-height.asp
You must sort your data according your needs (es. in reverse order) and use select top query
It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.
char *buff;
size_t buff_size = 100;
int choice;
do{
buff = (char *)malloc(buff_size *sizeof(char));
getline(&buff, &buff_size, stdin);
choice = atoi(buff);
free(buff);
}while((choice<1)&&(choice>9));
you can use Apache commons' StringUtils class
String[] partsOfString = StringUtils.split("I want to walk my dog",StringUtils.SPACE)
I had a similar problem. My solution was to switch off the antivirus software (Avast), download the .iso file, mount it (double click in the Windows Explorer on the .iso file), and then run it from the PowerShell with admin rights with the following switches:
.\vs_community.exe /NoWeb /NoRefresh
This way you don't have to go offline or remove your existing installation.
There is a very nice PHP library for detecting mobile clients here: http://mobiledetect.net
Using that it's quite easy to only display content for a mobile:
include 'Mobile_Detect.php';
$detect = new Mobile_Detect();
// Check for any mobile device.
if ($detect->isMobile()){
// mobile content
}
else {
// other content for desktops
}
COALESCE
is more modern function that is a part of ANSI-92
standard.
NVL
is Oracle
specific, it was introduced in 80
's before there were any standards.
In case of two values, they are synonyms.
However, they are implemented differently.
NVL
always evaluates both arguments, while COALESCE
usually stops evaluation whenever it finds the first non-NULL
(there are some exceptions, such as sequence NEXTVAL
):
SELECT SUM(val)
FROM (
SELECT NVL(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
FROM dual
CONNECT BY
level <= 10000
)
This runs for almost 0.5
seconds, since it generates SYS_GUID()
's, despite 1
being not a NULL
.
SELECT SUM(val)
FROM (
SELECT COALESCE(1, LENGTH(RAWTOHEX(SYS_GUID()))) AS val
FROM dual
CONNECT BY
level <= 10000
)
This understands that 1
is not a NULL
and does not evaluate the second argument.
SYS_GUID
's are not generated and the query is instant.
I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until
loop.
Do Until Selection.Value = ""
Rem Do things here...
Loop
You can use the overloads method RedirectToAction(string actionName, string controllerName);
Example:
RedirectToAction(nameof(HomeController.Index), "Home");
I was stuck with non functional https on IIS. Solved with:
file_get_contents('https.. ) wouldn't load.
edit php.ini with:
curl.cainfo = "C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem" openssl.cafile="C:\Program Files\PHP\v7.3\extras\ssl\cacert.pem"
finally!
I'd say the best way is to make an href anchor to an ID you'd never use, like #Do1Not2Use3This4Id5 or a similar ID, that you are 100% sure no one will use and won't offend people.
Javascript:void(0)
is a bad idea and violates Content Security Policy on CSP-enabled HTTPS pages https://developer.mozilla.org/en/docs/Security/CSP (thanks to @jakub.g)#
will have the user jump back to the top when pressedBasically no one mentioned 5 in this article which I think is important as your site comes off as unprofessional if it suddenly starts selecting things around the link.
<form>.WindowState = FormWindowState.Minimized;
The answer here (https://stackoverflow.com/a/22408965/2236315) by @adrianoesch should help (e.g., solves "If you know of a solution that does not require the awkward workaround mentioned in your comment (shift the column names, copy the data), that would be great." and "...requiring that the data be copied" proposed by @Frank).
Note that if you open in some text editor, you should see that the number of header fields less than number of columns below the header row. In my case, the data set had a "," missing at the end of the last header field.
My Solutions:
$("body").scrollspy({ target: ".target", offset: fix_header_height });
$(".target").click(function() {
$("body").animate(
{
scrollTop: $($(this).attr("href")).offset().top - fix_header_height
},
500
);
return;
});
If you use Three20
, then use the autoresizesForKeyboard
property. Just set in the your view controller's -initWithNibName:bundle
method
self.autoresizesForKeyboard = YES
This takes care of:
Done and done.
This is something that should only be done on a per-user basis, not per-repository. If Joe uses emacs, he will want to have emacs backup files ignored, but Betty (who uses vi) will want vi backup files ignored (in many cases, they are similar, but there are about 24,893 common editors in existence and it is pretty ridiculous to try to ignore all of the various backup extensions.)
In other words, do not put anything in .gitignore
or in core.excludes
in $GIT_DIR/config
. Put the info in $HOME/.gitconfig
instead (as nunopolonia suggests with --global
.) Note that "global" means per-user, not per-system.
If you want configuration across the system for all users (which you don't), you'll need a different mechanism. (Possibly with templates setup prior to initialization of the repository.)
A singleton should be used when managing access to a resource which is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread safe is one very good example of where this kind of pattern can be vital.
When using Singletons, you should make sure that you're not accidentally concealing dependencies. Ideally, the singletons (like most static variables in an application) be set up during the execution of your initialization code for the application (static void Main() for C# executables, static void main() for java executables) and then passed in to all other classes that are instantiated which require it. This helps you maintain testability.
I kept getting this error, when using wildcard subdomains with my app. I had the site url set to: http://myapp.com and app domain also to http://myapp.com, and also the same value for the Valid OAuth redirect URIs in the advanced tab of the settings app. I tried different combinations but only setting the http://subdomain.myapp.com as the redirect value worked, of course only for that subdomain.
The solution was to empty the redirect fields, leave it blank, that worked! ;)
Here are some:
"Ali".eql? "Ali"
=> true
The spaceship (<=>
) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:
"Apples" <=> "Apples"
=> 0
"Apples" <=> "Pears"
=> -1
"Pears" <=> "Apples"
=> 1
A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:
"Apples".casecmp "apples"
=> 0
As Justin Scofield has suggested in his answer, for Angular 5's latest release and for Angular 6, as on 1st June, 2018, just import 'rxjs/add/operator/map';
isn't sufficient to remove the TS error:
[ts] Property 'map' does not exist on type 'Observable<Object>'.
Its necessary to run the below command to install the required dependencies:
npm install rxjs@6 rxjs-compat@6 --save
after which the map
import dependency error gets resolved!
Open eclipse.ini
Search for -Xmx512m
or maybe more size it is.
Just change it to a required size such as I changed it to -Xmx1024m
When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.
To complete the response of the other users:
For this I have created an "WinHttp.WinHttpRequest.5.1" object.
Send a post request with some data from Excel using VBA:
Dim LoginRequest As Object
Set LoginRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
LoginRequest.Open "POST", "http://...", False
LoginRequest.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
LoginRequest.send ("key1=value1&key2=value2")
Send a get request with token authentication from Excel using VBA:
Dim TCRequestItem As Object
Set TCRequestItem = CreateObject("WinHttp.WinHttpRequest.5.1")
TCRequestItem.Open "GET", "http://...", False
TCRequestItem.setRequestHeader "Content-Type", "application/xml"
TCRequestItem.setRequestHeader "Accept", "application/xml"
TCRequestItem.setRequestHeader "Authorization", "Bearer " & token
TCRequestItem.send
You have to use bracket notation:
var obj = {};
obj[a[i]] = 0;
x.push(obj);
The result will be:
x = [{left: 0}, {top: 0}];
Maybe instead of an array of objects, you just want one object with two properties:
var x = {};
and
x[a[i]] = 0;
This will result in x = {left: 0, top: 0}
.
I know that i am late but i would like to post a solution here:
Check the full source code here.
This is the code i used when changing theme using preferences..
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
setTheme(R.style.AppTheme);
} else if (themeName.equals("Colorful Beach")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.beach);
} else if (themeName.equals("Abstract")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.abstract2);
} else if (themeName.equals("Default")) {
setTheme(R.style.defaulttheme);
}
Please note that you have to put the code before setcontentview..
HAPPY CODING!
Its actually formulated more like:
https://<bucket-name>.s3.amazonaws.com/<key>
See here
if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.
<div>
<div style="padding-bottom: 33%;">
i have 33% height of my parents width
</div>
</div>
Best Solution to wait AsynMethod till complete the task is
var result = Task.Run(async() => await yourAsyncMethod()).Result;
Here's a nice way to achieve anti-aliasing:
text-shadow: 0 0 1px rgba(0,0,0,0.3);
You need to annotate your Customer class with @Named or @Model annotation:
package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
private String email;
private String password;
}
or create/modify beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.
The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.
Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)
This will get you the PID of a process by name:
pidof name
Which you can then plug back in to ps for more detail:
ps -p $(pidof name)
I updated the old version, now it should support unquoted values such as integers and booleans.
I refactored the previous version and got the final version: The code is shorter and cleaner. Only require one extension method. The most important: fixed some bugs.
class JsonHelper
{
private const string INDENT_STRING = " ";
public static string FormatJson(string str)
{
var indent = 0;
var quoted = false;
var sb = new StringBuilder();
for (var i = 0; i < str.Length; i++)
{
var ch = str[i];
switch (ch)
{
case '{':
case '[':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case '}':
case ']':
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
}
sb.Append(ch);
break;
case '"':
sb.Append(ch);
bool escaped = false;
var index = i;
while (index > 0 && str[--index] == '\\')
escaped = !escaped;
if (!escaped)
quoted = !quoted;
break;
case ',':
sb.Append(ch);
if (!quoted)
{
sb.AppendLine();
Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
}
break;
case ':':
sb.Append(ch);
if (!quoted)
sb.Append(" ");
break;
default:
sb.Append(ch);
break;
}
}
return sb.ToString();
}
}
static class Extensions
{
public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
{
foreach (var i in ie)
{
action(i);
}
}
}
The following code should be considered bad form, regardless of language or desired functionality:
while( true ) {
}
The while( true )
loop is poor form because it:
while(true)
for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)The following code is better form:
while( isValidState() ) {
execute();
}
bool isValidState() {
return msg->state != DONE;
}
No flag. No goto
. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:
The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:
Readily insert the pause:
while( isValidState() ) {
execute();
sleep();
}
Override execute:
void execute() {
super->execute();
sleep();
}
This code is simpler (thus easier to read) than a loop with an embedded switch
. The isValidState
method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute
method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch
and goto
).
Contrast the following answer (to a Python question) that was posted on StackOverflow:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Versus:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Here, while True
results in misleading and overly complex code.
It would appear that you should
struct MD5context
and pass it to MD5Init
to get it into a proper starting conditionMD5Update
with the context and your dataMD5Final
to get the resulting hashThese three functions and the structure definition make a nice abstract interface to the hash algorithm. I'm not sure why you were shown the core transform function in that header as you probably shouldn't interact with it directly.
The author could have done a little more implementation hiding by making the structure an abstract type, but then you would have been forced to allocate the structure on the heap every time (as opposed to now where you can put it on the stack if you so desire).
As others have said, CGFloat is a float on 32-bit systems and a double on 64-bit systems. However, the decision to do that was inherited from OS X, where it was made based on the performance characteristics of early PowerPC CPUs. In other words, you should not think that float is for 32-bit CPUs and double is for 64-bit CPUs. (I believe, Apple's ARM processors were able to process doubles long before they went 64-bit.) The main performance hit of using doubles is that they use twice the memory and therefore might be slower if you are doing a lot of floating point operations.
As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique()
might be what you are looking for.
Input:
$input = array(4, "4", "3", 4, 3, "3");
$result = array_unique($input);
var_dump($result);
Result:
array(2) {
[0] => int(4)
[2] => string(1) "3"
}
You could leverage the html-to-react
npm module.
Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.
You could use .find("is")
, it would return position of "is" in the string
or use .start() from re
>>> re.search("is", String).start()
2
Actually its match "is" from "This"
If you need to match per word, you should use \b
before and after "is", \b
is the word boundary.
>>> re.search(r"\bis\b", String).start()
5
>>>
for more info about python regular expressions, docs here
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
.erb-image-wrapper img{
max-width:100% !important;
height:auto;
display:block;
}
Worked for me.
Thanks for MrMisterMan for his assistance.
If I'm understanding your question and code correctly, then I want to first mention three things before sharing my code/version of a solution. First, for both name
and value
you probably shouldn't be using the getAttribute()
method because they are, themselves, properties of (the variable named) inputs
(at a given index of i
). Secondly, the variable that you are trying to alert is one of a select handful of terms in JavaScript that are designated as 'reserved keywords' or simply "reserved words". As you can see in/on this list (on the link), new
is clearly a reserved word in JS and should never be used as a variable name. For more information, simply google 'reserved words in JavaScript'. Third and finally, in your alert statement itself, you neglected to include a semicolon. That and that alone can sometimes be enough for your code not to run as expected. [Aside: I'm not saying this as advice but more as observation: JavaScript will almost always forgive and allow having too many and/or unnecessary semicolons, but generally JavaScript is also equally if not moreso merciless if/when missing (any of the) necessary, required semicolons. Therefore, best practice is, of course, to add the semicolons only at all of the required points and exclude them in all other circumstances. But practically speaking, if in doubt, it probably will not hurt things by adding/including an extra one but will hurt by ignoring a mandatory one. General rules are all declarations and assignments end with a semicolon (such as variable assignments, alerts, console.log statements, etc.) but most/all expressions do not (such as for loops, while loops, function expressions Just Saying.] But I digress..
function whenWindowIsReady() {
var inputs = document.getElementsByTagName('input');
var lengthOfInputs = inputs.length; // this is for optimization
for (var i = 0; i < lengthOfInputs; i++) {
if (inputs[i].name === "ans") {
var ansIsName = inputs[i].value;
alert(ansIsName);
}
}
}
window.onReady = whenWindowIsReady();
PS: You used a double assignment operator in your conditional statement, and in this case it doesn't matter since you are comparing Strings, but generally I believe the triple assignment operator is the way to go and is more accurate as that would check if the values are EQUIVALENT WITHOUT TYPE CONVERSION, which can be very important for other instances of comparisons, so it's important to point out. For example, 1=="1" and 0==false are both true (when usually you'd want those to return false since the value on the left was not the same as the value on the right, without type conversion) but 1==="1" and 0===false are both false as you'd expect because the triple operator doesn't rely on type conversion when making comparisons. Keep that in mind for the future.
http://php.net/ereg_replace says:
Note: As of PHP 5.3.0, the regex extension is deprecated in favor of the PCRE extension.
Thus, preg_replace is in every way better choice. Note there are some differences in pattern syntax though.
So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.
Intuitively (and wrongly), most people assume that it looks something like this:
Local Computer | Remote Computer
--------------------------------
<local_ip>:80 | <foreign_ip>:80
^^ not actually what happens, but this is the conceptual model a lot of people have in mind.
This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.
Three things must be understood:
1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.
2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.
3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.
So, this is really what gets created when a client connects to a server:
Local Computer | Remote Computer | Role
-----------------------------------------------------------
0.0.0.0:80 | <none> | LISTENING
127.0.0.1:80 | 10.1.2.3:<random_port> | ESTABLISHED
First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).
netstat -atnp | grep -i ":500 "
As expected, the output is blank. Now let's start a web server:
sudo python3 -m http.server 500
Now, here is the output of running netstat again:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.
So now, let's connect a user to our machine:
quicknet -m tcp -t localhost:500 -p Test payload.
This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:54240 ESTABLISHED -
If you connect with another client and do netstat again, you will see the following:
Proto Recv-Q Send-Q Local Address Foreign Address State
tcp 0 0 0.0.0.0:500 0.0.0.0:* LISTEN -
tcp 0 0 192.168.1.10:500 192.168.1.13:26813 ESTABLISHED -
... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.
I too got the same error am using xcode version 4.0.2 so what i did was selected the xcode project file and from their i selected the Target option their i could see the app of my project so i clicked on it and went to the build settings option.
Their in the search option i typed Framework search path, and deleted all the settings and then clicked the build button and that worked for me just fine,
Thanks and Regards
One can use AMD GPU via the PlaidML Keras backend.
Fastest: PlaidML is often 10x faster (or more) than popular platforms (like TensorFlow CPU) because it supports all GPUs, independent of make and model. PlaidML accelerates deep learning on AMD, Intel, NVIDIA, ARM, and embedded GPUs.
Easiest: PlaidML is simple to install and supports multiple frontends (Keras and ONNX currently)
Free: PlaidML is completely open source and doesn't rely on any vendor libraries with proprietary and restrictive licenses.
For most platforms, getting started with accelerated deep learning is as easy as running a few commands (assuming you have Python (v2 or v3) installed):
virtualenv plaidml
source plaidml/bin/activate
pip install plaidml-keras plaidbench
Choose which accelerator you'd like to use (many computers, especially laptops, have multiple):
plaidml-setup
Next, try benchmarking MobileNet inference performance:
plaidbench keras mobilenet
Or, try training MobileNet:
plaidbench --batch-size 16 keras --train mobilenet
To use it with keras set
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
For more information
https://github.com/plaidml/plaidml
https://github.com/rstudio/keras/issues/205#issuecomment-348336284
I do wonder if perhaps you should iterate over the exploded HTTP_X_FORWARDED_FOR in reverse order, since my experience has been that the user's IP address ends up at the end of the comma-separated list, so starting at the start of the header, you're more likely to get the ip address of one of the proxies returned, which could potentially still allow session hijacking as many users may come through that proxy.
Account Unlock by using below query :
SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';
USERNAME ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV LOCKED
SQL> alter user ABCD_DEV account unlock;
User altered.
SQL> select USERNAME,ACCOUNT_STATUS from dba_users where username='ABCD_DEV';
USERNAME ACCOUNT_STATUS
-------------------- --------------------------------
ABCD_DEV OPEN
Check PASSWORD_LIFE_TIME
parameter by using below query :
SELECT resource_name, limit FROM dba_profiles WHERE profile = 'DEFAULT' AND resource_type = 'PASSWORD';
RESOURCE_NAME LIMIT
-------------------------------- ------------------------------
FAILED_LOGIN_ATTEMPTS 10
PASSWORD_LIFE_TIME 10
PASSWORD_REUSE_TIME 10
PASSWORD_REUSE_MAX UNLIMITED
PASSWORD_VERIFY_FUNCTION NULL
PASSWORD_LOCK_TIME 1
PASSWORD_GRACE_TIME 7
INACTIVE_ACCOUNT_TIME UNLIMITED
Change the parameter using below query
ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;
You could open the SLN file in any text editor (Notepad, etc.) and simply change the project path there.
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
You can subclass UIButton
and add @IBInspectable
variables to it so you can configure the custom button parameters via the StoryBoard "Attribute Inspector". Below I write down that code.
@IBDesignable
class BHButton: UIButton {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable lazy var isRoundRectButton : Bool = false
@IBInspectable public var cornerRadius : CGFloat = 0.0 {
didSet{
setUpView()
}
}
@IBInspectable public var borderColor : UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
@IBInspectable public var borderWidth : CGFloat = 0.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
// MARK: Awake From Nib
override func awakeFromNib() {
super.awakeFromNib()
setUpView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setUpView()
}
func setUpView() {
if isRoundRectButton {
self.layer.cornerRadius = self.bounds.height/2;
self.clipsToBounds = true
}
else{
self.layer.cornerRadius = self.cornerRadius;
self.clipsToBounds = true
}
}
}
<button class="btn btn-default glyphicon glyphicon-plus fa-2x" type="button">_x000D_
</button>_x000D_
_x000D_
<!--fa-2x , fa-3x , fa-4x ... -->_x000D_
<button class="btn btn-default glyphicon glyphicon-plus fa-3x" type="button">_x000D_
</button>
_x000D_
You can covert numpy.ndarray
to object
using astype(object)
This will work:
>>> a = [np.zeros((224,224,3)).astype(object), np.zeros((224,224,3)).astype(object), np.zeros((224,224,13)).astype(object)]
Split string in JavaScript
var array = str.match(/[^\r\n]+/g);
OR
var array = str.split(/\r?\n/);
The below PL/SQL block finds all locked rows in a table. The other answers only find the blocking session, finding the actual locked rows requires reading and testing each row.
(However, you probably do not need to run this code. If you're having a locking problem, it's usually easier to find the culprit using GV$SESSION.BLOCKING_SESSION
and other related data dictionary views. Please try another approach before you run this abysmally slow code.)
First, let's create a sample table and some data. Run this in session #1.
--Sample schema.
create table test_locking(a number);
insert into test_locking values(1);
insert into test_locking values(2);
commit;
update test_locking set a = a+1 where a = 1;
In session #2, create a table to hold the locked ROWIDs.
--Create table to hold locked ROWIDs.
create table locked_rowids(the_rowid rowid);
--Remove old rows if table is already created:
--delete from locked_rowids;
--commit;
In session #2, run this PL/SQL block to read the entire table, probe each row, and store the locked ROWIDs. Be warned, this may be ridiculously slow. In your real version of this query, change both references to TEST_LOCKING to your own table.
--Save all locked ROWIDs from a table.
--WARNING: This PL/SQL block will be slow and will temporarily lock rows.
--You probably don't need this information - it's usually good enough to know
--what other sessions are locking a statement, which you can find in
--GV$SESSION.BLOCKING_SESSION.
declare
v_resource_busy exception;
pragma exception_init(v_resource_busy, -00054);
v_throwaway number;
type rowid_nt is table of rowid;
v_rowids rowid_nt := rowid_nt();
begin
--Loop through all the rows in the table.
for all_rows in
(
select rowid
from test_locking
) loop
--Try to look each row.
begin
select 1
into v_throwaway
from test_locking
where rowid = all_rows.rowid
for update nowait;
--If it doesn't lock, then record the ROWID.
exception when v_resource_busy then
v_rowids.extend;
v_rowids(v_rowids.count) := all_rows.rowid;
end;
rollback;
end loop;
--Display count:
dbms_output.put_line('Rows locked: '||v_rowids.count);
--Save all the ROWIDs.
--(Row-by-row because ROWID type is weird and doesn't work in types.)
for i in 1 .. v_rowids.count loop
insert into locked_rowids values(v_rowids(i));
end loop;
commit;
end;
/
Finally, we can view the locked rows by joining to the LOCKED_ROWIDS table.
--Display locked rows.
select *
from test_locking
where rowid in (select the_rowid from locked_rowids);
A
-
1
This function will work properly :)
// MediaPlayer m; /*assume, somewhere in the global scope...*/
public void playBeep() {
try {
if (m.isPlaying()) {
m.stop();
m.release();
m = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("beepbeep.mp3");
m.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
m.prepare();
m.setVolume(1f, 1f);
m.setLooping(true);
m.start();
} catch (Exception e) {
e.printStackTrace();
}
}
There is no ANSI C function that provides better than 1 second time resolution but the POSIX function gettimeofday
provides microsecond resolution. The clock function only measures the amount of time that a process has spent executing and is not accurate on many systems.
You can use this function like this:
struct timeval tval_before, tval_after, tval_result;
gettimeofday(&tval_before, NULL);
// Some code you want to time, for example:
sleep(1);
gettimeofday(&tval_after, NULL);
timersub(&tval_after, &tval_before, &tval_result);
printf("Time elapsed: %ld.%06ld\n", (long int)tval_result.tv_sec, (long int)tval_result.tv_usec);
This returns Time elapsed: 1.000870
on my machine.
Panel with opacity:
public class GlassyPanel : Panel
{
const int WS_EX_TRANSPARENT = 0x20;
int opacity = 50;
public int Opacity
{
get
{
return opacity;
}
set
{
if (value < 0 || value > 100) throw new ArgumentException("Value must be between 0 and 100");
opacity = value;
}
}
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.ExStyle = cp.ExStyle | WS_EX_TRANSPARENT;
return cp;
}
}
protected override void OnPaint(PaintEventArgs e)
{
using (var b = new SolidBrush(Color.FromArgb(opacity * 255 / 100, BackColor)))
{
e.Graphics.FillRectangle(b, ClientRectangle);
}
base.OnPaint(e);
}
}
In my case, you need to convert the column(you think this column is numeric, but actually not) to numeric
geom_segment(data=tmpp,
aes(x=start_pos,
y=lib.complexity,
xend=end_pos,
yend=lib.complexity)
)
# to
geom_segment(data=tmpp,
aes(x=as.numeric(start_pos),
y=as.numeric(lib.complexity),
xend=as.numeric(end_pos),
yend=as.numeric(lib.complexity))
)
Include moment.js and using the below code you can format your date
var formatDate= 1399919400000;
var responseDate = moment(formatDate).format('DD/MM/YYYY');
My output is "13/05/2014"
Even though the question is too old, but I would like to share the solution that worked for me because I already checked everything when it comes to this error. It was a pain, I spent two days trying and at the end the solution was:
update the M2e plugin in eclipse
clean and build again
I think it's all personal preference. My preferences come from using NHibernate, in .NET, with SQL Server, so they probably differ from what others use.
Honestly, it doesn't matter too much, as long as it's consistent for the project. Just get to work and don't sweat the details :P
If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings xdt:Transform="Replace">
<!-- production environment config --->
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
<add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
....
Information for this answer are brought from this answer and this blog post.
notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).
Your query translates to
SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';
It will only return the results that match it.
One way of solving it avoiding the complexity would be, chaning the datatype to SET
.
Then you could use, FIND_IN_SET
SELECT * FROM table WHERE FIND_IN_SET('1', id);
If you make change default value to CURRENT_TIMESTAMP
it is more effiency,
ALTER TABLE servers MODIFY COLUMN network_shares datetime NOT NULL DEFAULT CURRENT_TIMESTAMP;
For most of the people still receiving the error after fixing project properties, you probably installed Java 7 SDK when setting up your environment, but it is not currently supported for Android development.
As the error message sais, you should have installed Java 5.0 or 6.0, but Java 7 was found.
If you fix project properties without first installing Java 5 or 6, you will see the same error again.
And then:
OR
Threaded:
/// <summary>
/// Usage: var timer = SetIntervalThread(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be disposed.</returns>
public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
{
TimerStateManager state = new TimerStateManager();
System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
state.TimerObject = tmr;
return tmr;
}
Regular
/// <summary>
/// Usage: var timer = SetInterval(DoThis, 1000);
/// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
/// </summary>
/// <returns>Returns a timer object which can be stopped and disposed.</returns>
public static System.Timers.Timer SetInterval(Action Act, int Interval)
{
System.Timers.Timer tmr = new System.Timers.Timer();
tmr.Elapsed += (sender, args) => Act();
tmr.AutoReset = true;
tmr.Interval = Interval;
tmr.Start();
return tmr;
}
If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE
command to CREATE DATABASE IF NOT EXISTS
in line22
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.
If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:
Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);
t.Start();
with ThreadProc being a delegate of type ThreadStart.
use this
System.Configuration.ConfigurationSettings.AppSettings.Get("Keyname")
Some people, like me, will benefit from using the :focus-within
pseudo-class.
Using it will apply the css you want to a div, for instance.
You can read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-within
You should make the container relative and give it a height as well and you're done.
http://jsfiddle.net/jaap/wjw83/4/
.main {_x000D_
width: 300px;_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
height: 200px;_x000D_
}_x000D_
_x000D_
img.absolute {_x000D_
left: 50%;_x000D_
margin-left: -200px;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="main">_x000D_
<img class="absolute" src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />_x000D_
</div>_x000D_
<br />_x000D_
<img src="http://via.placeholder.com/400x200/A44/EED?text=Hello" alt="" />
_x000D_
If you want to you can also center the image vertically by adding a negative margin and top position: http://jsfiddle.net/jaap/wjw83/5/
Just use DOMDocument->loadHTML() and be done with it. libxml's HTML parsing algorithm is quite good and fast, and contrary to popular belief, does not choke on malformed HTML.
To quote Bjarne Stroustrup:"The >> operator is intended for formatted input; that is, reading objects of an expected type and format. Where this is not desirable and we want to read charactes as characters and then examine them, we use the get() functions."
char c;
while (input.get(c))
{
// do something with c
}
From wikipedia:
In functional programming, a monad is a kind of abstract data type used to represent computations (instead of data in the domain model). Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad. Programs written in functional style can make use of monads to structure procedures that include sequenced operations,1[2] or to define arbitrary control flows (like handling concurrency, continuations, or exceptions).
Formally, a monad is constructed by defining two operations (bind and return) and a type constructor M that must fulfill several properties to allow the correct composition of monadic functions (i.e. functions that use values from the monad as their arguments). The return operation takes a value from a plain type and puts it into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.
A programmer will compose monadic functions to define a data-processing pipeline. The monad acts as a framework, as it's a reusable behavior that decides the order in which the specific monadic functions in the pipeline are called, and manages all the undercover work required by the computation.[3] The bind and return operators interleaved in the pipeline will be executed after each monadic function returns control, and will take care of the particular aspects handled by the monad.
I believe it explains it very well.
If you want to pass props to a component inside a route, the simplest way is by utilizing the render
, like this:
<Route exact path="/details/:id" render={(props) => <DetailsPage globalStore={globalStore} {...props} /> } />
You can access the props inside the DetailPage
using:
this.props.match
this.props.globalStore
The {...props}
is needed to pass the original Route's props, otherwise you will only get this.props.globalStore
inside the DetailPage
.
I know the ask is to count a particular letter. I am writing here generic code without using any method.
sentence1 =" Mary had a little lamb"
count = {}
for i in sentence1:
if i in count:
count[i.lower()] = count[i.lower()] + 1
else:
count[i.lower()] = 1
print(count)
output
{' ': 5, 'm': 2, 'a': 4, 'r': 1, 'y': 1, 'h': 1, 'd': 1, 'l': 3, 'i': 1, 't': 2, 'e': 1, 'b': 1}
Now if you want any particular letter frequency, you can print like below.
print(count['m'])
2
Apart of larsmans answer (who is indeed correct), the exception in a call to a get() method, so the code you have posted is not the one that is causing the error.
Yes, querySelectorAll
does take a group of selectors:
form, p, legend
Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.
Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().
from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True,
validation_split=0.2, verbose = 2)
How is Batch Normalization applied?
Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity
Now define new parameters ? and ß that will change the scale of the hidden layer as follows:
z_norm[l] = ?.Z_temp[l] + ß
In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.
a[l] = tanh(z_norm[l])
Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.
Benefits:
Just attach it to your timestamps on DOM ready:
jQuery(document).ready(function() {
jQuery('abbr.timeago').timeago();
});
This will turn all abbr
elements with a class of timeago and an ISO 8601 timestamp in the title:
<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>
into something like this:
<abbr class="timeago" title="July 17, 2008">4 months ago</abbr>
which yields: 4 months ago. As time passes, the timestamps will automatically update.
Disclaimer: I wrote this plugin, so I'm biased.
Based on @tenshi's and @pkalinow's comments (also kudos to @rogerdpack), the following is a simple solution for creating a list argument captor that also disables the "uses unchecked or unsafe operations" warning:
@SuppressWarnings("unchecked")
final ArgumentCaptor<List<SomeType>> someTypeListArgumentCaptor =
ArgumentCaptor.forClass(List.class);
Full example here and corresponding passing CI build and test run here.
Our team has been using this for some time in our unit tests and this looks like the most straightforward solution for us.
For example if you are in the parent directory of you destination folders you can do:
for i in $(ls); do cp sourcefile $i; done
WARNING: It should be noted that this solution will block the calling thread.
If you want to process exceptions thrown by the task, then it is generally better to use Callable
rather than Runnable
.
Callable.call()
is permitted to throw checked exceptions, and these get propagated back to the calling thread:
Callable task = ...
Future future = executor.submit(task);
try {
future.get();
} catch (ExecutionException ex) {
ex.getCause().printStackTrace();
}
If Callable.call()
throws an exception, this will be wrapped in an ExecutionException
and thrown by Future.get()
.
This is likely to be much preferable to subclassing ThreadPoolExecutor
. It also gives you the opportunity to re-submit the task if the exception is a recoverable one.
Use defaultdict
from collections import defaultdict
a = {}
a = defaultdict(lambda:0,a)
a["anything"] # => 0
This is very useful for case like this,where default values for every key is set as 0:
results ={ 'pre-access' : {'count': 4, 'pass_count': 2},'no-access' : {'count': 55, 'pass_count': 19}
for k,v in results.iteritems():
a['count'] += v['count']
a['pass_count'] += v['pass_count']
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
REPLACE INTO
pros:
cons:
too slow.
auto-increment key will CHANGE(increase by 1) if there is entry matches unique key
or primary key
, because it deletes the old entry then insert new one.
INSERT IGNORE
pros:
cons:
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
some other errors/warnings will be ignored such as data conversion error.
INSERT ... ON DUPLICATE KEY UPDATE
pros:
cons:
looks relatively complex if you just want to insert not update.
auto-increment key will not change if there is entry matches unique key
or primary key
but auto-increment index will increase by 1
unique key
or primary key
?As mentioned in the comment below by @toien: "auto-increment column will be effected depends on innodb_autoinc_lock_mode
config after version 5.1" if you are using innodb
as your engine, but this also effects concurrency, so it needs to be well considered before used. So far I'm not seeing any better solution.
in Eclipse 4.4.1
com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
Internally, the rm command must test for file existence anyway,
so why add another test? Just issue
rm filename
and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.
If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.
Instead of style changes, just put these two lines of code to your activity.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowleft);
I'd refrain from using floats for this sort of thing; I'd rather use inline-block
.
Some more points to consider:
<head>
and <body>
doctype
Here's a better way to format your document:
<!DOCTYPE html>
<html>
<head>
<title>Website Title</title>
<style type="text/css">
* {margin: 0; padding: 0;}
#container {height: 100%; width:100%; font-size: 0;}
#left, #middle, #right {display: inline-block; *display: inline; zoom: 1; vertical-align: top; font-size: 12px;}
#left {width: 25%; background: blue;}
#middle {width: 50%; background: green;}
#right {width: 25%; background: yellow;}
</style>
</head>
<body>
<div id="container">
<div id="left">Left Side Menu</div>
<div id="middle">Random Content</div>
<div id="right">Right Side Menu</div>
</div>
</body>
</html>
Here's a jsFiddle for good measure.
If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:
# cast() is available starting Python 3.3
size = 10**6
ints = memoryview(bytearray(size)).cast('i')
ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))
ints[0]
# 0
ints[0] = 16
ints[0]
# 16
The While statement will not execute until after form1 is closed - as it is outside the main message loop.
Remove it and change the first bit of code to:
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
this.Visible=false;
Form2 form2 = new Form2();
form2.show();
}
else MessageBox.Show("Insert Attributes First !");
}
This is not the best way to achieve what you are looking to do though. Instead consider the Wizard design pattern.
Alternatively you could implement a custom ApplicationContext that handles the lifetime of both forms. An example to implement a splash screen is here, which should set you on the right path.
http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx?display=Print
One line if:
<statement> if <condition>
Your case:
"Yes" if @item.rigged
"No" if [email protected] # or: "No" unless @item.rigged
Read the docs about built-in PHP function readfile
$file_url = 'http://www.myremoteserver.com/file.exe';
header('Content-Type: application/octet-stream');
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
readfile($file_url);
Also make sure to add proper content type based on your file application/zip, application/pdf etc. - but only if you do not want to trigger the save-as dialog.
That is a binary operator in hibernate you should use
is not null
Have a look at 14.10. Expressions
This is caused by:
So in both cases you have a poorly defined or implemented application protocol.
There is a third reason which I will not document here but which involves the peer taking deliberate action to reset rather than properly close the connection.
This will work in Chrome
// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'
But after looking, labels doesn't seem to be widely supported..
You can use querySelector
// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'
Maybe you want to try this: https://bootstrap-datepicker.readthedocs.org/en/latest/index.html
It's a flexible datepicker widget in the Bootstrap style.
Try to log the stack trace like below:
logger.error("Exception :: " , e);
A quick search using...
apt search Xlib.h
Turns up the package libx11-dev but you shouldn't need this for pure OpenGL programming. What tutorial are you using?
You can add Xlib.h to your system by running the following...
sudo apt install libx11-dev
A lot of these answers are super inflated and from what I can find, the answer isn't all that difficult to understand.
You can use plt.ion()
if you want, but I found using plt.draw()
just as effective
For my specific project I'm plotting images, but you can use plot()
or scatter()
or whatever instead of figimage()
, it doesn't matter.
plt.figimage(image_to_show)
plt.draw()
plt.pause(0.001)
Or
fig = plt.figure()
...
fig.figimage(image_to_show)
fig.canvas.draw()
plt.pause(0.001)
If you're using an actual figure.
I used @krs013, and @Default Picture's answers to figure this out
Hopefully this saves someone from having launch every single figure on a separate thread, or from having to read these novels just to figure this out
If it's just a matter of easy reading, you could always define your own function :
is.not.null <- function(x) !is.null(x)
So you can use it all along your program.
is.not.null(3)
is.not.null(NULL)
Padding is a way to add kind of a margin inside the Div.
Just Use
div { padding-left: 20px; }
And to mantain the size, you would have to -20px from the original width of the Div.
You can set the following environment variable:
PIP_TARGET=/path/to/pip/dir
https://pip.pypa.io/en/stable/user_guide/#environment-variables
I definitely agree that this is perfect for an extension method, but I think it can be improved a bit.
public static string Remove(this string source, string remove, int firstN)
{
if(firstN <= 0 || string.IsNullOrEmpty(source) || string.IsNullOrEmpty(remove))
{
return source;
}
int index = source.IndexOf(remove);
return index < 0 ? source : source.Remove(index, remove.Length).Remove(remove, --firstN);
}
This does a bit of recursion which is always fun.
Here is a simple unit test as well:
[TestMethod()]
public void RemoveTwiceTest()
{
string source = "look up look up look it up";
string remove = "look";
int firstN = 2;
string expected = " up up look it up";
string actual;
actual = source.Remove(remove, firstN);
Assert.AreEqual(expected, actual);
}
Try declaring the unit of width:
e1.style.width = "400px"; // width in PIXELS
HttpClient
lives in the System.Net.Http
namespace.
You'll need to add:
using System.Net.Http;
And make sure you are referencing System.Net.Http.dll
in .NET 4.5.
The code posted doesn't appear to do anything with webClient
. Is there something wrong with the code that is actually compiling using HttpWebRequest
?
Update
To open the Add Reference dialog right-click on your project in Solution Explorer and select Add Reference.... It should look something like:
I came across this question while Googling for "git remove folder from tracking". The OP's question lead me to the answer. I am summarizing it here for future generations.
Question
How do I remove a folder from my git repository without deleting it from my local machine (i.e., development environment)?
Answer
Step 1. Add the folder path to your repo's root .gitignore
file.
path_to_your_folder/
Step 2. Remove the folder from your local git tracking, but keep it on your disk.
git rm -r --cached path_to_your_folder/
Step 3. Push your changes to your git repo.
The folder will be considered "deleted" from Git's point of view (i.e. they are in past history, but not in the latest commit, and people pulling from this repo will get the files removed from their trees), but stay on your working directory because you've used --cached
.
dotnet is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.
This may be a great start to support Linux.