Create a Branch
$ git branch branch1
$ git branch branch2
Checkout a Branch
git checkout command switch branches or restore working tree files
$ git checkout branchname
Renaming a Branch
$ git branch -m branch1 newbranchname
Delete a Branch
$ git branch -d branch-to-delete
$ git branch -D branch-to-delete
( force deletion without checking the merged status )Create and Switch Branch
$ git checkout -b branchname
Branches that are completely included
$ git branch --merged
************************** Branch Differences [ git diff branch1..branch2 ] ************************
Multiline difference$ git diff master..branch1
$ git diff --color-words branch1..branch2
I add my answer, similar to others but maybe it will be the quickest one to read and implement.
NOTE: Rebase is not needed in this case.
Assume I have a repo1
and two branches master
and dev-user
.
dev-user
is a branch done at a certain state of master
.
Now assume that both dev-user
and master
advance.
At some point I want dev-user
to get all the commits made in master
.
How do I do it?
I go first in my repository root folder
cd name_of_the_repository
then
git checkout master
git pull
git checkout dev-user
git pull
git merge master
git push
I hope this helps someone else in the same situation.
You can simply use decimal.ToString()
For two decimals
myDecimal.ToString("0.00");
For four decimals
myDecimal.ToString("0.0000");
This gives dot as decimal separator, and no thousand separator regardless of culture.
For me I received a 404 error on my websites NOT using IIS Express (using Local IIS) while running an application that WAS using IIS Express. If I would close the browser that was used to run IIS Express, then the 404 would go away. For me I had my IIS Express project calling into Local IIS services, so I converted the IIS Express project to use Local IIS and then everything worked. It seems that you can't run both a non-IIS Express and Local IIS website at the same time for some reason.
One possibility would be to add fixed width rows and columns to act as the padding / margin you are looking for.
You might also consider that you are constrained by the size of your container, and that a grid will become as large as the containing element or its specified width and height. You could simply use columns and rows with no width or height set. That way they default to evenly breaking up the total space within the grid. Then it would just be a mater of centering your elements vertically and horizontally within you grid.
Another method might be to wrap all grid elements in a fixed with single row & column grid that has a fixed size and margin. That your grid contains fixed width / height boxes which contain your actual elements.
from selenium import webdriver
from selenium.webdriver.common.proxy import *
myProxy = "86.111.144.194:3128"
proxy = Proxy({
'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy,
'sslProxy': myProxy,
'noProxy':''})
driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')
DateTime.Now.ToString("HH:mm:ss tt");
this gives it to you as a string.
Keep the secret in firebase database
and get from it when app starts ,
It is far better than calling a web service .
If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()
Does this work for you?
String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));
Following function allocates just enough memory to keep string representation of the given number and then writes the string representation into this area using standard sprintf
method.
char *itoa(long n)
{
int len = n==0 ? 1 : floor(log10l(labs(n)))+1;
if (n<0) len++; // room for negative sign '-'
char *buf = calloc(sizeof(char), len+1); // +1 for null
snprintf(buf, len+1, "%ld", n);
return buf;
}
Don't forget to free
up allocated memory when out of need:
char *num_str = itoa(123456789L);
// ...
free(num_str);
N.B. As snprintf copies n-1 bytes, we have to call snprintf(buf, len+1, "%ld", n) (not just snprintf(buf, len, "%ld", n))
Use \D
to match non-digit characters.
preg_replace('~\D~', '', $str);
In case you would like to find the area between 2 values of x mean = 1; standard deviation = 2; the probability of x between [0.5,2]
import scipy.stats
scipy.stats.norm(1, 2).cdf(2) - scipy.stats.norm(1,2).cdf(0.5)
You can use a dissolved out effect instead of ellipsis, pure CSS and looks more professional:
<div style="width: 293px; height:48px; overflow: hidden; ">
More than two line of text goes here-More than two line of text goes here
</div>
<div style="position: relative; top: -24px; width: 293px; height:24px;
background: linear-gradient(90deg, rgba(255,0,0,0) 40%, rgba(255,255,255,1) 99%);">
</div>
Here I have assumed your background color is white.
After reading all comments and answers I am going to explain an optimal solution for this problem. The best option is @rik's solution, so my improvement is base on his.
Instead of having to ask each FragmentClass like
if(FragmentClass1){
...
if(FragmentClass2){
...
}
Create your own interface, and maker your child fragments implement it, something like
public interface MyChildFragment {
void updateView(int position);
}
Then, you can do something like this to initiate and update your inner fragments.
Fragment childFragment = (Fragment) mViewPagerDetailsAdapter.instantiateItem(mViewPager,mViewPager.getCurrentItem());
if (childFragment != null) {
((MyChildFragment) childFragment).updateView();
}
P.S. Be careful where you put that code, if you call insatiateItem before the system actually create it the savedInstanceState
of your child fragment will be null therefor
public void onCreate(@Nullable Bundle savedInstanceState){
super(savedInstanceState)
}
Will crash your app.
Good luck
Use timeit. http://docs.python.org/library/timeit.html
I don't know if this is going to work but you can try this:
It's becoming pretty clear that the emulator team needs to do a better job of disseminating this information about how to use the emulator on AMD on Windows. This question comes up every week it seems.
First, uninstall HAXM.
Next, go here - https://developer.android.com/studio/run/emulator-acceleration#vm-windows and follow the instructions for Configuring VM acceleration with Windows Hypervisor Platform
Finally, if you get low framerates in your emulator instances, follow the instructions in the same page for Enabling Skia rendering for Android UI.
This isn't as elegant as sub-classing UIButton, however if you just want something quick - what I did was create custom button, then a 1px by 1px image with the colour I'd want the button to be, and set the background of the button to that image for the highlighted state - works for my needs.
Use this
long startTime = System.currentTimeMillis();
long elapsedTime = 0L.
while (elapsedTime < 2*60*1000) {
//perform db poll/check
elapsedTime = (new Date()).getTime() - startTime;
}
//Throw your exception
It's probably worth noting that IE won't cache css files called by other css files using the @import method. So, for example, if your html page links to "master.css" which pulls in "reset.css" via @import, then reset.css will not be cached by IE.
just use this,
utf8_encode($string);
you've to replace your $arr
with $string
.
I think it will work...try this.
Move the config files from src/main/java
to src/main/resources
.
Broadcast ping:
$ ping 192.168.1.255
PING 192.168.1.255 (192.168.1.255): 56 data bytes
64 bytes from 192.168.1.154: icmp_seq=0 ttl=64 time=0.104 ms
64 bytes from 192.168.1.51: icmp_seq=0 ttl=64 time=2.058 ms (DUP!)
64 bytes from 192.168.1.151: icmp_seq=0 ttl=64 time=2.135 ms (DUP!)
...
(Add a -b
option on Linux)
The most simple way of doing this is to use an ArrayList<Integer>
and use the add(int, T)
method.
List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
// Now, we will insert the number
list.add(4, 87);
remove leading and trailing white space in 2nd column
awk 'BEGIN{FS=OFS=","}{gsub(/^[ \t]+/,"",$2);gsub(/[ \t]+$/,"",$2)}1' input.txt
another way by one gsub:
awk 'BEGIN{FS=OFS=","} {gsub(/^[ \t]+|[ \t]+$/, "", $2)}1' infile
You can't insert comments inside xml tags.
Bad
<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib">
Good
<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib">
<!-- Cool comment -->
select * from Header where userID like '%''%'
Hope this helps.
You can get all keys / values and preserve the hierarchy with this
// get keys of an object or array
function getkeys(z){
var out=[];
for(var i in z){out.push(i)};
return out;
}
// print all inside an object
function allInternalObjs(data, name) {
name = name || 'data';
return getkeys(data).reduce(function(olist, k){
var v = data[k];
if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
else { olist.push(name + '.' + k + ' = ' + v); }
return olist;
}, []);
}
// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')
This is a modification on (https://stackoverflow.com/a/25063574/1484447)
I had the same problem but solved it with a switch statement switch(a value you are switching on) { case 1: the code you want to happen; case 2: the code you want to happen; default: return a value }
I created long-press-event (0.5k pure JavaScript) to solve this, it adds a long-press
event to the DOM.
Listen for a long-press
on any element:
// the event bubbles, so you can listen at the root level
document.addEventListener('long-press', function(e) {
console.log(e.target);
});
Listen for a long-press
on a specific element:
// get the element
var el = document.getElementById('idOfElement');
// add a long-press event listener
el.addEventListener('long-press', function(e) {
// stop the event from bubbling up
e.preventDefault()
console.log(e.target);
});
Works in IE9+, Chrome, Firefox, Safari & hybrid mobile apps (Cordova & Ionic on iOS/Android)
FWIW, @SergeyL's answer is great, but here is a slight variant for testing. Note the change in logical or to logical and.
main.c has a main wrapper like this:
#if !defined(TEST_SPI) && !defined(TEST_SERIAL) && !defined(TEST_USB)
int main(int argc, char *argv[]) {
// the true main() routine.
}
spi.c, serial.c and usb.c have main wrappers for their respective test code like this:
#ifdef TEST_USB
int main(int argc, char *argv[]) {
// the main() routine for testing the usb code.
}
config.h Which is included by all the c files has an entry like this:
// Uncomment below to test the serial
//#define TEST_SERIAL
// Uncomment below to test the spi code
//#define TEST_SPI
// Uncomment below to test the usb code
#define TEST_USB
My thoughts:
Dependecy Injection: pass collaborators as parameters to the constructors. Dependency Injection Framework: a generic and configurable factory to create the objects to pass as parameters to the constructors.
Simply
if(isset($_POST['filename'])){
$filename = $_POST['filename'];
echo $filename;
}
else{
echo "POST filename is not assigned";
}
Go to view and press "Switch to scale mode" which will adjust the virtual screen when you adjust the application.
FWIW,
Poor mans security folder (to protect a public shared folder from little prying eyes ;) )
mkdir -p {0..9}/{0..9}/{0..9}/{0..9}
Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.
If you don't want to deal with security and want to make it as exposed (aka "convenient") as possible for short term, and|or don't have ssh/telnet or key generation on all your hosts, you can can hack a one-liner together with netcat. Write a command to your target computer's port over the network and it will run it. Then you can block access to that port to a few "trusted" users or wrap it in a script that only allows certain commands to run. And use a low privilege user.
mkfifo /tmp/netfifo; nc -lk 4201 0</tmp/netfifo | bash -e &>/tmp/netfifo
This one liner reads whatever string you send into that port and pipes it into bash to be executed. stderr & stdout are dumped back into netfifo and sent back to the connecting host via nc.
To run a command remotely:
echo "ls" | nc HOST 4201
I faced the same problem. Solution on windows:
mkdir .ssh
This will create a .ssh folder.
\dt (no * required) -- will list all tables for an existing database you are already connected to. Also useful to note:
\d [table_name] -- will show all columns for a given table including type information, references and key constraints.
The simplest way to modify all files of a project at once (batch) is through Line Endings Unify package:
OR (instead of 3.) copy:
{
"keys": ["ctrl+alt+l"],
"command": "line_endings_unify"
},
to the User array (right pane, after the opening [
) in Preferences -> KeyBindings + press Ctrl+Alt+L.
As mentioned in another answer:
The Carriage Return (CR) character (
0x0D
,\r
) [...] Early Macintosh operating systems (OS-9 and earlier).The Line Feed (LF) character (
0x0A
,\n
) [...] UNIX based systems (Linux, Mac OSX)The End of Line (EOL) sequence (
0x0D 0x0A
,\r\n
) [...] (non-Unix: Windows, Symbian OS).
If you have node_modules, build or other auto-generated folders, delete them before running the package.
When you run the package:
js,jsx
).\n
.Old question, modern answer. Using object destructuring, an ECMAScript 6 feature, it's as simple as:
const { a, ...rest } = { a: 1, b: 2, c: 3 };
Or with the questions sample:
const myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
const { regex, ...newObject } = myObject;
console.log(newObject);
You can see it in action in the Babel try-out editor.
Edit:
To reassign to the same variable, use a let
:
let myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
({ regex, ...myObject } = myObject);
console.log(myObject);
Hopefully I'm not late for the party.
Encountered this using Eclipse Kepler and Maven 3.1.
The solution is to use a JDK and not a JRE for your Eclipse project. Make sure to try maven clean and test from eclipse just to download missing jars.
If you use Spring you can:
1) create a log4j configuration file, e.g. "/WEB-INF/classes/log4j-myapp.properties" DO NOT name it "log4j.properties"
Example:
log4j.rootLogger=ERROR, stdout, rollingFile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=${myWebapp-instance-root}/WEB-INF/logs/application.log
log4j.appender.rollingFile.MaxFileSize=512KB
log4j.appender.rollingFile.MaxBackupIndex=10
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.rollingFile.Encoding=UTF-8
We'll define "myWebapp-instance-root" later on point (3)
2) Specify config location in web.xml:
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j-myapp.properties</param-value>
</context-param>
3) Specify a unique variable name for your webapp's root, e.g. "myWebapp-instance-root"
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myWebapp-instance-root</param-value>
</context-param>
4) Add a Log4jConfigListener:
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
If you choose a different name, remember to change it in log4j-myapp.properties, too.
See my article (Italian only... but it should be understandable): http://www.megadix.it/content/configurare-path-relativi-log4j-utilizzando-spring
UPDATE (2009/08/01) I've translated my article to English: http://www.megadix.it/node/136
Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
He explains using the following:
Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.
Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.
[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.
If you're looking for the equivalent to background-size: cover
for video
.
video {
object-fit: cover;
}
This will fill the container without distorting the video.
PS: I'm extending on Leo Yu's answer here.
If you want to group the results based on a column and take the count based on the same, you can run the query as,
$sql = "SELECT COLUMNNAME,
COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'New',
COUNT(CASE WHEN COLUMNNAME IN ('YOURCONDITION') then 1 ELSE NULL END) as 'ACCPTED',
from TABLENAME
GROUP BY COLUMNANME";
This can be implemented immutably and with a single traversal by folding through the collection as follows.
val map = c.foldLeft(Map[P, T]()) { (m, t) => m + (t.getP -> t) }
The solution works because adding to an immutable Map returns a new immutable Map with the additional entry and this value serves as the accumulator through the fold operation.
The tradeoff here is the simplicity of the code versus its efficiency. So, for large collections, this approach may be more suitable than using 2 traversal implementations such as applying map
and toMap
.
You should use Adaptive hashing like http://en.wikipedia.org/wiki/Bcrypt for securing passwords
Spring (nowadays) makes it easy to add Spring to a project by using just one dependency, e.g.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
This will resolve to
[INFO] The following files have been resolved:
[INFO] aopalliance:aopalliance:jar:1.0:compile
[INFO] commons-logging:commons-logging:jar:1.1.1:compile
[INFO] org.springframework:spring-aop:jar:3.1.2.RELEASE:compile
[INFO] org.springframework:spring-asm:jar:3.1.2.RELEASE:compile
[INFO] org.springframework:spring-beans:jar:3.1.2.RELEASE:compile
[INFO] org.springframework:spring-context:jar:3.1.2.RELEASE:compile
[INFO] org.springframework:spring-core:jar:3.1.2.RELEASE:compile
[INFO] org.springframework:spring-expression:jar:3.1.2.RELEASE:compile
Have a look at the Spring Framework documentation page for more information.
If you paste the string in server-side into the html don't need to do nothing:
For plain java in jsp:
var jsonObj=<%=jsonStringInJavaServlet%>;
For jsp width struts:
var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;
You can put up all your JS like this, so it doesn't execute before your HTML is ready
$(document).ready(function() {
// some code here
});
Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload
You can try also like this:
- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
for (id textField in self.view.subviews) {
if ([textField isKindOfClass:[UITextField class]] && [textField isFirstResponder]) {
[textField resignFirstResponder];
}
}
}
I didn't try it but it seems a good solution
Actually looking at other areas, if you open with _blank it keeps the sessionStorage as long as you're opening the tab when the parent is open:
In this link, there's a good jsfiddle to test it. sessionStorage on new window isn't empty, when following a link with target="_blank"
If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.
Well, i guess M represent the mantissa. Decimal can be used to save money, but it doesn't mean, decimal only used for money.
In WordPress, this helped me:
wp-admin/
wp-includes/
/wp-content/*
!wp-content/plugins/
/wp-content/plugins/*
!/wp-content/plugins/plugin-name/
!/wp-content/plugins/plugin-name/*.*
!/wp-content/plugins/plugin-name/**
You can simply use the data-interval
attribute of the carousel
class.
It's default value is set to data-interval="3000"
i.e 3seconds.
All you need to do is set it to your desired requirements.
I think double quotes works too:
SELECT "Business Name","Other Name" FROM your_Table
But I only tested on SQL Server NOT mySQL in case someone work with MS SQL Server.
If you only want to Close the form than you can use this.Close(); else if you want the whole application to be closed use Application.Exit();
How about:
rm -rf "$(pwd -P)"/*
You can assert that the two Set
s are equal to one another, which invokes the Set
equals()
method.
public class SimpleTest {
private Set<String> setA;
private Set<String> setB;
@Before
public void setUp() {
setA = new HashSet<String>();
setA.add("Testing...");
setB = new HashSet<String>();
setB.add("Testing...");
}
@Test
public void testEqualSets() {
assertEquals( setA, setB );
}
}
This @Test
will pass if the two Set
s are the same size and contain the same elements.
Use the Socket()
constructor, and connect(SocketAddress endpoint, int timeout)
method instead.
In your case it would look something like:
Socket socket = new Socket();
socket.connect(new InetSocketAddress(ipAddress, port), 1000);
Quoting from the documentation
connect
public void connect(SocketAddress endpoint, int timeout) throws IOException
Connects this socket to the server with a specified timeout value. A timeout of zero is interpreted as an infinite timeout. The connection will then block until established or an error occurs.
Parameters:
endpoint
- the SocketAddress
timeout
- the timeout value to be used in milliseconds.Throws:
IOException
- if an error occurs during the connection
SocketTimeoutException
- if timeout expires before connecting
IllegalBlockingModeException
- if this socket has an associated channel, and the channel is in non-blocking mode
IllegalArgumentException
- if endpoint is null or is a SocketAddress subclass not supported by this socketSince: 1.4
You can't - in theory. The whole point of a hash is that it's one way only. This means that if someone manages to get the list of hashes, they still can't get your password. Additionally it means that even if someone uses the same password on multiple sites (yes, we all know we shouldn't, but...) anyone with access to the database of site A won't be able to use the user's password on site B.
The fact that MD5 is a hash also means it loses information. For any given MD5 hash, if you allow passwords of arbitrary length there could be multiple passwords which produce the same hash. For a good hash it would be computationally infeasible to find them beyond a pretty trivial maximum length, but it means there's no guarantee that if you find a password which has the target hash, it's definitely the original password. It's astronomically unlikely that you'd see two ASCII-only, reasonable-length passwords that have the same MD5 hash, but it's not impossible.
MD5 is a bad hash to use for passwords:
I'm not a security expert, so won't make a concrete recommendation beyond "Don't roll your own authentication system." Find one from a reputable supplier, and use that. Both the design and implementation of security systems is a tricky business.
add {3,5}
to your expression which means length between 3 to 5
/^([a-zA-Z0-9_-]){3,5}$/
Here's a batch file, called base64encode.bat, that encodes base64.
@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con
(
set base64tmp=base64.tmp
certutil -encode "%1" %base64tmp% > nul
findstr /v /c:- %base64tmp%
erase %base64tmp%
) > %base64out%
as @Pointy said you don't cache images with javascript, the browser does that. so this may be what you are asking for and may not be... but you can preload images using javascript. By putting all of the images you want to preload into an array and putting all of the images in that array into hidden img elements, you effectively preload (or cache) the images.
var images = [
'/path/to/image1.png',
'/path/to/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
Oldapps.com has old versions of Chrome available for download, and they’re the standalone versions, so combined with @SamMeiers’ answer, these work a treat.
The Google Chrome support forum has some good discussion of getting old versions of Chrome.
Set auto margins on the inner div:
<div id="header" style="width:864px;">
<div id="centered" style="margin: 0 auto; width:855px;"></div>
</div>
Alternatively, text align center the parent, and force text align left on the inner div:
<div id="header" style="width:864px;text-align: center;">
<div id="centered" style="text-align: left; width:855px;"></div>
</div>
For Python 3 above, use:
sudo apt-get install python3-dateutil
Actually, it feels like swift is trying to promote strings to be treated less like objects and more like values. However this doesn't mean under the hood swift doesn't treat strings as objects, as am sure you all noticed that you can still invoke methods on strings and use their properties.
For example:-
//example of calling method (String to Int conversion)
let intValue = ("12".toInt())
println("This is a intValue now \(intValue)")
//example of using properties (fetching uppercase value of string)
let caUpperValue = "ca".uppercaseString
println("This is the uppercase of ca \(caUpperValue)")
In objectC you could pass the reference to a string object through a variable, on top of calling methods on it, which pretty much establishes the fact that strings are pure objects.
Here is the catch when you try to look at String as objects, in swift you cannot pass a string object by reference through a variable. Swift will always pass a brand new copy of the string. Hence, strings are more commonly known as value types in swift. In fact, two string literals will not be identical (===). They are treated as two different copies.
let curious = ("ca" === "ca")
println("This will be false.. and the answer is..\(curious)")
As you can see we are starting to break aways from the conventional way of thinking of strings as objects and treating them more like values. Hence .isEqualToString which was treated as an identity operator for string objects is no more a valid as you can never get two identical string objects in Swift. You can only compare its value, or in other words check for equality(==).
let NotSoCuriousAnyMore = ("ca" == "ca")
println("This will be true.. and the answer is..\(NotSoCuriousAnyMore)")
This gets more interesting when you look at the mutability of string objects in swift. But thats for another question, another day. Something you should probably look into, cause its really interesting. :) Hope that clears up some confusion. Cheers!
I faced the same problem.Ask your friend to add you as a collaborator by going to his repo settings and adding a new collaborator.
You will recieve an invite email ,accept it.Then you are good to go. Just make sure that you have added right remote.
The be-all-end-all, for no selecting or dragging, with all browser prefixes:
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
user-select: none;
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
-ms-user-drag: none;
user-drag: none;
You can also set the draggable
attribute to false
. You can do this with inline HTML: draggable="false"
, with Javascript: elm.draggable = false
, or with jQuery: elm.attr('draggable', false)
.
You can also handle the onmousedown
function to return false
. You can do this with inline HTML: onmousedown="return false"
, with Javascript: elm.onmousedown=()=>return false;
, or with jQuery: elm.mousedown(()=>return false)
This should work
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
da.Fill(ds);
if(ds.Tables.Count > 0)
{
// enter code here
}
You have the field in a string, so you'll need to convert it to datetime
order by CONVERT(datetime, EventDate ) desc
This snippet could help you with it in a few lines of jQuery 1.9+: http://jsfiddle.net/4MBUG/2/
$('input[type=button]').on('click', function() {
var cursorPos = $('#text').prop('selectionStart');
var v = $('#text').val();
var textBefore = v.substring(0, cursorPos);
var textAfter = v.substring(cursorPos, v.length);
$('#text').val(textBefore + $(this).val() + textAfter);
});
just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.
Controller:
ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);
Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)
Then this is my view to render it:
<div class="editor-label">
@Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
@Html.DropDownList("ActionStatusId")
@Html.ValidationMessageFor(model => model.ActionStatusId)
</div>
I think it is pretty simple, I hope this helps! :)
Import mplot3d whole to use "projection = '3d'".
Insert the command below in top of your script. It should run fine.
from mpl_toolkits import mplot3d
After trying @regeter's solution and seeing it didn't solve my problem when I was searching for a foreign/primary key to see all tables/columns where it exists, it didn't work. After reading how it failed for another who tried to use a unique identifier, I have made the modifications and here is the updated result: (works with both int, and guids... you will see how to easily extend)
CREATE PROC [dbo].[SearchAllTables_Like]
(
@SearchStr nvarchar(100)
)
AS
BEGIN
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Tested on: SQL Server 7.0 and SQL Server 2000
-- Date modified: 28th July 2002 22:50 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('guid', 'int', 'char', 'varchar', 'nchar', 'nvarchar')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO #Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM #Results
END
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
[Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]
You can have an HTML anchor (a
tag) without an href
attribute. Leave off the href
attribute & it won't link to anything:
<a>link</a>
I found this solution in "Super useful bits of PHP, Form and JavaScript code" at Skytopia.
Inside "page1.php" or "page1.html":
// Send the variables myNumber=1 and myFruit="orange" to the new PHP page...
<a href="page2c.php?myNumber=1&myFruit=orange">Send variables via URL!</a>
//or as I needed it.
<a href='page2c.php?myNumber={$row[0]}&myFruit={$row[1]}'>Send variables</a>
Inside "page2c.php":
<?php
// Retrieve the URL variables (using PHP).
$num = $_GET['myNumber'];
$fruit = $_GET['myFruit'];
echo "Number: ".$num." Fruit: ".$fruit;
?>
One can remove folder with cached jars.
In my case, on Mac the library was cached at path:
/Users/MY_NAME/.gradle/caches/modules-2/files-2.1/cached-library-to-remove
I removed the cached library folder ("cached-library-to-remove" in above example), deleted the build folder of my project and compiled again. Fresh library was downloaded then.
You can also save the bmp in a var like this:
var bmp = Resources.ImageName;
hope it helps!
This should work :
str = str.replace(/[^a-z0-9-]/g, '');
Everything between the indicates what your are looking for
/
is here to delimit your pattern so you have one to start and one to end[]
indicates the pattern your are looking for on one specific character^
indicates that you want every character NOT corresponding to what followsa-z
matches any character between 'a' and 'z' included0-9
matches any digit between '0' and '9' included (meaning any digit)-
the '-' characterg
at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole stringThen your expression is delimited by /
before and after.
So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
If an escape character is to be added at the beginning or the end like "JAVA"
, then use:
INSERT INTO STUDENT(name, class_id) VALUES ('Samantha', ''||chr(34)||'JAVA'||chr(34)||'');
Old question, but thought I'd share my solution anyway. Pretty simple.
dicta_set = set(dicta.items()) # creates a set of tuples (k/v pairs)
dictb_set = set(dictb.items())
setdiff = dictb_set.difference(dicta_set) # any set method you want for comparisons
for k, v in setdiff: # unpack the tuples for processing
print(f"k/v differences = {k}: {v}")
This code creates two sets of tuples representing the k/v pairs. It then uses a set method of your choosing to compare the tuples. Lastly, it unpacks the tuples (k/v pairs) for processing.
Is there a way ( I mean how do I ) set a system property in a maven project? I want to access a property from my test [...]
You can set system properties in the Maven Surefire Plugin configuration (this makes sense since tests are forked by default). From Using System Properties:
<project>
[...]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<systemPropertyVariables>
<propertyName>propertyValue</propertyName>
<buildDirectory>${project.build.directory}</buildDirectory>
[...]
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
[...]
</project>
and my webapp ( running locally )
Not sure what you mean here but I'll assume the webapp container is started by Maven. You can pass system properties on the command line using:
mvn -DargLine="-DpropertyName=propertyValue"
Update: Ok, got it now. For Jetty, you should also be able to set system properties in the Maven Jetty Plugin configuration. From Setting System Properties:
<project>
...
<plugins>
...
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<configuration>
...
<systemProperties>
<systemProperty>
<name>propertyName</name>
<value>propertyValue</value>
</systemProperty>
...
</systemProperties>
</configuration>
</plugin>
</plugins>
</project>
This may help you.
?php
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res))
{
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
// Assuming $list['options'] is a coma seperated options string
$arr=explode(",",$list['options']);
<?php foreach ($arr as $value) { ?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php } >
</select>
<?php
}
?>
Try
apt-get -d install <packages>
It is documented in man apt-get
.
Just for clarification; the downloaded packages are located in the apt package cache at
/var/cache/apt/archives
I needed to use this as a cell function (like SUM
or VLOOKUP
) and found that it was easy to:
Create the following function either in workbook or in its own module:
Function REGPLACE(myRange As Range, matchPattern As String, outputPattern As String) As Variant
Dim regex As New VBScript_RegExp_55.RegExp
Dim strInput As String
strInput = myRange.Value
With regex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = matchPattern
End With
REGPLACE = regex.Replace(strInput, outputPattern)
End Function
Then you can use in cell with =REGPLACE(B1, "(\w) (\d+)", "$1$2")
(ex: "A 243" to "A243")
SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.
One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.
so exclusively open SOAP Port in Firewalls
Please take a look at Xamarin. They have an extension for Visual Studio (http://xamarin.com/visual-studio).
Taken from their site:
Xamarin provides Visual Studio add-ins so that you can develop your iOS, Android and Windows apps all in a single solution. The Xamarin extensions support building, deploying, and debugging on simulator or device.
For your question as asked
Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))
If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA
I had this error, I looked into a log file C:\...\mysql\data\VM-IIS-Server.err and found this
2016-06-07 17:56:07 160c InnoDB: Error: unable to create temporary file; errno: 2
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' init function returned error.
2016-06-07 17:56:07 3392 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2016-06-07 17:56:07 3392 [ERROR] Unknown/unsupported storage engine: InnoDB
2016-06-07 17:56:07 3392 [ERROR] Aborting
The first line says "unable to create temporary file", it sounds like "insufficient privileges", first I tried to give access to mysql folder for my current user - no effect, then after some wandering around I came up to control panel->Administration->Services->Right Clicked MysqlService->Properties->Log On, switched to "This account", entered my username/password, clicked OK, and it woked!
Here's an example of how you'd use filter
within your AngularJS JavaScript (rather than in an HTML element).
In this example, we have an array of Country records, each containing a name and a 3-character ISO code.
We want to write a function which will search through this list for a record which matches a specific 3-character code.
Here's how we'd do it without using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
for (var i = 0; i < $scope.CountryList.length; i++) {
if ($scope.CountryList[i].IsoAlpha3 == CountryCode) {
return $scope.CountryList[i];
};
};
return null;
};
Yup, nothing wrong with that.
But here's how the same function would look, using filter
:
$scope.FindCountryByCode = function (CountryCode) {
// Search through an array of Country records for one containing a particular 3-character country-code.
// Returns either a record, or NULL, if the country couldn't be found.
var matches = $scope.CountryList.filter(function (el) { return el.IsoAlpha3 == CountryCode; })
// If 'filter' didn't find any matching records, its result will be an array of 0 records.
if (matches.length == 0)
return null;
// Otherwise, it should've found just one matching record
return matches[0];
};
Much neater.
Remember that filter
returns an array as a result (a list of matching records), so in this example, we'll either want to return 1 record, or NULL.
Hope this helps.
const input = document.getElementById('input')_x000D_
_x000D_
input.addEventListener('change', (event) => {_x000D_
const target = event.target_x000D_
if (target.files && target.files[0]) {_x000D_
_x000D_
/*Maximum allowed size in bytes_x000D_
5MB Example_x000D_
Change first operand(multiplier) for your needs*/_x000D_
const maxAllowedSize = 5 * 1024 * 1024;_x000D_
if (target.files[0].size > maxAllowedSize) {_x000D_
// Here you can ask your users to load correct file_x000D_
target.value = ''_x000D_
}_x000D_
}_x000D_
})
_x000D_
<input type="file" id="input" />
_x000D_
If you need to validate file type, write in comments below and I'll share my solution.
(Spoiler: accept
attribute is not bulletproof solution)
in my case (Angular 6+), I inherited from MatTableDataSource
to create MyDataSource
. Without calling after this.data = someArray
this.entitiesSubject.next(this.data as T[])
data where not displayed
export class MyDataSource<T extends WhateverYouWant> extends MatTableDataSource<T> {
private entitiesSubject = new BehaviorSubject<T[]>([]);
loadDataSourceData(someArray: T[]){
this.data = someArray //whenever it comes from an API asyncronously or not
this.entitiesSubject.next(this.data as T[])// Otherwise data not displayed
}
public connect(): BehaviorSubject<T[]> {
return this.entitiesSubject
}
}//end Class
If you really gotta be fast (not that I believe you do):
char[] chars = sourceDate.toCharArray();
chars[10] = ' ';
String targetDate = new String(chars, 0, 19);
I have a convention of naming xibs with views in them the same as the view. Same as one would do for a view controller. Then, I don't have to write out class names in code. I load a UIView from a nib file with the same name.
Example for a class called MyView.
In your code, create a new MyView like this:
MyView *myView = [MyView nib_viewFromNibWithOwner:owner];
Here's the category for this:
@implementation UIView (nib)
+ (id) nib_viewFromNib {
return [self nib_viewFromNibWithOwner:nil];
}
+ (id) nib_viewFromNibWithOwner:(id)owner {
NSString *className = NSStringFromClass([self class]);
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:className owner:owner options:nil];
UIView *view = nil;
for(UIView *v in nib) {
if ([v isKindOfClass:[self class]]) {
view = v;
break;
}
}
assert(view != nil && "View for class not found in nib file");
[view nib_viewDidLoad];
return view;
}
// override this to do custom setup
-(void)nib_viewDidLoad {
}
I'd then wire up buttons with actions from the controller I am using, and set things on labels using the outlets in my custom view subclass.
You'll need to consider this in context of the application. In general, you should design an application, not a database (the database simply being part of the application).
Consider how your application should respond to various cases.
The default action is to restrict (i.e. not permit) the operation, which is normally what you want as it prevents stupid programming errors. However, on DELETE CASCADE can also be useful. It really depends on your application and how you intend to delete particular objects.
Personally, I'd use InnoDB because it doesn't trash your data (c.f. MyISAM, which does), rather than because it has FK constraints.
According to my machine, sorting a long long
vector of [1..3000000] using the first method takes around 4 seconds, while using the second takes about twice the time. That says something, obviously, but I don't understand why either. Just think this would be helpful.
Same thing reported here.
As said by Xeo, with -O3
they use about the same time to finish.
The explanation given by Merlyn above is pretty complete. However, I would like to elaborate on coding standards.
When several IF's are chained, the final command is executed when all the previous conditions are meet; this is equivalent to an AND operator. I used this behavior now and then, but I clearly indicate what I intend to do via an auxiliary Batch variable called AND:
SET AND=IF
IF EXIST somefile.txt %AND% EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
Of course, this is NOT a true And operator and must not be used in combination with ELSE clause. This is just a programmer aid to increase the legibility of an instruction that is rarely used.
When I write Batch programs I always use several auxiliary variables that I designed with the sole purpose of write more readable code. For example:
SET AND=IF
SET THEN=(
SET ELSE=) ELSE (
SET NOELSE=
SET ENDIF=)
SET BEGIN=(
SET END=)
SET RETURN=EXIT /B
These variables aids in writting Batch programs in a much clearer way and helps to avoid subtle errors, as Merlyn suggested. For example:
IF EXIST "somefile.txt" %THEN%
IF EXIST "someotherfile.txt" %THEN%
SET var="somefile.txt,someotherfile.txt"
%NOELSE%
%ENDIF%
%NOELSE%
%ENDIF%
IF EXIST "%~1" %THEN%
SET "result=%~1"
%ELSE%
SET "result="
%ENDIF%
I even have variables that aids in writting WHILE-DO and REPEAT-UNTIL like constructs. This means that Batch variables may be used in some degree as preprocessor values.
I can see that documentation as far back as Java 1.2.
While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String
, so changing it would count as breaking existing contracts.
Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String
is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.
This is the easiest way to do it:
public function selectAllUsersByRole($userRole, $selector) {
$this->userRole = $userLevel;
$this->selector = $selector;
$sql = "SELECT * FROM users WHERE role <= ? AND del_stat = 0";
$stm = $this->connect()->prepare($sql); // Connect function in Dbh connect to database file
$stm->execute([$this->userRole]); // This is PHP 7. Use array($this->userRole) for PHP 5
$usersIdArray = array();
$usersFNameArray = array();
$usersLNameArray = array();
if($stm->rowCount()) {
while($row = $stm->fetch()) {
array_push($usersIdArray, $row['id']);
array_push($usersFNameArray, $row['f_name']);
array_push($usersLNameArray, $row['l_name']);
// You can return only $row['id'] or f_name or ...
// I used the array because it's most used.
}
}
if($this->selector == 1) {
return $usersIdArray;
}elseif($this->selector == 2) {
return $usersFNameArray;
}elseif($this->selector == 3) {
return $usersLNameArray;
}
}
How can we call this function?
$idData = $selectAllUsers->selectAllUsersByLevel($userRole, 0);
print_r($idData);
$idFName = $selectAllUsers->selectAllUsersByLevel($userRole, 1);
print_r($idFname);
That's it. Very easy.
On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.
When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).
It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.
So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.
Or try to check your mainActivity.xml you make sure that this one
xmlns:app="http://schemas.android.com/apk/res-auto"here
is included
Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.
The string class offers a replace method for the string object you want to update:
Example:
$myString = $myString.replace(".","")
The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.
Example:
[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)
I hope this addresses the issue you initially brought up in your question.
Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs
for the same like this way
import {Observable} from 'rxjs/Rx';
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
also you can handel error (with err block) that is throw by catch block while .map
function,
like this -
...
.subscribe(res=>{....}
err => {//handel here});
as required for any status without checking particluar one you can try this: -
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status < 400 || error.status ===500) {
return Observable.throw(new Error(error.status));
}
})
.subscribe(res => {...},
err => {console.log(err)} );
Solution:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline-block;
}
You must set parent font size to 0
I think it is much easier to just use a unicode character to get the job done. You can look through arrows by googling either Unicode Triangles or Unicode Arrows. Starting with iOS6 Apple changed the character to be an emoji character with a border. To disable the border I add the 0xFE0E Unicode Variation Selector.
NSString *backArrowString = @"\U000025C0\U0000FE0E"; //BLACK LEFT-POINTING TRIANGLE PLUS VARIATION SELECTOR
UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:backArrowString style:UIBarButtonItemStylePlain target:nil action:nil];
self.navigationItem.leftButtonItem = backBarButtonItem;
The code block is just for the demo. It would work in any button that accepts an NSString.
For a full list of characters search Google for Unicode character and what you want. Here is the entry for Black Left-Pointing Triangle.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Browser.IsMobileDevice == true)
{
Response.Redirect("Mobile//home.aspx");
}
}
This example works in asp.net
The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.
Examples:
// firstName has a hard-coded value of "hello world"
string firstName = "hello world";
// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();
A hard-coded constant[1]:
float areaOfCircle(int radius)
{
float area = 0;
area = 3.14*radius*radius; // 3.14 is a hard-coded value
return area;
}
Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.
- Hard Coding “Hard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.
The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.- Soft Coding
If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.
In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.
In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.
Sources and Citations:
1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid
Further Reading:
Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding
As of Ruby 2.5 you can use delete_prefix
or delete_prefix!
to achieve this in a readable manner.
In this case "[12,23,987,43".delete_prefix("[")
.
More info here:
'invisible'.delete_prefix('in') #=> "visible"
'pink'.delete_prefix('in') #=> "pink"
N.B. you can also use this to remove items from the end of a string with delete_suffix
and delete_suffix!
'worked'.delete_suffix('ed') #=> "work"
'medical'.delete_suffix('ed') #=> "medical"
Edit:
Using the Tin Man's benchmark setup, it looks pretty quick too (under the last two entries delete_p
and delete_p!
). Doesn't quite pip the previous faves for speed, though is very readable.
2.5.0
user system total real
[0] 0.174766 0.000489 0.175255 ( 0.180207)
[/^./] 0.318038 0.000510 0.318548 ( 0.323679)
[/^\[/] 0.372645 0.001134 0.373779 ( 0.379029)
sub+ 0.460295 0.001510 0.461805 ( 0.467279)
sub 0.498351 0.001534 0.499885 ( 0.505729)
gsub 1.669837 0.005141 1.674978 ( 1.682853)
[1..-1] 0.199840 0.000976 0.200816 ( 0.205889)
slice 0.279661 0.000859 0.280520 ( 0.285661)
length 0.268362 0.000310 0.268672 ( 0.273829)
eat! 0.341715 0.000524 0.342239 ( 0.347097)
reverse 0.335301 0.000588 0.335889 ( 0.340965)
delete_p 0.222297 0.000832 0.223129 ( 0.228455)
delete_p! 0.225798 0.000747 0.226545 ( 0.231745)
Use a git endpoint instead of a package name:
bower install https://github.com/jquery/jquery.git#2.0.3
cd ~ && apt-get source coreutils && ls -d coreutils*
You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo
assuming your downloading to a location you own.
Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.
Html
<div id="xx"></div>
Javascript:
if (document.getElementById('xx') !=null)
console.log('it exists!');
if (document.getElementById('xxThisisNotAnElementOnThePage') ==null)
console.log('does not exist!');
Forget about ASCII code checks, use isdigit
or isnumber
(see man isnumber
). The first function checks whether the character is 0–9, the second one also accepts various other number characters depending on the current locale.
There may even be better functions to do the check – the important lesson is that this is a bit more complex than it looks, because the precise definition of a “number string” depends on the particular locale and the string encoding.
It can be a mathematical convention in the definition of an interval where square brackets mean "extremal inclusive" and round brackets "extremal exclusive".
Use the new jQuery on function in 1.7.1 -
We can use following code
textBox1.DataBindings.Add("Text", model, "Name", false, DataSourceUpdateMode.OnPropertyChanged);
Where
"Text"
– the property of textbox model
– the model object enter code here "Name"
– the value of model which to bind the textbox.I just encountered this issue as well, and long story short my API was returning a string type and not JSON. So it looked exactly the same when you printed it to the log however whenever I tried to access the properties it gave me an undefined error.
API Code:
var response = JsonConvert.DeserializeObject<StatusResult>(string Of object);
return Json(response);
previously I was just returning:
return Json(string Of object);
This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.
If you're using SQL Server, use the SqlBulkCopy class.
For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.
The same thing happened to me. Here is what I did in order to get it successfully installed. I downloaded KB2999226 update from Microsofts website here: https://www.microsoft.com/en-us/download/details.aspx?id=49093
After installing this package, I started the installation process again. That worked for me.
The mysql_upgrade worked for me as well:
# mysql_upgrade -u root -p --force
# systemctl restart mysqld
Regards, MSz.
It depends on the compile context (See Example below).
out
and ref
both denote variable passing by reference, yet ref
requires the variable to be initialized before being passed, which can be an important difference in the context of Marshaling (Interop: UmanagedToManagedTransition or vice versa)
Do not confuse the concept of passing by reference with the concept of reference types. The two concepts are not the same. A method parameter can be modified by ref regardless of whether it is a value type or a reference type. There is no boxing of a value type when it is passed by reference.
From the official MSDN Docs:
out
:The out keyword causes arguments to be passed by reference. This is similar to the ref keyword, except that ref requires that the variable be initialized before being passed
ref
:The ref keyword causes an argument to be passed by reference, not by value. The effect of passing by reference is that any change to the parameter in the method is reflected in the underlying argument variable in the calling method. The value of a reference parameter is always the same as the value of the underlying argument variable.
We can verify that the out and ref are indeed the same when the argument gets assigned:
CIL Example:
Consider the following example
static class outRefTest{
public static int myfunc(int x){x=0; return x; }
public static void myfuncOut(out int x){x=0;}
public static void myfuncRef(ref int x){x=0;}
public static void myfuncRefEmpty(ref int x){}
// Define other methods and classes here
}
in CIL, the instructions of myfuncOut
and myfuncRef
are identical as expected.
outRefTest.myfunc:
IL_0000: nop
IL_0001: ldc.i4.0
IL_0002: starg.s 00
IL_0004: ldarg.0
IL_0005: stloc.0
IL_0006: br.s IL_0008
IL_0008: ldloc.0
IL_0009: ret
outRefTest.myfuncOut:
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: stind.i4
IL_0004: ret
outRefTest.myfuncRef:
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldc.i4.0
IL_0003: stind.i4
IL_0004: ret
outRefTest.myfuncRefEmpty:
IL_0000: nop
IL_0001: ret
nop: no operation, ldloc: load local, stloc: stack local, ldarg: load argument, bs.s: branch to target....
(See: List of CIL instructions )
you need to use add class open
in <div class="btn-group open">
and in li
add class="active"
I think it's possible in Java 9:
animalMap.entrySet().stream()
.forEach(
pair -> Optional.ofNullable(pair.getValue())
.ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))
);
Need the ifPresentOrElse for it to work though. (I think a for loop looks better.)
You are using the --noImplicitAny
and TypeScript doesn't know about the type of the Users
object. In this case, you need to explicitly define the user
type.
Change this line:
let user = Users.find(user => user.id === query);
to this:
let user = Users.find((user: any) => user.id === query);
// use "any" or some other interface to type this argument
Or define the type of your Users
object:
//...
interface User {
id: number;
name: string;
aliases: string[];
occupation: string;
gender: string;
height: {ft: number; in: number;}
hair: string;
eyes: string;
powers: string[]
}
//...
const Users = <User[]>require('../data');
//...
openssl rsa -in privkey.pem -out private.key
does the job.
.NET Core is an open source and cross platform version of .NET Framework.
OS X is "LP64". This means that:
int
is always 32-bits.
long long
is always 64-bits.
NSInteger
and long
are always pointer-sized. That means they're 32-bits on 32-bit systems, and 64 bits on 64-bit systems.
The reason NSInteger exists is because many legacy APIs incorrectly used int
instead of long
to hold pointer-sized variables, which meant that the APIs had to change from int
to long
in their 64-bit versions. In other words, an API would have different function signatures depending on whether you're compiling for 32-bit or 64-bit architectures. NSInteger
intends to mask this problem with these legacy APIs.
In your new code, use int
if you need a 32-bit variable, long long
if you need a 64-bit integer, and long
or NSInteger
if you need a pointer-sized variable.
Step 1, delete all the *.DS_store
files. One can run
git rm -f *.DS_Store
but be aware that rm -f
can be a bit dangerous if you have a typo!
Step two: add
*.DS_Store
.DS_Store
to .gitignore. This worked for me!
I personally suggest to use the autoNumeric plugin from http://www.decorplanit.com/plugin/ - it supports all different variations like prefix/suffix handling, currency handling, negative value formatting, min, max etc.
I have got the same error, but in my case I wrote class names for carousel item as .carousel-item the bootstrap.css is referring .item. SO ERROR solved. carosel-item is renamed to item
<div class="carousel-item active"></div>
RENAMED To the following:
<div class="item active"></div>
Some inputs to NN might not have a 'naturally defined' range of values. For example, the average value might be slowly, but continuously increasing over time (for example a number of records in the database).
In such case feeding this raw value into your network will not work very well. You will teach your network on values from lower part of range, while the actual inputs will be from the higher part of this range (and quite possibly above range, that the network has learned to work with).
You should normalize this value. You could for example tell the network by how much the value has changed since the previous input. This increment usually can be defined with high probability in a specific range, which makes it a good input for network.
I believe if you use the file:// method to access your subversion repository, your changes are always performed under the user which accesses the repository. You need to use a method that supports authentication such as http:// or svn://.
See http://svnbook.red-bean.com/en/1.5/svn-book.html#svn.serverconfig.choosing
At first you must consider that if your activity which I called A extends another activity (B) and in both of
them you want to use onbackpressed function then every code you have in B runs in A too. So if you want to separate these you should separate them. It means that A should not extend B , then you can have onbackpressed separately for each of them.
For those situations where you need a bit more customisation of the output (separator or decimal symbol), or who have large dataset (over 65k rows), I wrote the following:
Option Explicit
Sub rng2csv(rng As Range, fileName As String, Optional sep As String = ";", Optional decimalSign As String)
'export range data to a CSV file, allowing to chose the separator and decimal symbol
'can export using rng number formatting!
'by Patrick Honorez --- www.idevlop.com
Dim f As Integer, i As Long, c As Long, r
Dim ar, rowAr, sOut As String
Dim replaceDecimal As Boolean, oldDec As String
Dim a As Application: Set a = Application
ar = rng
f = FreeFile()
Open fileName For Output As #f
oldDec = Format(0, ".") 'current client's decimal symbol
replaceDecimal = (decimalSign <> "") And (decimalSign <> oldDec)
For Each r In rng.Rows
rowAr = a.Transpose(a.Transpose(r.Value))
If replaceDecimal Then
For c = 1 To UBound(rowAr)
'use isnumber() to avoid cells with numbers formatted as strings
If a.IsNumber(rowAr(c)) Then
'uncomment the next 3 lines to export numbers using source number formatting
' If r.cells(1, c).NumberFormat <> "General" Then
' rowAr(c) = Format$(rowAr(c), r.cells(1, c).NumberFormat)
' End If
rowAr(c) = Replace(rowAr(c), oldDec, decimalSign, 1, 1)
End If
Next c
End If
sOut = Join(rowAr, sep)
Print #f, sOut
Next r
Close #f
End Sub
Sub export()
Debug.Print Now, "Start export"
rng2csv shOutput.Range("a1").CurrentRegion, RemoveExt(ThisWorkbook.FullName) & ".csv", ";", "."
Debug.Print Now, "Export done"
End Sub
This is called modular exponentiation(https://en.wikipedia.org/wiki/Modular_exponentiation).
Let's assume you have the following expression:
19 ^ 3 mod 7
Instead of powering 19 directly you can do the following:
(((19 mod 7) * 19) mod 7) * 19) mod 7
But this can take also a long time due to a lot of sequential multipliations and so you can multiply on squared values:
x mod N -> x ^ 2 mod N -> x ^ 4 mod -> ... x ^ 2 |log y| mod N
Modular exponentiation algorithm makes assumptions that:
x ^ y == (x ^ |y/2|) ^ 2 if y is even
x ^ y == x * ((x ^ |y/2|) ^ 2) if y is odd
And so recursive modular exponentiation algorithm will look like this in java:
/**
* Modular exponentiation algorithm
* @param x Assumption: x >= 0
* @param y Assumption: y >= 0
* @param N Assumption: N > 0
* @return x ^ y mod N
*/
public static long modExp(long x, long y, long N) {
if(y == 0)
return 1 % N;
long z = modExp(x, Math.abs(y/2), N);
if(y % 2 == 0)
return (long) ((Math.pow(z, 2)) % N);
return (long) ((x * Math.pow(z, 2)) % N);
}
Special thanks to @chux for found mistake with incorrect return value in case of y and 0 comparison.
First, in Python, if your code is CPU-bound, multithreading won't help, because only one thread can hold the Global Interpreter Lock, and therefore run Python code, at a time. So, you need to use processes, not threads.
This is not true if your operation "takes forever to return" because it's IO-bound—that is, waiting on the network or disk copies or the like. I'll come back to that later.
Next, the way to process 5 or 10 or 100 items at once is to create a pool of 5 or 10 or 100 workers, and put the items into a queue that the workers service. Fortunately, the stdlib multiprocessing
and concurrent.futures
libraries both wraps up most of the details for you.
The former is more powerful and flexible for traditional programming; the latter is simpler if you need to compose future-waiting; for trivial cases, it really doesn't matter which you choose. (In this case, the most obvious implementation with each takes 3 lines with futures
, 4 lines with multiprocessing
.)
If you're using 2.6-2.7 or 3.0-3.1, futures
isn't built in, but you can install it from PyPI (pip install futures
).
Finally, it's usually a lot simpler to parallelize things if you can turn the entire loop iteration into a function call (something you could, e.g., pass to map
), so let's do that first:
def try_my_operation(item):
try:
api.my_operation(item)
except:
print('error with item')
Putting it all together:
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_my_operation, item) for item in items]
concurrent.futures.wait(futures)
If you have lots of relatively small jobs, the overhead of multiprocessing might swamp the gains. The way to solve that is to batch up the work into larger jobs. For example (using grouper
from the itertools
recipes, which you can copy and paste into your code, or get from the more-itertools
project on PyPI):
def try_multiple_operations(items):
for item in items:
try:
api.my_operation(item)
except:
print('error with item')
executor = concurrent.futures.ProcessPoolExecutor(10)
futures = [executor.submit(try_multiple_operations, group)
for group in grouper(5, items)]
concurrent.futures.wait(futures)
Finally, what if your code is IO bound? Then threads are just as good as processes, and with less overhead (and fewer limitations, but those limitations usually won't affect you in cases like this). Sometimes that "less overhead" is enough to mean you don't need batching with threads, but you do with processes, which is a nice win.
So, how do you use threads instead of processes? Just change ProcessPoolExecutor
to ThreadPoolExecutor
.
If you're not sure whether your code is CPU-bound or IO-bound, just try it both ways.
Can I do this for multiple functions in my python script? For example, if I had another for loop elsewhere in the code that I wanted to parallelize. Is it possible to do two multi threaded functions in the same script?
Yes. In fact, there are two different ways to do it.
First, you can share the same (thread or process) executor and use it from multiple places with no problem. The whole point of tasks and futures is that they're self-contained; you don't care where they run, just that you queue them up and eventually get the answer back.
Alternatively, you can have two executors in the same program with no problem. This has a performance cost—if you're using both executors at the same time, you'll end up trying to run (for example) 16 busy threads on 8 cores, which means there's going to be some context switching. But sometimes it's worth doing because, say, the two executors are rarely busy at the same time, and it makes your code a lot simpler. Or maybe one executor is running very large tasks that can take a while to complete, and the other is running very small tasks that need to complete as quickly as possible, because responsiveness is more important than throughput for part of your program.
If you don't know which is appropriate for your program, usually it's the first.
this is actually pretty easily done. You're almost there, doing what you've done with background-position: right center;
. What is actually needed in this case is something very much like that. Let's convert these to percentages. We know that center
=50%
, so that's easy enough. Now, in order to get the padding you wanted, you need to position the background like so: background-position: 99% 50%
.
The second, and more effective way of going about this, is to use the same background-position
idea, and just use background-position: 400px (width of parent) 50%;
. Of course, this method requires a static width, but will give you the same thing every time.
[u'ABC']
would be a one-element list of unicode strings. Beautiful Soup always produces Unicode. So you need to convert the list to a single unicode string, and then convert that to ASCII.
I don't know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really only ASCII you would use this:
soup[0].encode("ascii")
However, please double-check that your data is really ASCII. This is pretty rare. Much more likely it's latin-1 or utf-8.
soup[0].encode("latin-1")
soup[0].encode("utf-8")
Or you ask Beautiful Soup what the original encoding was and get it back in this encoding:
soup[0].encode(soup.originalEncoding)
I felt that we were lacking certain kinds of sub string counting, like unsafe byte-by-byte comparisons. I put together the original poster's method and any methods I could think of.
These are the string extensions I made.
namespace Example
{
using System;
using System.Text;
public static class StringExtensions
{
public static int CountSubstr(this string str, string substr)
{
return (str.Length - str.Replace(substr, "").Length) / substr.Length;
}
public static int CountSubstr(this string str, char substr)
{
return (str.Length - str.Replace(substr.ToString(), "").Length);
}
public static int CountSubstr2(this string str, string substr)
{
int substrlen = substr.Length;
int lastIndex = str.IndexOf(substr, 0, StringComparison.Ordinal);
int count = 0;
while (lastIndex != -1)
{
++count;
lastIndex = str.IndexOf(substr, lastIndex + substrlen, StringComparison.Ordinal);
}
return count;
}
public static int CountSubstr2(this string str, char substr)
{
int lastIndex = str.IndexOf(substr, 0);
int count = 0;
while (lastIndex != -1)
{
++count;
lastIndex = str.IndexOf(substr, lastIndex + 1);
}
return count;
}
public static int CountChar(this string str, char substr)
{
int length = str.Length;
int count = 0;
for (int i = 0; i < length; ++i)
if (str[i] == substr)
++count;
return count;
}
public static int CountChar2(this string str, char substr)
{
int count = 0;
foreach (var c in str)
if (c == substr)
++count;
return count;
}
public static unsafe int CountChar3(this string str, char substr)
{
int length = str.Length;
int count = 0;
fixed (char* chars = str)
{
for (int i = 0; i < length; ++i)
if (*(chars + i) == substr)
++count;
}
return count;
}
public static unsafe int CountChar4(this string str, char substr)
{
int length = str.Length;
int count = 0;
fixed (char* chars = str)
{
for (int i = length - 1; i >= 0; --i)
if (*(chars + i) == substr)
++count;
}
return count;
}
public static unsafe int CountSubstr3(this string str, string substr)
{
int length = str.Length;
int substrlen = substr.Length;
int count = 0;
fixed (char* strc = str)
{
fixed (char* substrc = substr)
{
int n = 0;
for (int i = 0; i < length; ++i)
{
if (*(strc + i) == *(substrc + n))
{
++n;
if (n == substrlen)
{
++count;
n = 0;
}
}
else
n = 0;
}
}
}
return count;
}
public static int CountSubstr3(this string str, char substr)
{
return CountSubstr3(str, substr.ToString());
}
public static unsafe int CountSubstr4(this string str, string substr)
{
int length = str.Length;
int substrLastIndex = substr.Length - 1;
int count = 0;
fixed (char* strc = str)
{
fixed (char* substrc = substr)
{
int n = substrLastIndex;
for (int i = length - 1; i >= 0; --i)
{
if (*(strc + i) == *(substrc + n))
{
if (--n == -1)
{
++count;
n = substrLastIndex;
}
}
else
n = substrLastIndex;
}
}
}
return count;
}
public static int CountSubstr4(this string str, char substr)
{
return CountSubstr4(str, substr.ToString());
}
}
}
Followed by the test code...
static void Main()
{
const char matchA = '_';
const string matchB = "and";
const string matchC = "muchlongerword";
const string testStrA = "_and_d_e_banna_i_o___pfasd__and_d_e_banna_i_o___pfasd_";
const string testStrB = "and sdf and ans andeians andano ip and and sdf and ans andeians andano ip and";
const string testStrC =
"muchlongerword amuchlongerworsdfmuchlongerwordsdf jmuchlongerworijv muchlongerword sdmuchlongerword dsmuchlongerword";
const int testSize = 1000000;
Console.WriteLine(testStrA.CountSubstr('_'));
Console.WriteLine(testStrA.CountSubstr2('_'));
Console.WriteLine(testStrA.CountSubstr3('_'));
Console.WriteLine(testStrA.CountSubstr4('_'));
Console.WriteLine(testStrA.CountChar('_'));
Console.WriteLine(testStrA.CountChar2('_'));
Console.WriteLine(testStrA.CountChar3('_'));
Console.WriteLine(testStrA.CountChar4('_'));
Console.WriteLine(testStrB.CountSubstr("and"));
Console.WriteLine(testStrB.CountSubstr2("and"));
Console.WriteLine(testStrB.CountSubstr3("and"));
Console.WriteLine(testStrB.CountSubstr4("and"));
Console.WriteLine(testStrC.CountSubstr("muchlongerword"));
Console.WriteLine(testStrC.CountSubstr2("muchlongerword"));
Console.WriteLine(testStrC.CountSubstr3("muchlongerword"));
Console.WriteLine(testStrC.CountSubstr4("muchlongerword"));
var timer = new Stopwatch();
timer.Start();
for (int i = 0; i < testSize; ++i)
testStrA.CountSubstr(matchA);
timer.Stop();
Console.WriteLine("CS1 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrB.CountSubstr(matchB);
timer.Stop();
Console.WriteLine("CS1 and: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrC.CountSubstr(matchC);
timer.Stop();
Console.WriteLine("CS1 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountSubstr2(matchA);
timer.Stop();
Console.WriteLine("CS2 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrB.CountSubstr2(matchB);
timer.Stop();
Console.WriteLine("CS2 and: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrC.CountSubstr2(matchC);
timer.Stop();
Console.WriteLine("CS2 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountSubstr3(matchA);
timer.Stop();
Console.WriteLine("CS3 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrB.CountSubstr3(matchB);
timer.Stop();
Console.WriteLine("CS3 and: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrC.CountSubstr3(matchC);
timer.Stop();
Console.WriteLine("CS3 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountSubstr4(matchA);
timer.Stop();
Console.WriteLine("CS4 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrB.CountSubstr4(matchB);
timer.Stop();
Console.WriteLine("CS4 and: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrC.CountSubstr4(matchC);
timer.Stop();
Console.WriteLine("CS4 mlw: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountChar(matchA);
timer.Stop();
Console.WriteLine("CC1 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountChar2(matchA);
timer.Stop();
Console.WriteLine("CC2 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountChar3(matchA);
timer.Stop();
Console.WriteLine("CC3 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
timer.Restart();
for (int i = 0; i < testSize; ++i)
testStrA.CountChar4(matchA);
timer.Stop();
Console.WriteLine("CC4 chr: " + timer.Elapsed.TotalMilliseconds + "ms");
}
Results: CSX corresponds with CountSubstrX and CCX corresponds with CountCharX. "chr" searches a string for '_', "and" searches a string for "and", and "mlw" searches a string for "muchlongerword"
CS1 chr: 824.123ms
CS1 and: 586.1893ms
CS1 mlw: 486.5414ms
CS2 chr: 127.8941ms
CS2 and: 806.3918ms
CS2 mlw: 497.318ms
CS3 chr: 201.8896ms
CS3 and: 124.0675ms
CS3 mlw: 212.8341ms
CS4 chr: 81.5183ms
CS4 and: 92.0615ms
CS4 mlw: 116.2197ms
CC1 chr: 66.4078ms
CC2 chr: 64.0161ms
CC3 chr: 65.9013ms
CC4 chr: 65.8206ms
And finally, I had a file with 3.6 million characters. It was "derp adfderdserp dfaerpderp deasderp" repeated 100,000 times. I searched for "derp" inside the file with the above methods 100 times these results.
CS1Derp: 1501.3444ms
CS2Derp: 1585.797ms
CS3Derp: 376.0937ms
CS4Derp: 271.1663ms
So my 4th method is definitely the winner, but, realistically, if a 3.6 million character file 100 times only took 1586ms as the worse case, then all of this is quite negligible.
By the way, I also scanned for the 'd' char in the 3.6 million character file with 100 times CountSubstr and CountChar methods. Results...
CS1 d : 2606.9513ms
CS2 d : 339.7942ms
CS3 d : 960.281ms
CS4 d : 233.3442ms
CC1 d : 302.4122ms
CC2 d : 280.7719ms
CC3 d : 299.1125ms
CC4 d : 292.9365ms
The original posters method is very bad for single character needles in a large haystack according to this.
Note: All values were updated to Release version output. I accidentally forgot to build on Release mode upon the first time I posted this. Some of my statements have been amended.
Sorry for being lazy just providing solution without explaining the reason. Now I'm updating my answer.
Reason: This error occurs because jackson library
doesn't know how to create your model which doesn't have empty constructor
and the model contains constructor with parameters which didn't annotated its parameters with @JsonProperty("field_name")
. By default java compiler creates empty constructor if you didn't add constructor to your class.
Solution:
Add empty constructor
to your model or annotate constructor parameters with @JsonProperty("field_name")
If you use kotlin data class
then also can annotate with @JsonProperty("field_name")
or register jackson module kotlin to ObjectMapper
.
You can create your models using http://www.jsonschema2pojo.org/.
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
If you want to listen to a native event on the root element of a component, you have to use the .native modifier for v-on
, like following:
<template>
<div id="app">
<test v-on:click.native="testFunction"></test>
</div>
</template>
or in shorthand, as suggested in comment, you can as well do:
<template>
<div id="app">
<test @click.native="testFunction"></test>
</div>
</template>
Your code was very close to working.
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
Here's some code that writes each key/value pair on a separate row:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
Try this:
<form method="post" action="check.php">
<select name="website_string">
<option value="" selected="selected"></option>
<option VALUE="abc"> ABC</option>
<option VALUE="def"> def</option>
<option VALUE="hij"> hij</option>
</select>
<input TYPE="submit" name="submit" />
</form>
Both your select control and your submit button had the same name
attribute, so the last one used was the submit button when you clicked it. All other syntax errors aside.
<?php
echo $_POST['website_string'];
?>
Obligatory disclaimer about using raw
$_POST
data. Sanitize anything you'll actually be using in application logic.
php artisan migrate:rollback --path=/database/migrations/0000_00_00_0000_create_something_table.php
public class Country
{
public string Name { get; set; }
public IList<City> Cities { get; set; }
public Country()
{
Cities = new List<City>();
}
}
public class City
{
public string Name { get; set; }
}
List<Country> Countries = new List<Country>
{
new Country
{
Name = "Germany",
Cities =
{
new City {Name = "Berlin"},
new City {Name = "Hamburg"}
}
},
new Country
{
Name = "England",
Cities =
{
new City {Name = "London"},
new City {Name = "Birmingham"}
}
}
};
bindingSource1.DataSource = Countries;
member_CountryComboBox.DataSource = bindingSource1.DataSource;
member_CountryComboBox.DisplayMember = "Name";
member_CountryCombo
Box.ValueMember = "Name";
This is the code I am using now.
defaultMember
already is an alias - it doesn't need to be the name of the exported function/thing. Just do
import alias from 'my-module';
Alternatively you can do
import {default as alias} from 'my-module';
but that's rather esoteric.
Try killing the pythonw process from the Task Manager (if Windows) if nothing else works.
I tried all the answers above, but none of them worked for me, so I was forced to try something else. I just removed the whole package with settings org.eclipse.Java and it worked fine, starts again like before and even keeps all settings like color themes and others. Worked like charm.
On Linux or Mac go to /home/{your_user_name}/.var/app and run the following command:
rm -r org.eclipse.Java
On Windows just find the same directory and move it to Trash.
After this is done, the settings and the errors are deleted, so Eclipse will start and re-create them with the proper settings.
When Eclipse starts it will ask for the workspace directory. When specified, everything works like before.
Answer that worked for me found here: https://github.com/select2/select2-bootstrap-theme/issues/41
$('select').select2({
dropdownParent: $('#my_amazing_modal')
});
Also doesn't require removing the tabindex
.
Important points in my experience:
xx5
in every chmod in other answers.xx5
or chmod o+rx
is necessary.But the greater conclusion I reached is start from little to more.
For example, if
http://myserver.com/sites/all/resources/assets/css/bootstrap.css
yields a 403 error, see if http://myserver.com/
works, then sites
, then sites/all
, then sites/all/resources
, and so on.
It will help if your server has directory indexes enable:
Options +Indexes
This instruction might also be in the .htaccess
of your webserver public_html folder.
The literal answer is:
return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:
return (value == 1
? Periods.VariablePeriods
: (value == 2
? Periods.FixedPeriods
: Periods.Unknown));
If you add more values an inline if will become unreadable and a switch would be preferred:
switch (value)
{
case 1:
return Periods.VariablePeriods;
case 2:
return Periods.FixedPeriods;
}
The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.
Well I have to add something as well. Structure is a bit different than array because array is a pointer and structure is not. So be careful!
Lets say I write this useless piece of code:
#include <stdio.h>
typedef struct{
int km;
int kph;
int kg;
} car;
int main(void){
car audi = {12000, 230, 760};
car *ptr = &audi;
}
Here pointer ptr
points to the address (!) of the structure variable audi
but beside address structure also has a chunk of data (!)! The first member of the chunk of data has the same address than structure itself and you can get it's data by only dereferencing a pointer like this *ptr
(no braces).
But If you want to acess any other member than the first one, you have to add a designator like .km
, .kph
, .kg
which are nothing more than offsets to the base address of the chunk of data...
But because of the preceedence you can't write *ptr.kg
as access operator .
is evaluated before dereference operator *
and you would get *(ptr.kg)
which is not possible as pointer has no members! And compiler knows this and will therefore issue an error e.g.:
error: ‘ptr’ is a pointer; did you mean to use ‘->’?
printf("%d\n", *ptr.km);
Instead you use this (*ptr).kg
and you force compiler to 1st dereference the pointer and enable acess to the chunk of data and 2nd you add an offset (designator) to choose the member.
Check this image I made:
But if you would have nested members this syntax would become unreadable and therefore ->
was introduced. I think readability is the only justifiable reason for using it as this ptr->kg
is much easier to write than (*ptr).kg
.
Now let us write this differently so that you see the connection more clearly. (*ptr).kg
? (*&audi).kg
? audi.kg
. Here I first used the fact that ptr
is an "address of audi
" i.e. &audi
and fact that "reference" &
and "dereference" *
operators cancel eachother out.
this.options[this.selectedIndex].innerText
You cannot 'alter' the property syntax this way. What you can do is this:
class Foo
{
string MyProperty { get; set; } // auto-property with inaccessible backing field
}
and a generic version would look like this:
class Foo<T>
{
T MyProperty { get; set; }
}
Step over the next function(F10)
button beside Resume(F8)
in the upper top center of the chrome until you freeze the popup you want to see. For example, you have collection ArrayList with elements Student class:
List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray(); // <----- toArray() function will convert collection to array
Escaping the double quotes with backslashes is the only way to do this in Java.
Some IDEs around such as IntelliJ IDEA do this escaping automatically when pasting such a String into a String literal (i.e. between the double quotes surrounding a java String literal)
One other option would be to put the String into some kind of text file that you would then read at runtime
This works for me using JsonConvert
var result = JsonConvert.DeserializeObject<Class>(responseString);
I´d like to mention, that I used spring boot version 1.4.0 and since this version you can only write:
@Component
public class MongoConnection {
@Value("${spring.data.mongodb.host}")
private String mongoHost;
@Value("${spring.data.mongodb.port}")
private int mongoPort;
@Value("${spring.data.mongodb.database}")
private String mongoDB;
}
Then inject class whenever you want.
EDIT:
From nowadays I would use @ConfigurationProperties because you are able to inject property values in your POJOs. Keep hierarchical sort above your properties. Moreover, you can put validations above POJOs attributes and so on. Take a look at the link
Both do the same on all browsers, AFAIK. Checked on Chrome and Firefox, both append display:none
to the style
attribute of the element.
The height is the text size you have set on the Paint variable.
Another way to find out the height is
mPaint.getTextSize();
PHP parser errors take some getting used to; if it complains about an unexpected 'something' at line X, look at line X-1 first. In this case it will not tell you that you forgot a semi-colon at the end of the previous line , instead it will complain about the if
that comes next.
You'll get used to it :)
cond? statementA: statementB
Equals to:
if (cond)
statementA
else
statementB
For your case, you may just delete all "if". If you totally use if-else instead of ?:. Don't mix them together.
You have to create a symlink to your mysql installation if it is not the most recent version of mysql.
$ brew link --force [email protected]
I met this problem on my project too.
This helped me, so hopefuly will help someone else:
adb uninstall "com.domain.yourapp"
If you want to attach a file on Linux
echo 'mail content' | mailx -s 'email subject' -a attachment.txt [email protected]
To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100
in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application.
If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.
If you want to present it modally, you should have something like bellow:
let vc = self.storyboard!.instantiateViewControllerWithIdentifier("YourViewControllerID")
self.showDetailViewController(vc as! YourViewControllerClassName, sender: self)
more generic would be:
function menu(){
title="Question time"
prompt="Select:"
options=("Yes" "No" "Maybe")
echo "$title"
PS3="$prompt"
select opt in "${options[@]}" "Quit/Cancel"; do
case "$REPLY" in
1 ) echo "You picked $opt which is option $REPLY";;
2 ) echo "You picked $opt which is option $REPLY";;
3 ) echo "You picked $opt which is option $REPLY";;
$(( ${#options[@]}+1 )) ) clear; echo "Goodbye!"; exit;;
*) echo "Invalid option. Try another one.";continue;;
esac
done
return
}
This solution can be applied only if the issue is on a WordPress installation!
If you don't have FTP access or too lazy to edit files,
You can use Increase Maximum Upload File Size plugin to increase the maximum upload file size.
It can be done recursively via the function:
CREATE FUNCTION dbo.RemSpaceFromStr(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS
BEGIN
RETURN (CASE WHEN CHARINDEX(' ', @str) > 0 THEN
dbo.RemSpaceFromStr(REPLACE(@str, ' ', ' ')) ELSE @str END);
END
then, for example:
SELECT dbo.RemSpaceFromStr('some string with many spaces') AS NewStr
returns:
NewStr
some string with many spaces
Or the solution based on method described by @agdk26 or @Neil Knight (but safer)
both examples return output above:
SELECT REPLACE(REPLACE(REPLACE('some string with many spaces'
, ' ', ' ' + CHAR(7)), CHAR(7) + ' ', ''), ' ' + CHAR(7), ' ') AS NewStr
--but it remove CHAR(7) (Bell) from string if exists...
or
SELECT REPLACE(REPLACE(REPLACE('some string with many spaces'
, ' ', ' ' + CHAR(7) + CHAR(7)), CHAR(7) + CHAR(7) + ' ', ''), ' ' + CHAR(7) + CHAR(7), ' ') AS NewStr
--but it remove CHAR(7) + CHAR(7) from string
Caution:
Char/string used to replace spaces shouldn't exist on begin or end of string and stand alone.
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
This should work.
I'm not sure you can use a relationship as an Id/PrimaryKey in Hibernate.
Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.
$('#divId').find(':input').val('');
In fact you should do both :
Add driver
Add Oracle SQL developper connector
Next time you will add a connection, MySQL new tab is available !
CountDownTimer waitTimer;
waitTimer = new CountDownTimer(60000, 300) {
public void onTick(long millisUntilFinished) {
//called every 300 milliseconds, which could be used to
//send messages or some other action
}
public void onFinish() {
//After 60000 milliseconds (60 sec) finish current
//if you would like to execute something when time finishes
}
}.start();
to stop the timer early:
if(waitTimer != null) {
waitTimer.cancel();
waitTimer = null;
}
You can use:
sed -i -e 's/<string-to-find>/<string-to-replace>/' <your-file-path>
Example:
sed -i -e 's/Hello/Bye/' file.txt
This works flawless in Mac.
A variable cannot be both null
and undefined
at the same time. However, the direct answer to your question is:
if (variable != null)
One =
, not two.
There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null
and the other being undefined
, and the result is true
for ==
and false
for !=
. Thus if the value of the variable is undefined
, it's not != null
, and if it's not null, it's obviously not != null
.
Now, the case of an identifier not being defined at all, either as a var
or let
, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:
var isDefined = false;
try {
(variable);
isDefined = true;
}
catch (x) {}
I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window
property (in browser JavaScript):
var isJqueryAvailable = window.jQuery != null;
or
var isJqueryAvailable = "jQuery" in window;
shareInfo is Class:
public class ShareInfo
{
[JsonIgnore]
public readonly DateTime Timestamp = DateTime.Now;
[JsonProperty("sharename")]
public string ShareName = null;
[JsonProperty("readystate")]
public string ReadyState = null;
[JsonProperty("created")]
[JsonConverter(typeof(Newtonsoft.Json.Converters.UnixDateTimeConverter))]
public DateTime? CreatedUtc = null;
[JsonProperty("title")]
public string Title = null;
[JsonProperty("getturl")]
public string GettUrl = null;
[JsonProperty("userid")]
public string UserId = null;
[JsonProperty("fullname")]
public string Fullname = null;
[JsonProperty("files")]
public GettFile.FileInfo[] Files = new GettFile.FileInfo[0];
}
// POST request.
var gett = new WebClient { Encoding = Encoding.UTF8 };
gett.Headers.Add("Content-Type", "application/json");
byte[] request = Encoding.UTF8.GetBytes(jsonArgument.ToString());
byte[] response = gett.UploadData(baseUri.Uri, request);
// Response.
var shareInfo = JsonConvert.DeserializeObject<ShareInfo>(Encoding.UTF8.GetString(response));
Eclipse 3.5 has an option to package required libraries into the runnable jar. File -> Export... Choose runnable jar and click next. The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.
You can always do
git clone git://repo.org/fossproject.git && rm -rf fossproject/.git
I think in this case they are the same, but here is an example where order matters:
const int* cantChangeTheData;
int* const cantChangeTheAddress;
Instead of RenderViewToString
I prefer a approach like
return Json(new { Url = Url.Action("Evil", model) });
then you can catch the result in your javascript and do something like
success: function(data) {
$.post(data.Url, function(partial) {
$('#IdOfDivToUpdate').html(partial);
});
}
Try the following:
window.history.back(1);
I made it work with this:
.element {
transition: height 3s ease-out, width 5s ease-in;
}
Use jQTouch instead - its jQuery's mobile version
Your best option is through PHP: All version requests from the client side cannot be trusted since your Apache could be configured with ServerTokens Prod and ServerSignature Off. See: http://www.petefreitag.com/item/419.cfm
Without using max-width
, or percentage column widths, or table-layout: fixed
etc.
https://jsfiddle.net/tturadqq/
How it works:
Step 1: Just let the table auto-layout do its thing.
When there's one or more columns with a lot of text, it will shrink the other columns as much as possible, then wrap the text of the long columns:
Step 2: Wrap cell contents in a div, then set that div to max-height: 1.1em
(the extra 0.1em is for characters which render a bit below the text base, like the tail of 'g' and 'y')
Step 3: Set title
on the divs
This is good for accessibility, and is necessary for the little trick we'll use in a moment.
Step 4: Add a CSS ::after
on the div
This is the tricky bit. We set a CSS ::after
, with content: attr(title)
, then position that on top of the div and set text-overflow: ellipsis
. I've coloured it red here to make it clear.
(Note how the long column now has a tailing ellipsis)
Step 5: Set the colour of the div text to transparent
And we're done!
Try something like:
WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else
To call a specific exception such as FileNotFoundException use this format
if (-not (Test-Path $file))
{
throw [System.IO.FileNotFoundException] "$file not found."
}
To throw a general exception use the throw command followed by a string.
throw "Error trying to do a task"
When used inside a catch, you can provide additional information about what triggered the error
it works for me.
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)? Math.ceil(from) : Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++) {
if (from in this && this[from] === elt)
return from;
}
return -1;
};
}
iOS9+, Swift 2
Delete all objects in all entities
func clearCoreDataStore() {
let entities = managedObjectModel.entities
for entity in entities {
let fetchRequest = NSFetchRequest(entityName: entity.name!)
let deleteReqest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try context.executeRequest(deleteReqest)
} catch {
print(error)
}
}
}
The [:-1]
removes the last element. Instead of
a[3:-1]
write
a[3:]
You can read up on Python slicing notation here: Explain Python's slice notation
NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.