You're calling writer.close();
after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.
public void writeToFile(){
String file_text= pedStatusText + " " + gatesStatus + " " + DrawBridgeStatusText;
try {
writer.write(file_text);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
And add a method cleanUp
to close the stream.
public void cleanUp() {
writer.close();
}
This means that you have the responsibility to make sure that you're calling cleanUp
when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.
EDIT: You can create a new stream each time you want to write to the file, by moving writer
into the writeToFile()
method..
public void writeToFile() {
FileWriter writer = new FileWriter("status.txt", true);
// ... Write to the file.
writer.close();
}
Here are few pointers/suggestions for investigation
vote
method which creates a fresh HTTP connection.HttpClient
instance to post to the server. This way it wont create too many connections from the client side. HttpClient
needs to be shut and hence call httpclient.getConnectionManager().shutdown();
to release the resources used by the connections. Make the class serializable by implementing the interface java.io.Serializable
.
java.io.Serializable
- Marker Interface which does not have any methods in it.ObjectOutputStream
that this object is a serializable object.None of these answers worked for me.
I had to remove all deployed java web app:
Then run the project on the server
The Error is gone!
You will have to stop the server before deploying another project because it will not be found by the server. Otherwise you will get a 404 error
It is an old post, but I came across this recently
Selecting a specific interval
As @aleroot already mentioned, by using
table.setRowSelectionInterval(index0, index1);
You can specify an interval, which should be selected.
Adding an interval to the existing selection
You can also keep the current selection, and simply add additional rows by using this here
table.getSelectionModel().addSelectionInterval(index0, index1);
This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.
I delete that web page that i want to link with master page from web application,add new web page in project then set the master page(Initially I had copied web page from web site into Web application fro coping that aspx page (I was converting website to web application as project))
This question is addressed in the Apache wiki.
Question: "Can I set Java system properties differently for each webapp?"
Answer: No. If you can edit Tomcat's startup scripts (or better create a setenv.sh file), you can add "-D" options to Java. But there is no way in Java to have different values of system properties for different classes in the same JVM. There are some other methods available, like using ServletContext.getContextPath() to get the context name of your web application and locate some resources accordingly, or to define elements in WEB-INF/web.xml file of your web application and then set the values for them in Tomcat context file (META-INF/context.xml). See http://tomcat.apache.org/tomcat-7.0-doc/config/context.html .
http://wiki.apache.org/tomcat/HowTo#Can_I_set_Java_system_properties_differently_for_each_webapp.3F
Just use inline if operation with tuple function:
query = "Select * from hr_employee WHERE id in " % tuple(employee_ids) if len(employee_ids) != 1 else "("+ str(employee_ids[0]) + ")"
Suppose you have a hidden input, named XXX, if you want to assign a value to the following
<script type="text/javascript">
$(document).ready(function(){
$('#XXX').val('any value');
})
</script>
Okay, I have refined my regular expression based on the solution you came up with (which erroneously matches strings that start with 'test').
^((?!foo).)*$
This regular expression will match only strings that do not contain foo. The first lookahead will deny strings beginning with 'foo', and the second will make sure that foo isn't found elsewhere in the string.
For me the case was Type inference I have changed the function parameters from int To float but did not update the calling code, and the compiler did not warn me on wrong type passed to the function
Before
func myFunc(param:Int, parma2:Int) {}
After
func myFunc(param:Float, parma2:Float) {}
Calling code with error
var param1:Int16 = 1
var param2:Int16 = 2
myFunc(param:param1, parma2:param2)// error here: Type of expression is ambiguous without more context
To fix:
var param1:Float = 1.0f
var param2:Float = 2.0f
myFunc(param:param1, parma2:param2)// ok!
I didn't like how I had to explicitly specify all the other column in the other solutions so this worked best for me. Though it might be slow for large dataframes...?
df = df.set_index('Mid').reset_index()
Incorrect usage.
Input type number it's made to have selectable value via arrows up and down.
So basically you are looking for "width" CSS style.
Input text historically is formatted with monospaced font, so size it's also the width it takes.
Input number it's new and "size" property has no sense at all*. A typical usage:
<input type="number" name="quantity" min="1" max="5">
to fix, add a style:
<input type="number" name="email" style="width: 7em">
EDIT: if you want a range, you have to set type="range"
and not ="number"
EDIT2: *size is not an allowed value (so, no sense). Check out official W3C specifications
Note: The size attribute works with the following input types: text, search, tel, url, email, and password.
Tip: To specify the maximum number of characters allowed in the element, use the maxlength attribute.
As Yoni already mentioned, you probably deleted the project named "Servers" from your Project Explorer. If config files for the server still present on a file system, the quickest way to restore it will be Right Click in Project Explorer->Import->General->Existing Projects into Workspace, then select the root dir where Servers dir located, set checkbox near "Servers" and finally click Finish. If everything works as expected, you should see the 'Servers' project added to the Project Explorer view and your old config files will be there. Finally, save the tomcat configuration which you had open. You can startup your Tomcat server without errors now.
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
Paste this code after setContentView or into onCreate
if you have a color code use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#408ed4")));
if you want a specific code from Color library use this ;
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
I'm not familiar with resolve, but I've used the others:
Recursive is the default for non-fast-forward merges. We're all familiar with that one.
I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.
An octopus branch merges multiple heads in one commit as long as it can do it cleanly.
For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).
A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):
However, a single octopus merge would look like this:
commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...
Ours == I want to pull in another head, but throw away all of the changes that head introduces.
This keeps the history of a branch without any of the effects of the branch.
(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours
)
Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.
Something like this should do it :
UPDATE table1
SET table1.Price = table2.price
FROM table1 INNER JOIN table2 ON table1.id = table2.id
You can also try this:
UPDATE table1
SET price=(SELECT price FROM table2 WHERE table1.id=table2.id);
In normal winForms, value of Label object is changed by,
myLabel.Text= "Your desired string";
But in WPF Label control, you have to use .content property of Label control for example,
myLabel.Content= "Your desired string";
Python’s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. “raw”.
This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?
s = s.replace("\\", "\\\\")
(Note that you can't do r"\"
as “a raw string cannot end in a single backslash”, but I could have used r"\\"
as well for the second argument.)
If that doesn’t work, your user input is for some arcane reason interpreting the backslashes, so you’ll need a way to tell it to stop that.
The default vector constructor will create an empty vector. As such, you should be able to write:
struct user r = { string(), vector<unsigned char>() };
Note, I've also used the default string constructor instead of "".
You might want to consider making user a class and adding a default constructor that does this for you:
class User {
User() {}
string username;
vector<unsigned char> password;
};
Then just writing:
User r;
Will result in a correctly initialized user.
If you are using Eclipse, for an existing project (which has a build.gradle
file) you can simply type gradle eclipse
which will create all the Eclipse files and folders for this project.
It takes care of all the dependencies for you and adds them to the project resource path in Eclipse as well.
There is a specific example that "_" be used:
type StringMatcher = String => (String => Boolean)
def starts: StringMatcher = (prefix:String) => _ startsWith prefix
may be equal to :
def starts: StringMatcher = (prefix:String) => (s)=>s startsWith prefix
Applying “_” in some scenarios will automatically convert to “(x$n) => x$n ”
Updated accepted answer to angular 7.0.1 on stackblitz here: https://stackblitz.com/edit/angular-inputsetter?embed=1&file=src/app/app.component.ts
directives
are no more in Component decorator options. So I have provided sub directive to app module.
thank you @thierry-templier!
If you need to check multiples times for any key, convert arr
to hash
, and now check in O(1)
arr = ['Cat', 'Dog', 'Bird']
hash = arr.map {|x| [x,true]}.to_h
=> {"Cat"=>true, "Dog"=>true, "Bird"=>true}
hash["Dog"]
=> true
hash["Insect"]
=> false
Performance of Hash#has_key? versus Array#include?
Parameter Hash#has_key? Array#include Time Complexity O(1) operation O(n) operation Access Type Accesses Hash[key] if it Iterates through each element returns any value then of the array till it true is returned to the finds the value in Array Hash#has_key? call call
For single time check using include?
is fine
Create a command file with your commands
ie: commands.txt
open www.domainhere.com
user useridhere
passwordhere
put test.txt
bye
Then run the FTP client from the command line: ftp -s:commands.txt
Note: This will work for the Windows FTP client.
Edit: Should have had a linebreak after the user name before the password.
I was having the same error - ImportError: No module named PyQt4.QtGui
. Instead of running your python file (which uses PyQt) on the terminal as -
python file_name.py
Run it with sudo privileges -
sudo python file_name.py
This worked for me!
In my case the "Fix Issue" button triggers a spinner for about 20 seconds and fixes nothing.
This works for me (iOS 7 iPhone 5, Xcode 5):
Xcode > Window > Organizer > Devices
Find the connected device(with a green dot) on the left pane. Select "Provisioning Profiles" On the right pane, there is a line with warning. Delete this line.
Now go back to click the "Fix Issue" button and everything is fine - the app runs in the device as expected.
%Started Program or Command% | taskkill /F /IM cmd.exe
Example:
notepad.exe | taskkill /F /IM cmd.exe
The simplest way to get tooltips in most browsers is to set some text in the title attribute.
eg.
<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />
produces (hover your mouse over the image):
a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg
Title attributes can be applied to most HTML elements.
Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.
string firstdayofyear = new DateTime(DateTime.Now.Year, 1, 1).ToString("MM-dd-yyyy");
string lastdayofyear = new DateTime(DateTime.Now.Year, 12, 31).ToString("MM-dd-yyyy");
string firstdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("MM-dd-yyyy");
string lastdayofmonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1).ToString("MM-dd-yyyy");
For .Net 4+:
string s = "{ \"user\" : { \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
dynamic usr = serializer.DeserializeObject(s);
var UserId = usr["user"]["id"];
For .Net 2/3.5: This code should work on JSON with 1 level
samplejson.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
var UserId = result["id"];
%>
<%=UserId %>
And for a 2 level JSON:
sample2.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Web.Script.Serialization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%
string s = "{ \"user\" : { \"id\" : 12345, \"screen_name\" : \"twitpicuser\"}}";
var serializer = new JavaScriptSerializer();
Dictionary<string, object> result = (serializer.DeserializeObject(s) as Dictionary<string, object>);
Dictionary<string, object> usr = (result["user"] as Dictionary<string, object>);
var UserId = usr["id"];
%>
<%= UserId %>
Java code:
public class MapActivity extends FragmentActivity implements LocationListener {
GoogleMap googleMap;
LatLng myPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
// Getting GoogleMap object from the fragment
googleMap = fm.getMap();
// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
// Getting latitude of the current location
double latitude = location.getLatitude();
// Getting longitude of the current location
double longitude = location.getLongitude();
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);
myPosition = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(myPosition).title("Start"));
}
}
}
activity_map.xml:
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.google.android.gms.maps.SupportMapFragment"/>
You will get your current location in a blue circle.
Nikita's point is an excellent one: don't confuse mature with bad. XML hasn't changed much.
JDOM would be another alternative to DOM4J.
You can also combine the two env_keep
statements in Ahmed Aswani's answer into a single statement like this:
Defaults env_keep += "http_proxy https_proxy"
You should also consider specifying env_keep
for only a single command like this:
Defaults!/bin/[your_command] env_keep += "http_proxy https_proxy"
you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe
it run your last mysql and you can see it in phpmyadmin and other section of your system.
notice: stop your current mysql version.
S F My English.
Another alternative is to use DATE()
function on the left hand operand as shown below
SELECT users.* FROM users WHERE DATE(created_at) BETWEEN '2011-12-01' AND '2011-12-06'
The design of HTTP means that making a POST with data will return a page. The original designers probably intended for that to be a "result" page of your POST.
It is normal for a PHP application to POST back to the same page as it can not only process the POST request, but it can generate an updated page based on the original GET but with the new information from the POST. However, there's nothing stopping your server code from providing completely different output. Alternatively, you could POST to an entirely different page.
If you don't want the output, one method that I've seen before AJAX took off was for the server to return a HTTP response code of (I think) 250. This is called "No Content" and this should make the browser ignore the data.
Of course, the third method is to make an AJAX call with your submitted data, instead.
Extending your code (assuming that the XML you want to send is in xmlString
) :
String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);
you can use -f
option to force delete the containers .
sudo docker rmi -f training/webapp
You may stop the containers using sudo docker stop training/webapp
before deleting
On OSX the following works from the command line:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-running-insecure-content
There is a special build-in util for this - 'yes'.
To answer all questions with the same answer, you can run
yes [answer] |./your_script
Or you can put it inside your script have specific answer to each question
Other than splice, you can use this approach which will not mutate the original array, but will create a new array with the added item. You should usually avoid mutation whenever possible. I'm using ES6 spread operator here.
const items = [1, 2, 3, 4, 5]_x000D_
_x000D_
const insert = (arr, index, newItem) => [_x000D_
// part of the array before the specified index_x000D_
...arr.slice(0, index),_x000D_
// inserted item_x000D_
newItem,_x000D_
// part of the array after the specified index_x000D_
...arr.slice(index)_x000D_
]_x000D_
_x000D_
const result = insert(items, 1, 10)_x000D_
_x000D_
console.log(result)_x000D_
// [1, 10, 2, 3, 4, 5]
_x000D_
This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well
const items = [1, 2, 3, 4, 5]_x000D_
_x000D_
const insert = (arr, index, ...newItems) => [_x000D_
// part of the array before the specified index_x000D_
...arr.slice(0, index),_x000D_
// inserted items_x000D_
...newItems,_x000D_
// part of the array after the specified index_x000D_
...arr.slice(index)_x000D_
]_x000D_
_x000D_
const result = insert(items, 1, 10, 20)_x000D_
_x000D_
console.log(result)_x000D_
// [1, 10, 20, 2, 3, 4, 5]
_x000D_
You can declare a @service as @Controller.
You can NOT declare an @Controller as @Service
@Service
It is regular. You are just declaring class as a Component.
@Controller
It is a little more special than Component. The dispatcher will search for @RequestMapping here. So a class annotated with @Controller, will be additionally empowered with declaring URLs through which APIs are called
In iOS6, Apple supports this via the <input type="file">
tag. I couldn't find a useful link in Apple's developer documentation, but there's an example here.
It looks like overlays and more advanced functionality is not yet available, but this should work for a lot of use cases.
EDIT: The w3c has a spec that iOS6 Safari seems to implement a subset of. The capture
attribute is notably missing.
do it like this
objArrayy.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase()
if (nameA < nameB) //sort string ascending
return -1
if (nameA > nameB)
return 1
return 0 //default return value (no sorting)
});
console.log(objArray)
A few other things:
As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:
var definition = new { Name = "" };
string json1 = @"{'Name':'James'}";
var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
Console.WriteLine(customer1.Name);
// James
NOW()
returns 2009-08-05 15:13:00
CURDATE()
returns 2009-08-05
CURTIME()
returns 15:13:00
It's a block of code which is executed when the class gets loaded by a classloader. It is meant to do initialization of static members of the class.
It is also possible to write non-static initializers, which look even stranger:
public class Foo {
{
// This code will be executed before every constructor
// but after the call to super()
}
Foo() {
}
}
As of Telegram Desktop 1.3 you can format your messages and add links.
[Ctrl+K] = create link (https://my.website)
Other useful hotkeys are:
[Ctrl+B] = bold
[Ctrl+I] = italic
[Ctrl+Shift+M] = monospace
[Ctrl+Shift+N] = clear formatting
I guess in the context of neural network terminology:
In order to define iteration (a.k.a steps), you first need to know about batch size:
Batch size: You probably wouldn't like to process the entire training instances all at one forward pass as it is inefficient and needs a huge deal of memory. So what is commonly done is splitting up training instances into subsets (i.e., batches), performing one pass over the selected subset (i.e., batch), and then optimizing the network through backpropagation. The number of training instances within a subset (i.e., batch) is called batch_size.
Iteration: (a.k.a training steps) You know that your network has to go over all training instances in one pass in order to complete one epoch. But wait! when you are splitting up your training instances into batches, that means you can only process one batch (a subset of training instances) in one forward pass, so what about the other batches? This is where the term Iteration comes into play:
Definition: The number of forward passes (The number of batches that you have created) that your network has to do in order to complete one epoch (i.e., going over all training instances) is called Iteration.
For example, when you have 10000 training instances and you want to do batching with size of 10; you have to do 10000/10 = 1000 iterations to complete 1 epoch.
Hope this could answer your question!
#include "stdafx.h"
#include <iostream>
using namespace std;
void main()
{
int n, i;
cout << "n = ";
cin >> n;
int *a = new int[n];
int *b = new int[n];
for (i = 0; i < n; i++)
{
cout << "a[" << i << "]= ";
cin >> a[i];
}
for (i = 0; i < n; i++)
{
b[i] = a[n - 1 - i];
}
for (i = 0; i < n; i++)
{
cout << b[i];
}
}
Without vue-route, split the URL
var vm = new Vue({
....
created()
{
let uri = window.location.href.split('?');
if (uri.length == 2)
{
let vars = uri[1].split('&');
let getVars = {};
let tmp = '';
vars.forEach(function(v){
tmp = v.split('=');
if(tmp.length == 2)
getVars[tmp[0]] = tmp[1];
});
console.log(getVars);
// do
}
},
updated(){
},
Another solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:
var vm = new Vue({
....
created()
{
let uri = window.location.search.substring(1);
let params = new URLSearchParams(uri);
console.log(params.get("var_name"));
},
updated(){
},
On the replacement side, you must use $1, not \1.
And you can only do what you want by making replace an evalable expression that gives the result you want and telling s/// to eval it with the /ee modifier like so:
$find="start (.*) end";
$replace='"foo $1 bar"';
$var = "start middle end";
$var =~ s/$find/$replace/ee;
print "var: $var\n";
To see why the "" and double /e are needed, see the effect of the double eval here:
$ perl
$foo = "middle";
$replace='"foo $foo bar"';
print eval('$replace'), "\n";
print eval(eval('$replace')), "\n";
__END__
"foo $foo bar"
foo middle bar
(Though as ikegami notes, a single /e or the first /e of a double e isn't really an eval()
; rather, it tells the compiler that the substitution is code to compile, not a string. Nonetheless, eval(eval(...))
still demonstrates why you need to do what you need to do to get /ee to work as desired.)
There are two common approaches for this:
Specify http-proxy-
options in your /etc/.subversion/servers or %APPDATA%\Subversion\servers file,
Use --config-option
command-line option to specify the same http-proxy-
options in single command-line you run. For example,
svn checkout ^
--config-option servers:global:http-proxy-host=<PROXY-HOST> ^
--config-option servers:global:http-proxy-port=<PORT> <REPO-URL> <LWC-DIR>
If you are on Windows, you can also write http-proxy-
options to Windows Registry. It's pretty handy if you need to apply proxy settings in Active Directory environment via Group Policy Objects.
iOS 9.2.1, Xcode 7.2.1, ARC enabled
You can always append the '%' by itself without any other format specifiers in the string you are appending, like so...
int test = 10;
NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [stringTest stringByAppendingString:@"%"];
NSLog(@"%@", stringTest);
For iOS7.0+
To expand the answer to other characters that might cause you conflict you may choose to use:
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
Written out step by step it looks like this:
int test = 10;
NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [[stringTest stringByAppendingString:@"%"]
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];
NSLog(@"percent value of test: %@", stringTest);
Or short hand:
NSLog(@"percent value of test: %@", [[[[NSString stringWithFormat:@"%d", test]
stringByAppendingString:@"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);
Thanks to all the original contributors. Hope this helps. Cheers!
Are you sure that floated block-level elements are the best solution to this problem?
Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.
I know, that the question is about Java, but I would like to list here an ActionScript 1 source code (here the license) to generate MD5 in a different way than the answers listed at this page.
The function below works well and could surely be converted to Java:
/* MD5 implementation from http://www.webtoolkit.info */
function md5(string) {
function RotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function AddUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function F(x,y,z) { return (x & y) | ((~x) & z); }
function G(x,y,z) { return (x & z) | (y & (~z)); }
function H(x,y,z) { return (x ^ y ^ z); }
function I(x,y,z) { return (y ^ (x | (~z))); }
function FF(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function GG(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function HH(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function II(a,b,c,d,x,s,ac) {
a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
return AddUnsigned(RotateLeft(a, s), b);
};
function ConvertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray=Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] |
(string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
};
function WordToHex(lValue) {
var WordToHexValue="",WordToHexValue_temp="",lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
WordToHexValue_temp = "0" + lByte.toString(16);
WordToHexValue = WordToHexValue +
WordToHexValue_temp.substr(WordToHexValue_temp.length-2,2);
}
return WordToHexValue;
};
function Utf8Encode(string) {
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var x=Array();
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = Utf8Encode(string);
x = ConvertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=FF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=FF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=FF(c,d,a,b,x[k+2], S13,0x242070DB);
b=FF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=FF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=FF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=FF(c,d,a,b,x[k+6], S13,0xA8304613);
b=FF(b,c,d,a,x[k+7], S14,0xFD469501);
a=FF(a,b,c,d,x[k+8], S11,0x698098D8);
d=FF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=FF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=FF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=FF(a,b,c,d,x[k+12],S11,0x6B901122);
d=FF(d,a,b,c,x[k+13],S12,0xFD987193);
c=FF(c,d,a,b,x[k+14],S13,0xA679438E);
b=FF(b,c,d,a,x[k+15],S14,0x49B40821);
a=GG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=GG(d,a,b,c,x[k+6], S22,0xC040B340);
c=GG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=GG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=GG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=GG(d,a,b,c,x[k+10],S22,0x2441453);
c=GG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=GG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=GG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=GG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=GG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=GG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=GG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=GG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=GG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=GG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=HH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=HH(d,a,b,c,x[k+8], S32,0x8771F681);
c=HH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=HH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=HH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=HH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=HH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=HH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=HH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=HH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=HH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=HH(b,c,d,a,x[k+6], S34,0x4881D05);
a=HH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=HH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=HH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=HH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=II(a,b,c,d,x[k+0], S41,0xF4292244);
d=II(d,a,b,c,x[k+7], S42,0x432AFF97);
c=II(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=II(b,c,d,a,x[k+5], S44,0xFC93A039);
a=II(a,b,c,d,x[k+12],S41,0x655B59C3);
d=II(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=II(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=II(b,c,d,a,x[k+1], S44,0x85845DD1);
a=II(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=II(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=II(c,d,a,b,x[k+6], S43,0xA3014314);
b=II(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=II(a,b,c,d,x[k+4], S41,0xF7537E82);
d=II(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=II(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=II(b,c,d,a,x[k+9], S44,0xEB86D391);
a=AddUnsigned(a,AA);
b=AddUnsigned(b,BB);
c=AddUnsigned(c,CC);
d=AddUnsigned(d,DD);
}
var temp = WordToHex(a)+WordToHex(b)+WordToHex(c)+WordToHex(d);
return temp.toLowerCase();
}
Style your change the Submit button to an anchor tag instead and submit using javascript:
<a class="link-button" href="javascript:submit();">Submit</a>
<a class="link-button" href="some_url">Cancel</a>
function submit() {
var form = document.getElementById("form_id");
form.submit();
}
For me this was caused by using a dynamic ipadress using installation. I reinstalled Oracle using a static ipadress and then everything was fine
Here is PostgreSQL example without trigger if someone need it on PostgreSQL:
CREATE SEQUENCE messages_seq;
CREATE TABLE IF NOT EXISTS messages (
id CHAR(20) NOT NULL DEFAULT ('message_' || nextval('messages_seq')),
name CHAR(30) NOT NULL,
);
ALTER SEQUENCE messages_seq OWNED BY messages.id;
Swift 5 Protocol Extension
Here is an approach using protocol extension so that you can easily inline an optional nil check:
import Foundation
public extension Optional {
var isNil: Bool {
guard case Optional.none = self else {
return false
}
return true
}
var isSome: Bool {
return !self.isNil
}
}
Usage
var myValue: String?
if myValue.isNil {
// do something
}
if myValue.isSome {
// do something
}
This method I've used a lot, not sure if it is a very good way but it works fine for my needs.
<html>
<head>
<script language="JavaScript">
function setVisibility(id, visibility) {
document.getElementById(id).style.display = visibility;
}
</script>
</head>
<body>
<div id="HiddenStuff1" style="display:none">
CONTENT TO HIDE 1
</div>
<div id="HiddenStuff2" style="display:none">
CONTENT TO HIDE 2
</div>
<div id="HiddenStuff3" style="display:none">
CONTENT TO HIDE 3
</div>
<input id="YOUR ID" title="HIDDEN STUFF 1" type=button name=type value='HIDDEN STUFF 1' onclick="setVisibility('HiddenStuff1', 'inline');setVisibility('HiddenStuff2', 'none');setVisibility('HiddenStuff3', 'none');";>
<input id="YOUR ID" title="HIDDEN STUFF 2" type=button name=type value='HIDDEN STUFF 2' onclick="setVisibility('HiddenStuff1', 'none');setVisibility('HiddenStuff2', 'inline');setVisibility('HiddenStuff3', 'none');";>
<input id="YOUR ID" title="HIDDEN STUFF 3" type=button name=type value='HIDDEN STUFF 3' onclick="setVisibility('HiddenStuff1', 'none');setVisibility('HiddenStuff2', 'none');setVisibility('HiddenStuff3', 'inline');";>
</body>
</html>
The terms "stress testing" and "load testing" are often used interchangeably by software test engineers but they are really quite different.
Stress testing
In Stress testing we tries to break the system under test by overwhelming its resources or by taking resources away from it (in which case it is sometimes called negative testing). The main purpose behind this madness is to make sure that the system fails and recovers gracefully -- this quality is known as recoverability. OR Stress testing is the process of subjecting your program/system under test (SUT) to reduced resources and then examining the SUT’s behavior by running standard functional tests. The idea of this is to expose problems that do not appear under normal conditions.For example, a multi-threaded program may work fine under normal conditions but under conditions of reduced CPU availability, timing issues will be different and the SUT will crash. The most common types of system resources reduced in stress testing are CPU, internal memory, and external disk space. When performing stress testing, it is common to call the tools which reduce these three resources EatCPU, EatMem, and EatDisk respectively.
While on the other hand Load Testing
In case of Load testing Load testing is the process of subjecting your SUT to heavy loads, typically by simulating multiple users( Using Load runner), where "users" can mean human users or virtual/programmatic users. The most common example of load testing involves subjecting a Web-based or network-based application to simultaneous hits by thousands of users. This is generally accomplished by a program which simulates the users. There are two main purposes of load testing: to determine performance characteristics of the SUT, and to determine if the SUT "breaks" gracefully or not.
In the case of a Web site, you would use load testing to determine how many users your system can handle and still have adequate performance, and to determine what happens with an extreme load — will the Web site generate a "too busy" message for users, or will the Web server crash in flames?
Python 3.5 + Use io module
import json
import io
my_bytes_value = b'[{\'Date\': \'2016-05-21T21:35:40Z\', \'CreationDate\': \'2012-05-05\', \'LogoType\': \'png\', \'Ref\': 164611595, \'Classe\': [\'Email addresses\', \'Passwords\'],\'Link\':\'http://some_link.com\'}]'
fix_bytes_value = my_bytes_value.replace(b"'", b'"')
my_json = json.load(io.BytesIO(fix_bytes_value))
You have to modify the viewBox
property to change the height and the width correctly with a svg. It is in the <svg>
tag of the svg.
https://developer.mozilla.org/en/docs/Web/SVG/Attribute/viewBox
The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.
Native methods are usually used to interface with system calls or libraries written in other programming languages.
If HELLO
is your String then you can't change HELLO
to HILLO
. This property is called immutability property.
You can have multiple pointer String variable to point HELLO String.
But if HELLO is char Array then you can change HELLO to HILLO. Eg,
char[] charArr = 'HELLO';
char[1] = 'I'; //you can do this
Answer:
Programming languages have immutable data variables so that it can be used as keys in key, value pair. String variables are used as keys/indices, so they are immutable.
AkashG's solution don't work for me. When I set up check.xml to background it's just stratched in vertical direction. To solve this problem you should set up check.xml to "android:button" property:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/check" //check.xml
android:background="@null"/>
check.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
A word of warning: though padding-right
might solve your particular (visual) problem, it is not the right way to add spacing between table cells. What padding-right
does for a cell is similar to what it does for most other elements: it adds space within the cell. If the cells do not have a border or background colour or something else that gives the game away, this can mimic the effect of setting the space between the cells, but not otherwise.
As someone noted, margin specifications are ignored for table cells:
CSS 2.1 Specification – Tables – Visual layout of table contents
Internal table elements generate rectangular boxes with content and borders. Cells have padding as well. Internal table elements do not have margins.
What's the "right" way then? If you are looking to replace the cellspacing
attribute of the table, then border-spacing
(with border-collapse
disabled) is a replacement. However, if per-cell "margins" are required, I am not sure how that can be correctly achieved using CSS. The only hack I can think of is to use padding
as above, avoid any styling of the cells (background colours, borders, etc.) and instead use container DIVs inside the cells to implement such styling.
I am not a CSS expert, so I could well be wrong in the above (which would be great to know! I too would like a table cell margin CSS solution).
Cheers!
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
If you meant renaming your repository, go to your repository and click "admin", then rename.
Once you see the red box warning you about some sky-fallingness and other things, go read this question.
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference
(or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference
, the name of proxy class is CalculatorSoapClient
. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();
Hope this helps. If you encounter any problems, let us know.
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
from
is a keyword in SQL. You may not used it as a column name without quoting it. In MySQL, things like column names are quoted using backticks, i.e. `from`
.
Personally, I wouldn't bother; I'd just rename the column.
PS. as pointed out in the comments, to
is another SQL keyword so it needs to be quoted, too. Conveniently, the folks at drupal.org maintain a list of reserved words in SQL.
There was conflict in java version. Resolved after using 1.8 for maven.
The comma expression takes on the value of the last (eg. right-most) expression.
So in your first loop, the only controlling expression is i<=5
; and j>=0
is ignored.
In the second loop, j>=0
controls the loop, and i<=5
is ignored.
As for a reason... there is no reason. This code is just wrong. The first part of the comma-expressions does nothing except confuse programmers. If a serious programmer wrote this, they should be ashamed of themselves and have their keyboard revoked.
One more choice is to use Spring's org.springframework.util.FileSystemUtils
relevant method which will recursively delete all content of the directory.
File directoryToDelete = new File(<your_directory_path_to_delete>);
FileSystemUtils.deleteRecursively(directoryToDelete);
That will do the job!
You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:
After you've enabled, set a break-point to where you want it to:
After you're done setting the break-point:
Once that has been completed:
The first thing you need to know is that HashSet
acts like a Set
, which means you add your object directly to the HashSet
and it cannot contain duplicates. You just add your value directly in HashSet
.
However, HashMap
is a Map
type. That means every time you add an entry, you add a key-value pair.
In HashMap
you can have duplicate values, but not duplicate keys. In HashMap
the new entry will replace the old one. The most recent entry will be in the HashMap
.
Understanding Link between HashMap and HashSet:
Remember, HashMap
can not have duplicate keys. Behind the scene HashSet
uses a HashMap
.
When you attempt to add any object into a HashSet
, this entry is actually stored as a key in the HashMap
- the same HashMap
that is used behind the scene of HashSet
. Since this underlying HashMap
needs a key-value pair, a dummy value is generated for us.
Now when you try to insert another duplicate object into the same HashSet
, it will again attempt to be insert it as a key in the HashMap
lying underneath. However, HashMap
does not support duplicates. Hence, HashSet
will still result in having only one value of that type. As a side note, for every duplicate key, since the value generated for our entry in HashSet is some random/dummy value, the key is not replaced at all. it will be ignored as removing the key and adding back the same key (the dummy value is the same) would not make any sense at all.
Summary:
HashMap
allows duplicate values
, but not keys
.
HashSet
cannot contains duplicates.
To play with whether the addition of an object is successfully completed or not, you can check the boolean
value returned when you call .add()
and see if it returns true
or false
. If it returned true
, it was inserted.
Yes, you will need to specify the width for each cell, otherwise they will try to be "intelligent" about it and divide the 100% between whichever cells think they need it most. Cells with more content will take up more width than those with less.
To make sure you get equal width for each cell you need to make it clear. Either do it as you already have, or use CSS.
table.className td { width: 25%; }
On the File menu, choose Advanced Save Options, you can control it there.
Edit: Here's the documentation, you should have a file open first.
In addition to previously provided answers, one option is to follow the 'localhost exception' approach to create the first user if your db is already started with access control (--auth
switch). In order to do that, you need to have localhost access to the server and then run:
mongo
use admin
db.createUser(
{
user: "user_name",
pwd: "user_pass",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" }
]
})
As stated in MongoDB documentation:
The localhost exception allows you to enable access control and then create the first user in the system. With the localhost exception, after you enable access control, connect to the localhost interface and create the first user in the admin database. The first user must have privileges to create other users, such as a user with the userAdmin or userAdminAnyDatabase role. Connections using the localhost exception only have access to create the first user on the admin database.
Here is the link to that section of the docs.
Nobody responding seems to be using the Map()
built-in for this, which tends to be my go-to combined with Array.prototype.reduce()
:
const data = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];_x000D_
const result = data.reduce((a, c) => a.set(c, (a.get(c) || 0) + 1), new Map());_x000D_
console.log(...result);
_x000D_
N.b., you'll have to polyfill Map()
if wanting to use it in older browsers.
The reason for this error is that the element that you are trying to click is not in the viewport (region seen by the user) of the browser. So the way to overcome this is by scrolling to the desired element first and then performing the click.
Javascript:
async scrollTo (webElement) {
await this.driver.executeScript('arguments[0].scrollIntoView(true)', webElement)
await this.driver.executeScript('window.scrollBy(0,-150)')
}
Java:
public void scrollTo (WebElement e) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeAsyncScript('arguments[0].scrollIntoView(true)', e)
js.executeAsyncScript('window.scrollBy(0,-150)')
}
Another reason to the error may be if you are running a cron job that updates a subversion working copy and then has attempted to run a versioned script that was in a conflicted state after the update...
Keyboard shortcuts such as Ctrl+Shift+R work on Android too, you just need a keyboard capable of sending these keys. I used Hacker's Keyboard to send Ctrl+Shift+R, which did a hard reload on my phone.
Using params
allows you to call the function with no arguments. Without params
:
static public int addTwoEach(int[] args)
{
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;
}
addtwoEach(); // throws an error
Compare with params
:
static public int addTwoEach(params int[] args)
{
int sum = 0;
foreach (var item in args)
{
sum += item + 2;
}
return sum;
}
addtwoEach(); // returns 0
Generally, you can use params when the number of arguments can vary from 0 to infinity, and use an array when numbers of arguments vary from 1 to infinity.
There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
};
};
Or a more structured way of handling it:
(function(d){
var modern = (d.addEventListener), event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, code = function(e){
e = e || window.event;
return(e.keyCode || e.which);
}, init = function(){
event(d, "keypress", function(e){
var key = code(e);
// do stuff with key here
});
};
if(modern) {
d.addEventListener("DOMContentLoaded", init, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
init();
}
});
}
})(document);
I used this to change the background for my button
button.setBackground(getResources().getDrawable(R.drawable.primary_button));
"button" is the variable holding my Button, and the image am setting in the background is primary_button
Further to the answer from Diodeus above, you need the font-family: FontAwesome
rule (assuming you have the @font-face
rule for FontAwesome declared already in your CSS). Then it is a matter of knowing which CSS content value corresponds to which icon.
I have listed them all here: http://astronautweb.co/snippet/font-awesome/
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
When I tried to create something simillar to inbox floating action button i thought about creating own custom component.
It would be simple frame layout with fixed height (to contain expanded menu) containing FAB button and 3 more placed under the FAB. when you click on FAB you just simply animate other buttons to translate up from under the FAB.
There are some libraries which do that (for example https://github.com/futuresimple/android-floating-action-button), but it's always more fun if you create it by yourself :)
If you'd like to do it for all dialogs throughout the site try the following code...
$.extend( $.ui.dialog.prototype.options, {
open: function() {
var dialog = this;
$('.ui-widget-overlay').bind('click', function() {
$(dialog).dialog('close');
});
}
});
Use CSS grid and set all the grid items to be in the same cell.
.layered {
display: grid;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
Adding the layered class to an element causes all it's children to be layered on top of each other.
if the layers are not the same size you can set the justify-items
and align-items
properties to set the horizontal and vertical alignment respectively.
.layered {
display: grid;
/* Set horizontal alignment of items in, case they have a different width. */
/* justify-items: start | end | center | stretch (default); */
justify-items: start;
/* Set vertical alignment of items, in case they have a different height. */
/* align-items: start | end | center | stretch (default); */
align-items: start;
}
.layered > * {
grid-column-start: 1;
grid-row-start: 1;
}
/* for demonstration purposes only */
.layered > * {
outline: 1px solid red;
background-color: rgba(255, 255, 255, 0.4)
}
_x000D_
<div class="layered">
<img src="https://via.placeholder.com/250x100?text=first" />
<p>
2
</p>
<div>
<p>
Third layer
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
<p>
Third layer continued
</p>
</div>
</div>
_x000D_
Edit: New article by Dave Abrahams on cpp-next:
Pass by value for structs where the copying is cheap has the additional advantage that the compiler may assume that the objects don't alias (are not the same objects). Using pass-by-reference the compiler cannot assume that always. Simple example:
foo * f;
void bar(foo g) {
g.i = 10;
f->i = 2;
g.i += 5;
}
the compiler can optimize it into
g.i = 15;
f->i = 2;
since it knows that f and g doesn't share the same location. if g was a reference (foo &), the compiler couldn't have assumed that. since g.i could then be aliased by f->i and have to have a value of 7. so the compiler would have to re-fetch the new value of g.i from memory.
For more pratical rules, here is a good set of rules found in Move Constructors article (highly recommended reading).
"Primitive" above means basically small data types that are a few bytes long and aren't polymorphic (iterators, function objects, etc...) or expensive to copy. In that paper, there is one other rule. The idea is that sometimes one wants to make a copy (in case the argument can't be modified), and sometimes one doesn't want (in case one wants to use the argument itself in the function if the argument was a temporary anyway, for example). The paper explains in detail how that can be done. In C++1x that technique can be used natively with language support. Until then, i would go with the above rules.
Examples: To make a string uppercase and return the uppercase version, one should always pass by value: One has to take a copy of it anyway (one couldn't change the const reference directly) - so better make it as transparent as possible to the caller and make that copy early so that the caller can optimize as much as possible - as detailed in that paper:
my::string uppercase(my::string s) { /* change s and return it */ }
However, if you don't need to change the parameter anyway, take it by reference to const:
bool all_uppercase(my::string const& s) {
/* check to see whether any character is uppercase */
}
However, if you the purpose of the parameter is to write something into the argument, then pass it by non-const reference
bool try_parse(T text, my::string &out) {
/* try to parse, write result into out */
}
You can do :
document.forms["loginForm"].submit()
But this won't call the onclick
action of your button, so you will need to call it by hand.
Be aware that you must use the name
of your form and not the id
to access it.
Instead of style changes, just put these two lines of code to your activity.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.arrowleft);
<style type="text/css">
.topcorner{
position:absolute;
top:10;
right:15;
}
</style>
You ca also use this in CSS external file.
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven't tried it):
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin:
gcc
g++
make
Cmake
gdb
Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']
Add the 'bin' folder to the Path variable. For Cygwin, I added:
D:\cygwin64\bin
Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings
Select 'Build, Execution, Deployment' and then click on 'Toolchains'
Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)
For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)
'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'
See screenshot: Check all paths to the compiler, make and gdb
See screenshot: Check the configuration to run the project
There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active
Build your project and then run the project. You should see the output in the terminal window
Hope this helps! Good luck and enjoy CLion.
You should keep a watch on your scope.
Here is how you can do it:
<layout layoutId="myScope"></layout>
Your directive should look like
app.directive('layout', function($http, $compile){
return {
restrict: 'E',
scope: {
layoutId: "=layoutId"
},
link: function(scope, element, attributes) {
var layoutName = (angular.isDefined(attributes.name)) ? attributes.name : 'Default';
$http.get(scope.constants.pathLayouts + layoutName + '.html')
.success(function(layout){
var regexp = /^([\s\S]*?){{content}}([\s\S]*)$/g;
var result = regexp.exec(layout);
var templateWithLayout = result[1] + element.html() + result[2];
element.html($compile(templateWithLayout)(scope));
});
}
}
$scope.$watch('myScope',function(){
//Do Whatever you want
},true)
Similarly you can models in your directive, so if model updates automatically your watch method will update your directive.
To disable inputting password:
sudo visudo
Then add a new line like below and save then:
# The user can run installer as root without inputting password
yourusername ALL=(root) NOPASSWD: /usr/sbin/installer
Then you run installer without password:
sudo installer -pkg ...
If you have a SharedPreferenceActivity by which you have saved your values
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String imgSett = prefs.getString(keyChannel, "");
if the value is saved in a SharedPreference in an Activity then this is the correct way to saving it.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString(keyChannel, email);
editor.commit();// commit is important here.
and this is how you can retrieve the values.
SharedPreferences shared = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
String channel = (shared.getString(keyChannel, ""));
Also be aware that you can do so in a non-Activity class too but the only condition is that you need to pass the context of the Activity. use this context in to get the SharedPreferences.
mContext.getSharedPreferences(PREF_NAME, MODE_PRIVATE);
You want the CASE statement
WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END
Some other answer have already pointed out the traceback module.
Please notice that with print_exc
, in some corner cases, you will not obtain what you would expect. In Python 2.x:
import traceback
try:
raise TypeError("Oups!")
except Exception, err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_exc()
...will display the traceback of the last exception:
Traceback (most recent call last):
File "e.py", line 7, in <module>
raise TypeError("Again !?!")
TypeError: Again !?!
If you really need to access the original traceback one solution is to cache the exception infos as returned from exc_info
in a local variable and display it using print_exception
:
import traceback
import sys
try:
raise TypeError("Oups!")
except Exception, err:
try:
exc_info = sys.exc_info()
# do you usefull stuff here
# (potentially raising an exception)
try:
raise TypeError("Again !?!")
except:
pass
# end of useful stuff
finally:
# Display the *original* exception
traceback.print_exception(*exc_info)
del exc_info
Producing:
Traceback (most recent call last):
File "t.py", line 6, in <module>
raise TypeError("Oups!")
TypeError: Oups!
Few pitfalls with this though:
From the doc of sys_info
:
Assigning the traceback return value to a local variable in a function that is handling an exception will cause a circular reference. This will prevent anything referenced by a local variable in the same function or by the traceback from being garbage collected. [...] If you do need the traceback, make sure to delete it after use (best done with a try ... finally statement)
but, from the same doc:
Beginning with Python 2.2, such cycles are automatically reclaimed when garbage collection is enabled and they become unreachable, but it remains more efficient to avoid creating cycles.
On the other hand, by allowing you to access the traceback associated with an exception, Python 3 produce a less surprising result:
import traceback
try:
raise TypeError("Oups!")
except Exception as err:
try:
raise TypeError("Again !?!")
except:
pass
traceback.print_tb(err.__traceback__)
... will display:
File "e3.py", line 4, in <module>
raise TypeError("Oups!")
You fiddle already does the job ... maybe you try to get the string before the double colon? (you really should edit your question) Then the code would go like this:
str.substring(0, str.indexOf(":"));
Where 'str' represents the variable with your string inside.
Click here for JSFiddle Example
Javascript
var input_string = document.getElementById('my-input').innerText;
var output_element = document.getElementById('my-output');
var left_text = input_string.substring(0, input_string.indexOf(":"));
output_element.innerText = left_text;
Html
<p>
<h5>Input:</h5>
<strong id="my-input">Left Text:Right Text</strong>
<h5>Output:</h5>
<strong id="my-output">XXX</strong>
</p>
CSS
body { font-family: Calibri, sans-serif; color:#555; }
h5 { margin-bottom: 0.8em; }
strong {
width:90%;
padding: 0.5em 1em;
background-color: cyan;
}
#my-output { background-color: gold; }
Don't checksum the entire file, create checksums every 100mb or so, so each file has a collection of checksums.
Then when comparing checksums, you can stop comparing after the first different checksum, getting out early, and saving you from processing the entire file.
It'll still take the full time for identical files.
The original syntax will work with BASH but not with DASH. On debian systems you might think you are using bash, but maybe dash instead. If /bin/dash/exist then try temporarily renaming dash to something like no.dash, and then create soft a link, aka ln -s /bin/bash /bin/dash and see if that fixes the problem.
You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.
You can put your servers in the default_step
group and those vars will apply to it:
# inventory file
[default_step]
prod2
web_v2
Then just move your default_step.yml
file to group_vars/default_step.yml
.
Another solution:
inside the loop, use List instead of string.
List<string> lst= new List<string>();
for(int i=0; i<100000; i++){
...........
lst.Add(...);
}
return String.Join("", lst.ToArray());;
it is very very fast.
I tried installing the nodemon globally but that doesn't worked for me. whenever i try to run it always shows me the error:
nodemon : The term 'nodemon' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is
correct and try again.
2. I have found two solutions for this
solution 1:
What i have tried is to update the "scripts" in package.json file and there i have added
"server": "nodemon app.js"
above line of code and after that
npm run server
Soluton 2:
Press the Windows key.
Type "Path" in the search box and select "Edit the system environment variables"
Click on "Environment Variables" near the bottom.
In the "System Variables" section double click on the "Path" variable.
Click "New" on the right-hand side.
Copy and paste this into the box (replace [Username]):
C:\Users[Username]\AppData\Roaming\npm
restart your terminal and VSCode.
Then type nodemon app.js
to run the nodemon
i applied solution 2 as we just need to run nodemon [filename.js]
document.getElementsByClassName('CLASSNAME')[0].style.display = 'none';
Acyually by using getElementsByClassName, it returns an array of multiple classes. Because same class name could be used in more than one instance inside same HTML page. We use array element id to target the class we need, in my case, it's first instance of the given class name.So I've used [0]
Neither adding data-dismiss="modal"
nor using $("#modal").modal("hide")
in javascript worked for me. Sure they closed the modal but the ajax request is not sent either.
Instead, I rendered the partial containing the modals again after ajax is successful (I'm using ruby on rails). I also had to remove "modal-open"
class from the body tag too. This basically resets the modals. I think something similar, with a callback upon successful ajax request to remove and add back the modals should work in other framework too.
I ran into this issue but had a different fix. It involved updating the Control Panel>Administrative Tools>IIS Manager
and reverting my App site's Managed Pipeline from Integrated
to Classic
.
Actually, to make your favicon work in all browsers properly, you will have to add more than 10 files in the correct sizes and formats.
My friend and I have created an App just for this! you can find it in faviconit.com
We did this, so people don't have to create all these images and the correct tags by hand, create all of them used to annoy me a lot!
There is a way that's pretty memory inefficient.
single file:
import hashlib
def file_as_bytes(file):
with file:
return file.read()
print hashlib.md5(file_as_bytes(open(full_path, 'rb'))).hexdigest()
list of files:
[(fname, hashlib.md5(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
Recall though, that MD5 is known broken and should not be used for any purpose since vulnerability analysis can be really tricky, and analyzing any possible future use your code might be put to for security issues is impossible. IMHO, it should be flat out removed from the library so everybody who uses it is forced to update. So, here's what you should do instead:
[(fname, hashlib.sha256(file_as_bytes(open(fname, 'rb'))).digest()) for fname in fnamelst]
If you only want 128 bits worth of digest you can do .digest()[:16]
.
This will give you a list of tuples, each tuple containing the name of its file and its hash.
Again I strongly question your use of MD5. You should be at least using SHA1, and given recent flaws discovered in SHA1, probably not even that. Some people think that as long as you're not using MD5 for 'cryptographic' purposes, you're fine. But stuff has a tendency to end up being broader in scope than you initially expect, and your casual vulnerability analysis may prove completely flawed. It's best to just get in the habit of using the right algorithm out of the gate. It's just typing a different bunch of letters is all. It's not that hard.
Here is a way that is more complex, but memory efficient:
import hashlib
def hash_bytestr_iter(bytesiter, hasher, ashexstr=False):
for block in bytesiter:
hasher.update(block)
return hasher.hexdigest() if ashexstr else hasher.digest()
def file_as_blockiter(afile, blocksize=65536):
with afile:
block = afile.read(blocksize)
while len(block) > 0:
yield block
block = afile.read(blocksize)
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.md5()))
for fname in fnamelst]
And, again, since MD5 is broken and should not really ever be used anymore:
[(fname, hash_bytestr_iter(file_as_blockiter(open(fname, 'rb')), hashlib.sha256()))
for fname in fnamelst]
Again, you can put [:16]
after the call to hash_bytestr_iter(...)
if you only want 128 bits worth of digest.
I solved this error
A connection attempt failed with "ECONNREFUSED - Connection refused by server"
by changing my port to 22 that was successful
Join on the prices table, and then select the entry for the last day:
select pa.partid, pa.Partnumber, max(pr.price)
from myparts pa
inner join myprices pr on pr.partid = pa.partid
where pr.PriceDate = (
select max(PriceDate)
from myprices
where partid = pa.partid
)
The max() is in case there are multiple prices per day; I'm assuming you'd like to display the highest one. If your price table has an id column, you can avoid the max() and simplify like:
select pa.partid, pa.Partnumber, pr.price
from myparts pa
inner join myprices pr on pr.partid = pa.partid
where pr.priceid = (
select max(priceid)
from myprices
where partid = pa.partid
)
P.S. Use wcm's solution instead!
Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.
To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.
Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.
Hope it helps Rihan
Output is buffered.
stdout is line-buffered by default, which means that '\n' is supposed to flush the buffer. Why is it not happening in your case? I don't know. I need more info about your application/environment.
However, you can control buffering with setvbuf():
setvbuf(stdout, NULL, _IOLBF, 0);
This will force stdout to be line-buffered.
setvbuf(stdout, NULL, _IONBF, 0);
This will force stdout to be unbuffered, so you won't need to use fflush(). Note that it will severely affect application performance if you have lots of prints.
The following steps worked for me:
Clone it from github
git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew
Open your .bash_profile file using vi ~/.bash_profile
Add these lines
export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"
Then type the following lines in your terminal
export PATH=$HOME/.linuxbrew/bin:$PATH
hash -r
Yes, it is done. Type brew
in your terminal to check its existence.
To get the current year using PHP’s date function, you can pass in the “Y” format character like so:
//Getting the current year using //PHP's date function.
$year = date("Y");
echo $year;
//Getting the current year using //PHP's date function.
$year = date("Y");
echo $year;
The example above will print out the full 4-digit representation of the current year.
If you only want to retrieve the 2-digit format, then you can use the lowercase “y” format character:
$year = date("y"); echo $year; 1 2 $year = date("y"); echo $year; The snippet above will print out 20 instead of 2020, or 19 instead of 2019, etc.
dynDiv.Attributes["class"] = "myCssClass";
I came up with a solution similar to Christians but without depending on the Community MSBuild tasks, this is not an option for me as I do not want to install these tasks for all of our developers.
I am generating code and compiling to an Assembly and want to auto-increment version numbers. However, I can not use the VS 6.0.* AssemblyVersion trick as it auto-increments build numbers each day and breaks compatibility with Assemblies that use an older build number. Instead, I want to have a hard-coded AssemblyVersion but an auto-incrementing AssemblyFileVersion. I've accomplished this by specifying AssemblyVersion in the AssemblyInfo.cs and generating a VersionInfo.cs in MSBuild like this,
<PropertyGroup>
<Year>$([System.DateTime]::Now.ToString("yy"))</Year>
<Month>$([System.DateTime]::Now.ToString("MM"))</Month>
<Date>$([System.DateTime]::Now.ToString("dd"))</Date>
<Time>$([System.DateTime]::Now.ToString("HHmm"))</Time>
<AssemblyFileVersionAttribute>[assembly:System.Reflection.AssemblyFileVersion("$(Year).$(Month).$(Date).$(Time)")]</AssemblyFileVersionAttribute>
</PropertyGroup>
<Target Name="BeforeBuild">
<WriteLinesToFile File="Properties\VersionInfo.cs" Lines="$(AssemblyFileVersionAttribute)" Overwrite="true">
</WriteLinesToFile>
</Target>
This will generate a VersionInfo.cs file with an Assembly attribute for AssemblyFileVersion where the version follows the schema of YY.MM.DD.TTTT with the build date. You must include this file in your project and build with it.
Also, there is the issue of possible 2.0 rollback. Trust me it has happened to me a couple of times so I am sure it has happened to others.
I also agree that abstraction is the best. Along with the fact, the original purpose of an ORM is to make RDBMS match up nicely to the OO concepts. However, if everything worked fine before LINQ by having to deviate a bit from OO concepts then screw 'em. Concepts and reality don't always fit well together. There is no room for militant zealots in IT.
double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));
outputs:
1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875
Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).
More about double precision:
Yes. Look at http://jerrywickey.com/test/testJerrysLibrary.php
It gives sample code examples for RSA encryption and decryption in PHP as well as RSA encryption in javascript.
If you want to encrypt text instead of just base 10 numbers, you'll also need a base to base conversion. That is convert text to a very large number. Text is really just writing in base 63. 26 lowercase letters plus 26 uppercase + 10 numerals + space character. The code for that is below also.
The $GETn parameter is a file name that holds keys for the cryption functions. If you don't figure it out, ask. I'll help.
I actually posted this whole encryption library yesterday, but Brad Larson a mod, killed it and said this kind of stuff isn't really what Stack Overflow is about. But you can still find all the code examples and the whole function library to carry out client/server encryption decryption for AJAX at the link above.
function RSAencrypt( $num, $GETn){
if ( file_exists( 'temp/bigprimes'.hash( 'sha256', $GETn).'.php')){
$t= explode( '>,', file_get_contents('temp/bigprimes'.hash( 'sha256', $GETn).'.php'));
return JL_powmod( $num, $t[4], $t[10]);
}else{
return false;
}
}
function RSAdecrypt( $num, $GETn){
if ( file_exists( 'temp/bigprimes'.hash( 'sha256', $GETn).'.php')){
$t= explode( '>,', file_get_contents('temp/bigprimes'.hash( 'sha256', $GETn).'.php'));
return JL_powmod( $num, $t[8], $t[10]);
}else{
return false;
}
}
function JL_powmod( $num, $pow, $mod) {
if ( function_exists('bcpowmod')) {
return bcpowmod( $num, $pow, $mod);
}
$result= '1';
do {
if ( !bccomp( bcmod( $pow, '2'), '1')) {
$result = bcmod( bcmul( $result, $num), $mod);
}
$num = bcmod( bcpow( $num, '2'), $mod);
$pow = bcdiv( $pow, '2');
} while ( bccomp( $pow, '0'));
return $result;
}
function baseToBase ($message, $fromBase, $toBase){
$from= strlen( $fromBase);
$b[$from]= $fromBase;
$to= strlen( $toBase);
$b[$to]= $toBase;
$result= substr( $b[$to], 0, 1);
$f= substr( $b[$to], 1, 1);
$tf= digit( $from, $b[$to]);
for ($i=strlen($message)-1; $i>=0; $i--){
$result= badd( $result, bmul( digit( strpos( $b[$from], substr( $message, $i, 1)), $b[$to]), $f, $b[$to]), $b[$to]);
$f= bmul($f, $tf, $b[$to]);
}
return $result;
}
function digit( $from, $bto){
$to= strlen( $bto);
$b[$to]= $bto;
$t[0]= intval( $from);
$i= 0;
while ( $t[$i] >= intval( $to)){
if ( !isset( $t[$i+1])){
$t[$i+1]= 0;
}
while ( $t[$i] >= intval( $to)){
$t[$i]= $t[$i] - intval( $to);
$t[$i+1]++;
}
$i++;
}
$res= '';
for ( $i=count( $t)-1; $i>=0; $i--){
$res.= substr( $b[$to], $t[$i], 1);
}
return $res;
}
function badd( $n1, $n2, $nbase){
$base= strlen( $nbase);
$b[$base]= $nbase;
while ( strlen( $n1) < strlen( $n2)){
$n1= substr( $b[$base], 0, 1) . $n1;
}
while ( strlen( $n1) > strlen( $n2)){
$n2= substr( $b[$base], 0, 1) . $n2;
}
$n1= substr( $b[$base], 0, 1) . $n1;
$n2= substr( $b[$base], 0, 1) . $n2;
$m1= array();
for ( $i=0; $i<strlen( $n1); $i++){
$m1[$i]= strpos( $b[$base], substr( $n1, (strlen( $n1)-$i-1), 1));
}
$res= array();
$m2= array();
for ($i=0; $i<strlen( $n1); $i++){
$m2[$i]= strpos( $b[$base], substr( $n2, (strlen( $n1)-$i-1), 1));
$res[$i]= 0;
}
for ($i=0; $i<strlen( $n1) ; $i++){
$res[$i]= $m1[$i] + $m2[$i] + $res[$i];
if ($res[$i] >= $base){
$res[$i]= $res[$i] - $base;
$res[$i+1]++;
}
}
$o= '';
for ($i=0; $i<strlen( $n1); $i++){
$o= substr( $b[$base], $res[$i], 1).$o;
}
$t= false;
$o= '';
for ($i=strlen( $n1)-1; $i>=0; $i--){
if ($res[$i] > 0 || $t){
$o.= substr( $b[$base], $res[$i], 1);
$t= true;
}
}
return $o;
}
function bmul( $n1, $n2, $nbase){
$base= strlen( $nbase);
$b[$base]= $nbase;
$m1= array();
for ($i=0; $i<strlen( $n1); $i++){
$m1[$i]= strpos( $b[$base], substr($n1, (strlen( $n1)-$i-1), 1));
}
$m2= array();
for ($i=0; $i<strlen( $n2); $i++){
$m2[$i]= strpos( $b[$base], substr($n2, (strlen( $n2)-$i-1), 1));
}
$res= array();
for ($i=0; $i<strlen( $n1)+strlen( $n2)+2; $i++){
$res[$i]= 0;
}
for ($i=0; $i<strlen( $n1) ; $i++){
for ($j=0; $j<strlen( $n2) ; $j++){
$res[$i+$j]= ($m1[$i] * $m2[$j]) + $res[$i+$j];
while ( $res[$i+$j] >= $base){
$res[$i+$j]= $res[$i+$j] - $base;
$res[$i+$j+1]++;
}
}
}
$t= false;
$o= '';
for ($i=count( $res)-1; $i>=0; $i--){
if ($res[$i]>0 || $t){
$o.= substr( $b[$base], $res[$i], 1);
$t= true;
}
}
return $o;
}
I built a laravel package for making statistics : https://github.com/Ifnot/statistics
It is based on eloquent, carbon and indicators so it is really easy to use. It may be usefull for extracting date grouped indicators.
$statistics = Statistics::of(MyModel::query());
$statistics->date('validated_at');
$statistics->interval(Interval::$DAILY, Carbon::createFromFormat('Y-m-d', '2016-01-01'), Carbon::now())
$statistics->indicator('total', function($row) {
return $row->counter;
});
$data = $statistics->make();
echo $data['2016-01-01']->total;
```
Here's a simple solution
<form method="post" enctype="multipart/form-data">
<input type="text" name="db" placeholder="Databasename" />
<input type="file" name="file">
<input type="submit" name="submit" value="submit">
</form>
<?php
if(isset($_POST['submit'])){
$query = file_get_contents($_FILES["file"]["name"]);
$dbname = $_POST['db'];
$con = new PDO("mysql:host=localhost;dbname=$dbname","root","");
$stmt = $con->prepare($query);
if($stmt->execute()){
echo "Successfully imported to the $dbname.";
}
}
?>
Definitely working on my end. Worth a try.
It seems to me that if a collection has a mode, then its elements can be mapped one-to-one with the natural numbers. So, the problem of finding the mode reduces to producing such a mapping, finding the mode of the mapped values, then mapping back to some of the items in the collection. (Dealing with NA
occurs at the mapping phase).
I have a histogram
function that operates on a similar principal. (The special functions and operators used in the code presented herein should be defined in Shapiro and/or the neatOveRse. The portions of Shapiro and neatOveRse duplicated herein are so duplicated with permission; the duplicated snippets may be used under the terms of this site.) R pseudocode for histogram
is
.histogram <- function (i)
if (i %|% is.empty) integer() else
vapply2(i %|% max %|% seqN, `==` %<=% i %O% sum)
histogram <- function(i) i %|% rmna %|% .histogram
(The special binary operators accomplish piping, currying, and composition) I also have a maxloc
function, which is similar to which.max
, but returns all the absolute maxima of a vector. R pseudocode for maxloc
is
FUNloc <- function (FUN, x, na.rm=F)
which(x == list(identity, rmna)[[na.rm %|% index.b]](x) %|% FUN)
maxloc <- FUNloc %<=% max
minloc <- FUNloc %<=% min # I'M THROWING IN minloc TO EXPLAIN WHY I MADE FUNloc
Then
imode <- histogram %O% maxloc
and
x %|% map %|% imode %|% unmap
will compute the mode of any collection, provided appropriate map
-ping and unmap
-ping functions are defined.
Assuming userInfoList
is a List<UserInfo>
:
var groups = userInfoList
.GroupBy(n => n.metric)
.Select(n => new
{
MetricName = n.Key,
MetricCount = n.Count()
}
)
.OrderBy(n => n.MetricName);
The lambda function for GroupBy()
, n => n.metric
means that it will get field metric
from every UserInfo
object encountered. The type of n
is depending on the context, in the first occurrence it's of type UserInfo
, because the list contains UserInfo
objects. In the second occurrence n
is of type Grouping
, because now it's a list of Grouping
objects.
Grouping
s have extension methods like .Count()
, .Key()
and pretty much anything else you would expect. Just as you would check .Lenght
on a string
, you can check .Count()
on a group.
just declare the member variables to private in the class you want to convert to XML. Happy coding
std::atomic
exists because many ISAs have direct hardware support for it
What the C++ standard says about std::atomic
has been analyzed in other answers.
So now let's see what std::atomic
compiles to to get a different kind of insight.
The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic
basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.
This support allows for faster alternatives to more general methods such as std::mutex
, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic
because std::mutex
it makes futex
system calls in Linux, which is way slower than the userland instructions emitted by std::atomic
, see also: Does std::mutex create a fence?
Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.
main.cpp
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>
size_t niters;
#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif
void threadMain() {
for (size_t i = 0; i < niters; ++i) {
#if LOCK
__asm__ __volatile__ (
"lock incq %0;"
: "+m" (global),
"+g" (i) // to prevent loop unrolling
:
:
);
#else
__asm__ __volatile__ (
""
: "+g" (i) // to prevent he loop from being optimized to a single add
: "g" (global)
:
);
global++;
#endif
}
}
int main(int argc, char **argv) {
size_t nthreads;
if (argc > 1) {
nthreads = std::stoull(argv[1], NULL, 0);
} else {
nthreads = 2;
}
if (argc > 2) {
niters = std::stoull(argv[2], NULL, 0);
} else {
niters = 10;
}
std::vector<std::thread> threads(nthreads);
for (size_t i = 0; i < nthreads; ++i)
threads[i] = std::thread(threadMain);
for (size_t i = 0; i < nthreads; ++i)
threads[i].join();
uint64_t expect = nthreads * niters;
std::cout << "expect " << expect << std::endl;
std::cout << "global " << global << std::endl;
}
Compile, run and disassemble:
comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out -DLOCK $common
./main_fail.out 4 100000
./main_std_atomic.out 4 100000
./main_lock.out 4 100000
gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out
Extremely likely "wrong" race condition output for main_fail.out
:
expect 400000
global 100000
and deterministic "right" output of the others:
expect 400000
global 400000
Disassembly of main_fail.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: mov 0x29b5(%rip),%rcx # 0x5140 <niters>
0x000000000000278b <+11>: test %rcx,%rcx
0x000000000000278e <+14>: je 0x27b4 <threadMain()+52>
0x0000000000002790 <+16>: mov 0x29a1(%rip),%rdx # 0x5138 <global>
0x0000000000002797 <+23>: xor %eax,%eax
0x0000000000002799 <+25>: nopl 0x0(%rax)
0x00000000000027a0 <+32>: add $0x1,%rax
0x00000000000027a4 <+36>: add $0x1,%rdx
0x00000000000027a8 <+40>: cmp %rcx,%rax
0x00000000000027ab <+43>: jb 0x27a0 <threadMain()+32>
0x00000000000027ad <+45>: mov %rdx,0x2984(%rip) # 0x5138 <global>
0x00000000000027b4 <+52>: retq
Disassembly of main_std_atomic.out
:
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a6 <threadMain()+38>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock addq $0x1,0x299f(%rip) # 0x5138 <global>
0x0000000000002799 <+25>: add $0x1,%rax
0x000000000000279d <+29>: cmp %rax,0x299c(%rip) # 0x5140 <niters>
0x00000000000027a4 <+36>: ja 0x2790 <threadMain()+16>
0x00000000000027a6 <+38>: retq
Disassembly of main_lock.out
:
Dump of assembler code for function threadMain():
0x0000000000002780 <+0>: endbr64
0x0000000000002784 <+4>: cmpq $0x0,0x29b4(%rip) # 0x5140 <niters>
0x000000000000278c <+12>: je 0x27a5 <threadMain()+37>
0x000000000000278e <+14>: xor %eax,%eax
0x0000000000002790 <+16>: lock incq 0x29a0(%rip) # 0x5138 <global>
0x0000000000002798 <+24>: add $0x1,%rax
0x000000000000279c <+28>: cmp %rax,0x299d(%rip) # 0x5140 <niters>
0x00000000000027a3 <+35>: ja 0x2790 <threadMain()+16>
0x00000000000027a5 <+37>: retq
Conclusions:
the non-atomic version saves the global to a register, and increments the register.
Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000
.
std::atomic
compiles to lock addq
. The LOCK prefix makes the following inc
fetch, modify and update memory atomically.
our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic
, except that our inc
is used instead of add
. Not sure why GCC chose add
, considering that our INC generated a decoding 1 byte smaller.
ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?
Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.
The following code will disable mouse right click from full page.
$(document).ready(function () {
$("body").on("contextmenu",function(e){
return false;
});
});
The full tutorial and working demo can be found from here - Disable mouse right click using jQuery
Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.
If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.
If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.
It could be a solution:
Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*
Load the address again once you have replaced uc with open in the address.
This loads a new screen with controls at the top.
Click on the "add to my drive" icon at the top right.
Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.
You should see the locked file on your drive now.
Select it with a right-click, and then the "make a copy" option from the menu.
8.Select the copy of the file with a right-click, and there download to download the file to your local system.
Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.
Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.
Another option is: Any public folder in Drive can host files and provide direct links to the files.
How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)
This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.
My solution:
I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it
Traffic limits DROPBOX
Links and file requests are automatically banned if they generate unusually large amounts of traffic.
Dropbox Basic (free) accounts:
20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate
Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.
P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!
If you want to have the item remain highlighted after you have clicked it, you need to manually set it as being selected in the onItemClick listener
Android ListView selected item stay highlighted:
myList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
view.setSelected(true); // <== Will cause the highlight to remain
//... do more stuff
}});
This assumes you have a state_selected item in your selector:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:state_pressed="true" android:drawable="@color/red" />
<item android:state_enabled="true" android:state_focused="true" android:drawable="@color/red" />
<item android:state_enabled="true" android:state_selected="true" android:drawable="@color/red" />
<item android:drawable="@color/white" />
</selector>
If you are using linux, and the data file is from windows. It probably because the character ^M Find it and delete. done!
You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.
for other type of products it will automatically restore it.
Please read following text which will clear your concept about this :
Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.
Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.
If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices
Camel sends messages from A to B:
Why a whole framework for this? Well, what if you have:
ftp
, http
, jms
, etc.)So now you need:
Camel gives you the above (and more) out of the box:
with a cool DSL language for you to define the what and how:
new DefaultCamelContext().addRoutes(new RouteBuilder() {
public void configure() {
from("jms:incomingMessages")
.choice() // start router rules
.when(header("CamelFileName")
.endsWith(".xml"))
.to("jms:xmlMessages")
.when(header("CamelFileName")
.endsWith(".csv"))
.to("ftp:csvMessages");
}
See also this and this and Camel in Action (as others have said, an excellent book!)
We can use hashing to our leverage if you can abstract a single pair of socks as the key itself and its other pair as value.
Make two imaginary sections behind you on the floor, one for you and another for your spouse.
Take one from the pile of socks.
Now place the socks on the floor, one by one, following the below rule.
Identify the socks as yours or hers and look at the relevant section on the floor.
If you can spot the pair on the floor pick it up and knot them up or clip them up or do whatever you would do after you find a pair and place it in a basket (remove it from the floor).
Place it in the relevant section.
Repeat 3 until all socks are over from the pile.
Hashing and Abstraction
Abstraction is a very powerful concept that has been used to improve user experience (UX). Examples of abstraction in real-life interactions with computers include:
Hashing or other not-in-place solutions are not an option because I am not able to duplicate my socks (though it could be nice if I could).
I believe the asker was thinking of applying hashing such that the slot to which either pair of sock goes should be known before placing them.
That's why I suggested abstracting a single sock that is placed on the floor as the hash key itself (hence there is no need to duplicate the socks).
How to define our hash key?
The below definition for our key would also work if there are more than one pair of similar socks. That is, let's say there are two pairs of black men socks PairA and PairB, and each sock is named PairA-L, PairA-R, PairB-L, PairB-R. So PairA-L can be paired with PairB-R, but PairA-L and PairB-L cannot be paired.
Let say any sock can be uniqly identified by,
Attribute[Gender] + Attribute[Colour] + Attribute[Material] + Attribute[Type1] + Attribute[Type2] + Attribute[Left_or_Right]
This is our first hash function. Let's use a short notation for this h1(G_C_M_T1_T2_LR)
. h1(x) is not our location key.
Another hash function eliminating the Left_or_Right attribute would be h2(G_C_M_T1_T2)
. This second function h2(x) is our location key! (for the space on the floor behind you).
NOTE: Since we remove a pair once we find one, it's safe to assume that there would only be at a maximum one slot with a unique h2(x) or h1(x) value.
In case we have each sock with exactly one matching pair then use h2(x) for finding the location and if no pair, a check is required, since it's safe to assume they are a pair.
Why is it important to lay the socks on the floor
Let's consider a scenario where the socks are stacked over one another in a pile (worst case). This means we would have no other choice but to do a linear search to find a pair.
Spreading them on the floor gives more visibility which improves the chance of spotting the matching sock (matching a hash key). When a sock was placed on the floor in step 3, our mind had subconsciously registered the location. - So in case, this location is available in our memory we can directly find the matching pair. - In case the location is not remembered, don't worry, then we can always revert back to linear search.
Why is it important to remove the pair from the floor?
Analysis
I am talking about comparison operations, picking the socks from the pile would necessarily be n number of operations. So a practical lower bound would be n iterations with n/2 comparisons.
Speeding up things
To achieve a perfect score so Derp gets O(n/2) comparisons, I would recommend Derpina to,
Is this equivalent to the element distinctness problem?
The method I suggested is one of the methods used to solve element distinctness problem where you place them in the hash table and do the comparison.
Given your special case where there exists only one exact pair, it has become very much equivalent to the element distinct problem. Since we can even sort the socks and check adjacent socks for pairs (another solution for EDP).
However, if there is a possibility of more than one pair that can exist for given sock then it deviates from EDP.
Use JQuery Hover
to add/remove class or style on Hover:
$( "mah div" ).hover(
function() {
$( this ).css("background-color","red");
}, function() {
$( this ).css("background-color",""); //to remove property set it to ''
}
);
Im not a java developer but was using a java app to test a RESTful API. In order for me to fix the error I had to install the intermediate certificates in the webserver in order to make the error go away. I was using lighttpd, the original certificate was installed on an IIS server. Hope it helps. These were the certificates I had missing on the server.
Try this:
String LINK = "type_here_the_link";
setContentView(R.layout.mediaplayer);
VideoView videoView = (VideoView) findViewById(R.id.video);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri video = Uri.parse(LINK);
videoView.setMediaController(mc);
videoView.setVideoURI(video);
videoView.start();
If you mean, you want to scroll through multiple items in your stackpanel, try putting a grid around it. By definition, a stackpanel has infinite length.
So try something like this:
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel Width="311">
<TextBlock Text="{Binding A}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" FontStretch="Condensed" FontSize="28" />
<TextBlock Text="{Binding B}" TextWrapping="Wrap" Margin="12,-6,12,0" Style="{StaticResource PhoneTextSubtleStyle}"/>
</StackPanel>
</Grid>
You could even make this work with a ScrollViewer
I will leave the way I do to submit the form without using the name
tag inside the form:
<button type="submit" onClick="placeOrder(this.form)">Place Order</button>
function placeOrder(form){
form.submit();
}
when(
fooDao.getBar(
any(Bazoo.class)
)
).thenReturn(myFoo);
or (to avoid null
s):
when(
fooDao.getBar(
(Bazoo)notNull()
)
).thenReturn(myFoo);
Don't forget to import matchers (many others are available):
For Mockito 2.1.0 and newer:
import static org.mockito.ArgumentMatchers.*;
For older versions:
import static org.mockito.Matchers.*;
Try the Currency Format Specifier ("C"). It automatically takes the current UI culture into account and displays currency values accordingly.
You can use it with either String.Format
or the overloaded ToString
method for a numeric type.
For example:
double value = 12345.6789;
Console.WriteLine(value.ToString("C", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CurrentCulture));
Console.WriteLine(value.ToString("C3", CultureInfo.CreateSpecificCulture("da-DK")));
// The example displays the following output on a system whose
// current culture is English (United States):
// $12,345.68
// $12,345.679
// kr 12.345,679
For hidden files I had to use the following:
DEL /S /Q /A:H Thumbs.db
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
MS provides the OpenXML SDK V 2.5 - see https://msdn.microsoft.com/en-us/library/bb448854(v=office.15).aspx
This can read+write MS Office files (including Excel)...
Another option see http://www.codeproject.com/KB/office/OpenXML.aspx
IF you need more like rendering, formulas etc. then there are different commercial libraries like Aspose and Flexcel...
With Python3x, you need to convert your string to raw bytes. You would have to encode the string as bytes. Over the network you need to send bytes and not characters. You are right that this would work for Python 2x since in Python 2x, socket.sendto on a socket takes a "plain" string and not bytes. Try this:
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))
If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.
$data = json_decode($json, TRUE);
Take below reference to convert a JSON into POJO and vice-versa
Let's suppose your JSON schema looks like:
{
"type":"object",
"properties": {
"dataOne": {
"type": "string"
},
"dataTwo": {
"type": "integer"
},
"dataThree": {
"type": "boolean"
}
}
}
Then to covert into POJO, your need to decleare some classes as explained in below style:
==================================
package ;
public class DataOne
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataTwo
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class DataThree
{
private String type;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
}
==================================
package ;
public class Properties
{
private DataOne dataOne;
private DataTwo dataTwo;
private DataThree dataThree;
public void setDataOne(DataOne dataOne){
this.dataOne = dataOne;
}
public DataOne getDataOne(){
return this.dataOne;
}
public void setDataTwo(DataTwo dataTwo){
this.dataTwo = dataTwo;
}
public DataTwo getDataTwo(){
return this.dataTwo;
}
public void setDataThree(DataThree dataThree){
this.dataThree = dataThree;
}
public DataThree getDataThree(){
return this.dataThree;
}
}
==================================
package ;
public class Root
{
private String type;
private Properties properties;
public void setType(String type){
this.type = type;
}
public String getType(){
return this.type;
}
public void setProperties(Properties properties){
this.properties = properties;
}
public Properties getProperties(){
return this.properties;
}
}
Aligning to 6 bytes is not weird, because it is aligning to addresses multiple to 4.
So basically you have 34 bytes in your structure and the next structure should be placed on the address, that is multiple to 4. The closest value after 34 is 36. And this padding area counts into the size of the structure.
A class based clean to use solution:
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while not killer.kill_now:
time.sleep(1)
print("doing something in a loop ...")
print("End of the program. I was killed gracefully :)")
There is a much more concise way to do this. Arguments to a bash script can be brought into an array, which makes dealing with the elements much simpler. The script below will always print the last argument passed to a script.
argArray=( "$@" ) # Add all script arguments to argArray
arrayLength=${#argArray[@]} # Get the length of the array
lastArg=$((arrayLength - 1)) # Arrays are zero based, so last arg is -1
echo ${argArray[$lastArg]}
Sample output
$ ./lastarg.sh 1 2 buckle my shoe
shoe
Use Thread.sleep(2000); //2000 for 2 seconds
Consider the case where you don't control or own the base classes.
Take visual controls for instance, in .NET for Winforms they all inherit from the base class Control, that is completely defined in the .NET framework.
Let's assume you're in the business of creating custom controls. You want to build new buttons, textboxes, listviews, grids, whatnot and you'd like them all to have certain features unique to your set of controls.
For instance you might want a common way to handle theming, or a common way to handle localization.
In this case you can't "just create a base class" because if you do that, you have to reimplement everything that relates to controls.
Instead you will descend from Button, TextBox, ListView, GridView, etc. and add your code.
But this poses a problem, how can you now identify which controls are "yours", how can you build some code that says "for all the controls on the form that are mine, set the theme to X".
Enter interfaces.
Interfaces are a way to look at an object, to determine that the object adheres to a certain contract.
You would create "YourButton", descend from Button, and add support for all the interfaces you need.
This would allow you to write code like the following:
foreach (Control ctrl in Controls)
{
if (ctrl is IMyThemableControl)
((IMyThemableControl)ctrl).SetTheme(newTheme);
}
This would not be possible without interfaces, instead you would have to write code like this:
foreach (Control ctrl in Controls)
{
if (ctrl is MyThemableButton)
((MyThemableButton)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableTextBox)
((MyThemableTextBox)ctrl).SetTheme(newTheme);
else if (ctrl is MyThemableGridView)
((MyThemableGridView)ctrl).SetTheme(newTheme);
else ....
}
A slightly different approach to implement the singleton in Python is the borg pattern by Alex Martelli (Google employee and Python genius).
class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state
So instead of forcing all instances to have the same identity, they share state.
You can try this.
txt = <file_path>
txt_opn = open(txt)
print txt_opn.read()
This will give you file output.
Try this:
<html>
<table>
<tr>
<td style="padding-left: 5px;
padding-bottom: 3px;">
<strong style="font-size: 35px;">Datum:</strong><br />
November 2010
</td>
</tr>
</table>
</html>
Notice that I also included the table-tag, which you seem to have forgotten. This has to be included if you want this to appear as a table.
Use the standard XPath function contains().
Function: boolean contains(string, string)
The contains function returns true if the first argument string contains the second argument string, and otherwise returns false
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
You can use parameter substitution in the twig globals section of the config:
Parameter config:
parameters:
app.version: 0.1.0
Twig config:
twig:
globals:
version: '%app.version%'
Twig template:
{{ version }}
This method provides the benefit of allowing you to use the parameter in ContainerAware
classes as well, using:
$container->getParameter('app.version');
We can add "AwaitTerminationSeconds" property for both taskExecutor and taskScheduler as below,
<property name="awaitTerminationSeconds" value="${taskExecutor .awaitTerminationSeconds}" />
<property name="awaitTerminationSeconds" value="${taskScheduler .awaitTerminationSeconds}" />
Documentation for "waitForTasksToCompleteOnShutdown" property says, when shutdown is called
"Spring's container shutdown continues while ongoing tasks are being completed. If you want this executor to block and wait for the termination of tasks before the rest of the container continues to shut down - e.g. in order to keep up other resources that your tasks may need -, set the "awaitTerminationSeconds" property instead of or in addition to this property."
So it is always advised to use waitForTasksToCompleteOnShutdown and awaitTerminationSeconds properties together. Value of awaitTerminationSeconds depends on our application.
We are also looking for some way to convert html files with complex javascript to pdf.
The javasript in our files contains document.write
and DOM manipulation.
We have tried using a combination of HtmlUnit to parse the files and Flying Saucer to render to pdf but the results are not satisfactory enough. It works, but in our case the pdf is not close enough to what the user wants.
If you want to try this out, here is a code snippet to convert a local html file to pdf.
URL url = new File("test.html").toURI().toURL();
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(url);
OutputStream os = null;
try{
os = new FileOutputStream("test.pdf");
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(page,url.toString());
renderer.layout();
renderer.createPDF(os);
} finally{
if(os != null) os.close();
}
Firstly, in general:
If these .h
files are indeed typical C-style header files (as opposed to being something completely different that just happens to be named with .h
extension), then no, there's no reason to "compile" these header files independently. Header files are intended to be included into implementation files, not fed to the compiler as independent translation units.
Since a typical header file usually contains only declarations that can be safely repeated in each translation unit, it is perfectly expected that "compiling" a header file will have no harmful consequences. But at the same time it will not achieve anything useful.
Basically, compiling hello.h
as a standalone translation unit equivalent to creating a degenerate dummy.c
file consisting only of #include "hello.h"
directive, and feeding that dummy.c
file to the compiler. It will compile, but it will serve no meaningful purpose.
Secondly, specifically for GCC:
Many compilers will treat files differently depending on the file name extension. GCC has special treatment for files with .h
extension when they are supplied to the compiler as command-line arguments. Instead of treating it as a regular translation unit, GCC creates a precompiled header file for that .h
file.
You can read about it here: http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html
So, this is the reason you might see .h
files being fed directly to GCC.
The only way I able to get this to work was by doing this on the presenting view controller:
func didTapButton() {
self.definesPresentationContext = true
self.modalTransitionStyle = .crossDissolve
let yourVC = self.storyboard?.instantiateViewController(withIdentifier: "YourViewController") as! YourViewController
let navController = UINavigationController(rootViewController: yourVC)
navController.modalPresentationStyle = .overCurrentContext
navController.modalTransitionStyle = .crossDissolve
self.present(navController, animated: true, completion: nil)
}
Stub is a function definition that has correct function name, the correct number of parameters and produces dummy result of the correct type.
It helps to write the test and serves as a kind of scaffolding to make it possible to run the examples even before the function design is complete
ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.
Instead, you need to wrap that form in code something like this:
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Sign Up" />
}
This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp()
method, assuming your routes are properly set up (the defaults should work).
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO product_cate (site_title, sub_title)
VALUES ('$site_title', '$sub_title')";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO menu (menu_title, sub_menu)
VALUES ('$menu_title', '$sub_menu', )";
// db table name / blog_post / menu / site_title
// Insert into Table (column names separated with comma)
$sql = "INSERT INTO blog_post (post_title, post_des, post_img)
VALUES ('$post_title ', '$post_des', '$post_img')";
Here are my two solutions.
Short answer:
Instead of creating a layer-list
, I separated it into two files. One for ProgressBar
and one for its background.
This is the ProgressDrawable
file (@drawable folder): circular_progress_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromDegrees="270"
android:toDegrees="270">
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thickness="1dp"
android:useLevel="true"><!-- this line fixes the issue for lollipop api 21 -->
<gradient
android:angle="0"
android:endColor="#007DD6"
android:startColor="#007DD6"
android:type="sweep"
android:useLevel="false" />
</shape>
</rotate>
And this is for its background
(@drawable folder): circle_shape.xml
<?xml version="1.0" encoding="utf-8"?>
<shape
xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring"
android:innerRadiusRatio="2.5"
android:thickness="1dp"
android:useLevel="false">
<solid android:color="#CCC" />
</shape>
And at the end, inside the layout that you're working:
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="200dp"
android:layout_height="200dp"
android:indeterminate="false"
android:progressDrawable="@drawable/circular_progress_bar"
android:background="@drawable/circle_shape"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="65" />
Here's the result:
Long Answer:
Use a custom view which inherits the android.view.View
Here is the full project on github
In order to clarify the question, I would rather categorize the usage of 'static' keyword in three different forms:
(A). variables
(B). functions
(C). member variables/functions of classes
the explanation follows below for each of the sub headings:
(A) 'static' keyword for variables
This one can be little tricky however if explained and understood properly, it's pretty straightforward.
To explain this, first it is really useful to know about the scope, duration and linkage of variables, without which things are always difficult to see through the murky concept of staic keyword
1. Scope : Determines where in the file, the variable is accessible. It can be of two types: (i) Local or Block Scope. (ii) Global Scope
2. Duration : Determines when a variable is created and destroyed. Again it's of two types: (i) Automatic Storage Duration (for variables having Local or Block scope). (ii) Static Storage Duration (for variables having Global Scope or local variables (in a function or a in a code block) with static specifier).
3. Linkage: Determines whether a variable can be accessed (or linked ) in another file. Again ( and luckily) it is of two types: (i) Internal Linkage (for variables having Block Scope and Global Scope/File Scope/Global Namespace scope) (ii) External Linkage (for variables having only for Global Scope/File Scope/Global Namespace Scope)
Let's refer an example below for better understanding of plain global and local variables (no local variables with static storage duration) :
//main file
#include <iostream>
int global_var1; //has global scope
const global_var2(1.618); //has global scope
int main()
{
//these variables are local to the block main.
//they have automatic duration, i.e, they are created when the main() is
// executed and destroyed, when main goes out of scope
int local_var1(23);
const double local_var2(3.14);
{
/* this is yet another block, all variables declared within this block are
have local scope limited within this block. */
// all variables declared within this block too have automatic duration, i.e,
/*they are created at the point of definition within this block,
and destroyed as soon as this block ends */
char block_char1;
int local_var1(32) //NOTE: this has been re-declared within the block,
//it shadows the local_var1 declared outside
std::cout << local_var1 <<"\n"; //prints 32
}//end of block
//local_var1 declared inside goes out of scope
std::cout << local_var1 << "\n"; //prints 23
global_var1 = 29; //global_var1 has been declared outside main (global scope)
std::cout << global_var1 << "\n"; //prints 29
std::cout << global_var2 << "\n"; //prints 1.618
return 0;
} //local_var1, local_var2 go out of scope as main ends
//global_var1, global_var2 go out of scope as the program terminates
//(in this case program ends with end of main, so both local and global
//variable go out of scope together
Now comes the concept of Linkage. When a global variable defined in one file is intended to be used in another file, the linkage of the variable plays an important role.
The Linkage of global variables is specified by the keywords: (i) static , and, (ii) extern
( Now you get the explanation )
static keyword can be applied to variables with local and global scope, and in both the cases, they mean different things. I will first explain the usage of 'static' keyword in variables with global scope ( where I also clarify the usage of keyword 'extern') and later the for those with local scope.
Global variables have static duration, meaning they don't go out of scope when a particular block of code (for e.g main() ) in which it is used ends . Depending upon the linkage, they can be either accessed only within the same file where they are declared (for static global variable), or outside the file even outside the file in which they are declared (extern type global variables)
In the case of a global variable having extern specifier, and if this variable is being accessed outside the file in which it has been initialized, it has to be forward declared in the file where it's being used, just like a function has to be forward declared if it's definition is in a file different from where it's being used.
In contrast, if the global variable has static keyword, it cannot be used in a file outside of which it has been declared.
(see example below for clarification)
eg:
//main2.cpp
static int global_var3 = 23; /*static global variable, cannot be
accessed in anyother file */
extern double global_var4 = 71; /*can be accessed outside this file linked to main2.cpp */
int main() { return 0; }
main3.cpp
//main3.cpp
#include <iostream>
int main()
{
extern int gloabl_var4; /*this variable refers to the gloabal_var4
defined in the main2.cpp file */
std::cout << global_var4 << "\n"; //prints 71;
return 0;
}
now any variable in c++ can be either a const or a non-const and for each 'const-ness' we get two case of default c++ linkage, in case none is specified:
(i) If a global variable is non-const, its linkage is extern by default, i.e, the non-const global variable can be accessed in another .cpp file by forward declaration using the extern keyword (in other words, non const global variables have external linkage ( with static duration of course)). Also usage of extern keyword in the original file where it has been defined is redundant. In this case to make a non-const global variable inaccessible to external file, use the specifier 'static' before the type of the variable.
(ii) If a global variable is const, its linkage is static by default, i.e a const global variable cannot be accessed in a file other than where it is defined, (in other words, const global variables have internal linkage (with static duration of course)). Also usage of static keyword to prevent a const global variable from being accessed in another file is redundant. Here, to make a const global variable have an external linkage, use the specifier 'extern' before the type of the variable
Here's a summary for global scope variables with various linkages
//globalVariables1.cpp
// defining uninitialized vairbles
int globalVar1; // uninitialized global variable with external linkage
static int globalVar2; // uninitialized global variable with internal linkage
const int globalVar3; // error, since const variables must be initialized upon declaration
const int globalVar4 = 23; //correct, but with static linkage (cannot be accessed outside the file where it has been declared*/
extern const double globalVar5 = 1.57; //this const variable ca be accessed outside the file where it has been declared
Next we investigate how the above global variables behave when accessed in a different file.
//using_globalVariables1.cpp (eg for the usage of global variables above)
// Forward declaration via extern keyword:
extern int globalVar1; // correct since globalVar1 is not a const or static
extern int globalVar2; //incorrect since globalVar2 has internal linkage
extern const int globalVar4; /* incorrect since globalVar4 has no extern
specifier, limited to internal linkage by
default (static specifier for const variables) */
extern const double globalVar5; /*correct since in the previous file, it
has extern specifier, no need to initialize the
const variable here, since it has already been
legitimately defined perviously */
Updates (August 2019) on static keyword for variables in local scope
This further can be subdivided in two categories :
(i) static keyword for variables within a function block, and (ii) static keyword for variables within a unnamed local block.
(i) static keyword for variables within a function block.
Earlier, I mentioned that variables with local scope have automatic duration, i.e they come to exist when the block is entered ( be it a normal block, be it a function block) and cease to exist when the block ends, long story short, variables with local scope have automatic duration and automatic duration variables (and objects) have no linkage meaning they are not visible outside the code block.
If static specifier is applied to a local variable within a function block, it changes the duration of the variable from automatic to static and its life time is the entire duration of the program which means it has a fixed memory location and its value is initialized only once prior to program start up as mentioned in cpp reference(initialization should not be confused with assignment)
lets take a look at an example.
//localVarDemo1.cpp
int localNextID()
{
int tempID = 1; //tempID created here
return tempID++; //copy of tempID returned and tempID incremented to 2
} //tempID destroyed here, hence value of tempID lost
int newNextID()
{
static int newID = 0;//newID has static duration, with internal linkage
return newID++; //copy of newID returned and newID incremented by 1
} //newID doesn't get destroyed here :-)
int main()
{
int employeeID1 = localNextID(); //employeeID1 = 1
int employeeID2 = localNextID(); // employeeID2 = 1 again (not desired)
int employeeID3 = newNextID(); //employeeID3 = 0;
int employeeID4 = newNextID(); //employeeID4 = 1;
int employeeID5 = newNextID(); //employeeID5 = 2;
return 0;
}
Looking at the above criterion for static local variables and static global variables, one might be tempted to ask, what the difference between them could be. While global variables are accessible at any point in within the code (in same as well as different translation unit depending upon the const-ness and extern-ness), a static variable defined within a function block is not directly accessible. The variable has to be returned by the function value or reference. Lets demonstrate this by an example:
//localVarDemo2.cpp
//static storage duration with global scope
//note this variable can be accessed from outside the file
//in a different compilation unit by using `extern` specifier
//which might not be desirable for certain use case.
static int globalId = 0;
int newNextID()
{
static int newID = 0;//newID has static duration, with internal linkage
return newID++; //copy of newID returned and newID incremented by 1
} //newID doesn't get destroyed here
int main()
{
//since globalId is accessible we use it directly
const int globalEmployee1Id = globalId++; //globalEmployeeId1 = 0;
const int globalEmployee2Id = globalId++; //globalEmployeeId1 = 1;
//const int employeeID1 = newID++; //this will lead to compilation error since newID++ is not accessible direcly.
int employeeID2 = newNextID(); //employeeID3 = 0;
int employeeID2 = newNextID(); //employeeID3 = 1;
return 0;
}
More explaination about choice of static global and static local variable could be found on this stackoverflow thread
(ii) static keyword for variables within a unnamed local block.
static variables within a local block (not a function block) cannot be accessed outside the block once the local block goes out of scope. No caveats to this rule.
//localVarDemo3.cpp
int main()
{
{
const static int static_local_scoped_variable {99};
}//static_local_scoped_variable goes out of scope
//the line below causes compilation error
//do_something is an arbitrary function
do_something(static_local_scoped_variable);
return 0;
}
C++11 introduced the keyword constexpr
which guarantees the evaluation of an expression at compile time and allows compiler to optimize the code. Now if the value of a static const variable within a scope is known at compile time, the code is optimized in a manner similar to the one with constexpr
. Here's a small example
I recommend readers also to look up the difference between constexpr
and static const
for variables in this stackoverflow thread.
this concludes my explanation for the static keyword applied to variables.
B. 'static' keyword used for functions
in terms of functions, the static keyword has a straightforward meaning. Here, it refers to linkage of the function Normally all functions declared within a cpp file have external linkage by default, i.e a function defined in one file can be used in another cpp file by forward declaration.
using a static keyword before the function declaration limits its linkage to internal , i.e a static function cannot be used within a file outside of its definition.
C. Staitc Keyword used for member variables and functions of classes
1. 'static' keyword for member variables of classes
I start directly with an example here
#include <iostream>
class DesignNumber
{
private:
static int m_designNum; //design number
int m_iteration; // number of iterations performed for the design
public:
DesignNumber() { } //default constructor
int getItrNum() //get the iteration number of design
{
m_iteration = m_designNum++;
return m_iteration;
}
static int m_anyNumber; //public static variable
};
int DesignNumber::m_designNum = 0; // starting with design id = 0
// note : no need of static keyword here
//causes compiler error if static keyword used
int DesignNumber::m_anyNumber = 99; /* initialization of inclass public
static member */
enter code here
int main()
{
DesignNumber firstDesign, secondDesign, thirdDesign;
std::cout << firstDesign.getItrNum() << "\n"; //prints 0
std::cout << secondDesign.getItrNum() << "\n"; //prints 1
std::cout << thirdDesign.getItrNum() << "\n"; //prints 2
std::cout << DesignNumber::m_anyNumber++ << "\n"; /* no object
associated with m_anyNumber */
std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 100
std::cout << DesignNumber::m_anyNumber++ << "\n"; //prints 101
return 0;
}
In this example, the static variable m_designNum retains its value and this single private member variable (because it's static) is shared b/w all the variables of the object type DesignNumber
Also like other member variables, static member variables of a class are not associated with any class object, which is demonstrated by the printing of anyNumber in the main function
const vs non-const static member variables in class
(i) non-const class static member variables In the previous example the static members (both public and private) were non constants. ISO standard forbids non-const static members to be initialized in the class. Hence as in previous example, they must be initalized after the class definition, with the caveat that the static keyword needs to be omitted
(ii) const-static member variables of class this is straightforward and goes with the convention of other const member variable initialization, i.e the const static member variables of a class can be initialized at the point of declaration and they can be initialized at the end of the class declaration with one caveat that the keyword const needs to be added to the static member when being initialized after the class definition.
I would however, recommend to initialize the const static member variables at the point of declaration. This goes with the standard C++ convention and makes the code look cleaner
for more examples on static member variables in a class look up the following link from learncpp.com http://www.learncpp.com/cpp-tutorial/811-static-member-variables/
2. 'static' keyword for member function of classes
Just like member variables of classes can ,be static, so can member functions of classes. Normal member functions of classes are always associated with a object of the class type. In contrast, static member functions of a class are not associated with any object of the class, i.e they have no *this pointer.
Secondly since the static member functions of the class have no *this pointer, they can be called using the class name and scope resolution operator in the main function (ClassName::functionName(); )
Thirdly static member functions of a class can only access static member variables of a class, since non-static member variables of a class must belong to a class object.
for more examples on static member functions in a class look up the following link from learncpp.com
http://www.learncpp.com/cpp-tutorial/812-static-member-functions/
In Python3
pip list
Empty venv is
Package Version
---------- -------
pip 19.2.3
setuptools 41.2.0
To start a new environment
python3 -m venv your_foldername_here
Activate
cd your_foldername_here
source bin/activate
Deactivate
deactivate
You can also stand in the folder and give the virtual environment a name/folder (python3 -m venv name_of_venv).
Venv is a subset of virtualenv that is shipped with Python after 3.3.
If you arrived here because you can't log into your phpMyAdmin, then try the root password from your Mysql instead of the password you put during phpMyAdmin installation.
Some of the answers I've seen explain how to make the contents of a cell invisible, but not how to hide the entire column, which is what I wanted to do.
If you have AutoGenerateColumns = "false"
and are actually using BoundField
for the column you want to hide, Bala's answer is slick. But if you are using TemplateField
for the column, you can handle the DataBound
event and do something like this:
protected void gridView_DataBound(object sender, EventArgs e)
{
const int countriesColumnIndex = 4;
if (someCondition == true)
{
// Hide the Countries column
this.gridView.Columns[countriesColumnIndex].Visible = false;
}
}
This may not be what the OP was looking for, but it's the solution I was looking for when I found myself asking the same question.
First Activity Code :
Intent mIntent = new Intent(ActivityA.this, ActivityB.class);
mIntent.putExtra("easyPuzzle", easyPuzzle);
Second Activity Code :
String easyPuzzle = getIntent().getStringExtra("easyPuzzle");
Add "-static" to other linker options solves this problem. I was just having the same issue after I tested this on another system, but not on my own, so even if you haven't noticed this on your development system, you should check that you have this set if you're statically linking.
Another note, copying the DLL into the same folder as the executable is not a solution as it defeats the idea of statically linking.
Another option is to use the TDM version of MinGW which solves this problem.
Update edit: this may not solve the problem for everyone. Another reason I recently discovered for this is when you use a library compiled by someone else, in my case it was SFML which was improperly compiled and so required a DLL that did not exist as it was compiled with a different version of MinGW than what I use. I use a dwarf build, this used another one, so I didn't have the DLL anywhere and of course, I didn't want it as it was a static build. The solution may be to find another build of the library, or build it yourself.
Brief syntax lesson
Cells(Row, Column)
identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)
.Cells(Row, Column)
identifies a cell within a sheet identified in a earlier With statement:
With ActiveSheet
:
.Cells(Row,Column)
:
End With
If you omit the dot, Cells(Row,Column)
is within the active worksheet. So wsh = ActiveWorkbook
wsh.Range
is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:
With ActiveSheet
:
.Range.
:
End With
Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:
With Sheets("xxxx")
:
.Range.
:
End With
because my code only works on sheet xxxx.
Cells(Row,Column)
identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value
is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value
is good.
Cells(Row,Column) like "*Miami*"
will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.
Cells(Row,Column).Value = "Miami"
will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:
Lcase(Cells(Row,Column).Value) = "miami"
My suggestions
Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami"
when I started typing this.
Use
If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
Cells(i, "C").Value = "BA"
if you want to accept, for example, "South Miami" and "Miami, North".
Use
If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
Cells(i, "C").Value = "BA"
if you want to accept, exactly, "Miami" and "Florida".
Use
If Lcase(Cells(i, "A").Value) = "miami" And _
Lcase(Cells(i, "D").Value) = "florida" Then
Cells(i, "C").Value = "BA"
if you don't care about case.
Short Answer: value >= 0 means that the servlet is loaded when the web-app is deployed or when the server starts. value < 0 : servlet is loaded whenever the container feels like.
Long answer (from the spec):
The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive 128 integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.
Don't forget that you can always cut and paste into the minibuffer.
So you can just copy a newline character (or any string) from your buffer, then yank it when prompted for the replacement text.
No there is no built-in support for this.
You have to make your own "INIFileReader". Maybe something like this?
var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));
Console.WriteLine(data["ServerName"]);
Edit: Updated to reflect Paul's comment.
Run
ssh-agent bash
ssh-add
To get more details you can search
ssh-agent
or run
man ssh-agent
If you use the Express framework, this functionality comes ready to go.
To setup a simple file serving app just do this:
mkdir yourapp
cd yourapp
npm install express
node_modules/express/bin/express
I use a Dynamic Management View (DMV) to capture locks as well as the object_id or partition_id of the item that is locked.
(MUST switch to the Database you want to observe to get object_id)
SELECT
TL.resource_type,
TL.resource_database_id,
TL.resource_associated_entity_id,
TL.request_mode,
TL.request_session_id,
WT.blocking_session_id,
O.name AS [object name],
O.type_desc AS [object descr],
P.partition_id AS [partition id],
P.rows AS [partition/page rows],
AU.type_desc AS [index descr],
AU.container_id AS [index/page container_id]
FROM sys.dm_tran_locks AS TL
INNER JOIN sys.dm_os_waiting_tasks AS WT
ON TL.lock_owner_address = WT.resource_address
LEFT OUTER JOIN sys.objects AS O
ON O.object_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.partitions AS P
ON P.hobt_id = TL.resource_associated_entity_id
LEFT OUTER JOIN sys.allocation_units AS AU
ON AU.allocation_unit_id = TL.resource_associated_entity_id;
You can redirect to a new URL in different ways.
$location.path(YOUR_URL);
or $location.url(YOUR_URL);
. So the basic difference between the 2 methods is that $location.url()
also affects get parameters whilst $location.path()
does not.I would recommend reading the docs on $location
and $window
so you get a better grasp on the differences between them.
Hammer.js all the way! It handles "transforms" (pinches). http://eightmedia.github.com/hammer.js/
But if you wish to implement it youself, i think that Jeffrey's answer is pretty solid.
To convert the string to an actual dict, you can do df['Pollutant Levels'].map(eval)
. Afterwards, the solution below can be used to convert the dict to different columns.
Using a small example, you can use .apply(pd.Series)
:
In [2]: df = pd.DataFrame({'a':[1,2,3], 'b':[{'c':1}, {'d':3}, {'c':5, 'd':6}]})
In [3]: df
Out[3]:
a b
0 1 {u'c': 1}
1 2 {u'd': 3}
2 3 {u'c': 5, u'd': 6}
In [4]: df['b'].apply(pd.Series)
Out[4]:
c d
0 1.0 NaN
1 NaN 3.0
2 5.0 6.0
To combine it with the rest of the dataframe, you can concat
the other columns with the above result:
In [7]: pd.concat([df.drop(['b'], axis=1), df['b'].apply(pd.Series)], axis=1)
Out[7]:
a c d
0 1 1.0 NaN
1 2 NaN 3.0
2 3 5.0 6.0
Using your code, this also works if I leave out the iloc
part:
In [15]: pd.concat([df.drop('b', axis=1), pd.DataFrame(df['b'].tolist())], axis=1)
Out[15]:
a c d
0 1 1.0 NaN
1 2 NaN 3.0
2 3 5.0 6.0
Try changing it to:
queryDate = '2009-11-01';
$('#datePicker').datepicker({defaultDate: new Date (queryDate)});
pip install numpy scipy scikit-learn
if you don't have pip, install it using
python get-pip.py
Download get-pip.py from the following link. or use curl to download it.
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Try putting display: block
in the <li>
tags instead of the <ul>
One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.
Code check:
This is offtopic here but the people over at CodeReview are more than happy to help you.
I strongly suggest you to do so, there are several things that need attention in your code. Likewise I suggest that you do start reading tutorials since there is really no good reason not to do so.
Lists:
As you said yourself: you need a list of items. The way it is now you only store a reference to one item. Lucky there is exactly that to hold a group of related objects: a List
.
Lists are very straightforward to use but take a look at the related documentation anyway.
A very simple example to keep multiple bikes in a list:
List<Motorbike> bikes = new List<Motorbike>();
bikes.add(new Bike { make = "Honda", color = "brown" });
bikes.add(new Bike { make = "Vroom", color = "red" });
And to iterate over the list you can use the foreach
statement:
foreach(var bike in bikes) {
Console.WriteLine(bike.make);
}
One way is to simply destroy the listener once you are done with it.
var removeListener = $scope.$on('navBarRight-ready', function () {
$rootScope.$broadcast('workerProfile-display', $scope.worker)
removeListener(); //destroy the listener
})
I agree that StringTokenizer is overkill here. Actually I tried out the suggestions above and took the time.
My test was fairly simple: create a StringBuilder with about a million characters, convert it to a String, and traverse each of them with charAt() / after converting to a char array / with a CharacterIterator a thousand times (of course making sure to do something on the string so the compiler can't optimize away the whole loop :-) ).
The result on my 2.6 GHz Powerbook (that's a mac :-) ) and JDK 1.5:
As the results are significantly different, the most straightforward way also seems to be the fastest one. Interestingly, charAt() of a StringBuilder seems to be slightly slower than the one of String.
BTW I suggest not to use CharacterIterator as I consider its abuse of the '\uFFFF' character as "end of iteration" a really awful hack. In big projects there's always two guys that use the same kind of hack for two different purposes and the code crashes really mysteriously.
Here's one of the tests:
int count = 1000;
...
System.out.println("Test 1: charAt + String");
long t = System.currentTimeMillis();
int sum=0;
for (int i=0; i<count; i++) {
int len = str.length();
for (int j=0; j<len; j++) {
if (str.charAt(j) == 'b')
sum = sum + 1;
}
}
t = System.currentTimeMillis()-t;
System.out.println("result: "+ sum + " after " + t + "msec");
It is also possible to read an encoded text file using the python 3 read method:
f = open (file.txt, 'r', encoding='utf-8')
text = f.read()
f.close()
With this variation, there is no need to import any additional libraries
jQuery's documentation states:
[jQuery.val] checks, or selects, all the radio buttons, checkboxes, and select options that match the set of values.
This behavior is in jQuery
versions 1.2
and above.
You most likely want this:
$("._statusDDL").val('2');
Be careful when using the MAC address as an identifier. I've experienced several gotchas:
Even with the above issues, I still think it's the best pure Java approach to hardware locking a license.
you can use pandas.set_option(), for column, you can specify any of these options
pd.set_option("display.max_rows", 200)
pd.set_option("display.max_columns", 100)
pd.set_option("display.max_colwidth", 200)
For full print column, you can use like this
import pandas as pd
pd.set_option('display.max_colwidth', -1)
print(words.head())