I've installed and use VB6 for legacy projects many times on Windows 7.
What I have done and never came across any issues, is to install VB6, ignore the errors and then proceed to install the latest service pack, currently SP6.
Download here: http://www.microsoft.com/en-us/download/details.aspx?id=5721
Bonus: Also once you install it and realize that scrolling doesn't work, use the below: http://www.joebott.com/vb6scrollwheel.htm
In my case it was a simple type
$_SESSION['role' == 'ge']
I was missing the correct closing bracket
$_SESSION['role'] == 'ge'
!!!
I had a similar problem and I found that in my case the withCredentials: true
in the request was activating the CORS check while issuing the same in the header would avoid the check:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMIssingAllowCredentials
do not use
withCredentials: true
but set
'Access-Control-Allow-Credentials':true
in the headers
Short and simple:
new DirectoryInfo(path).GetFiles().OrderByDescending(o => o.LastWriteTime).FirstOrDefault();
I can confirm that Ctrl + click works fine with the following :
Eclipse Java EE IDE for Web Developers.
Version: Juno Release
Build id: 20120606-2254
Operating System : Windows 7, 64 Bit
What do you have for the following preference ?
On Window -> Preferences -> General -> Editors -> Text Editors -> Hyperlinking -> Open Declaration
Here is what I had for a new workspace in Juno :
Update
I have not experienced this in the recent past, but I vaguely remember encountering this problem in previous Eclipse releases (Galileo and earlier).
All of what follows is worth doing only if we are sure that it's a problem with the Eclipse workspace. A quick way of checking this is to restart eclipse with a new workspace (Do this by going to File -> Switch Workspace -> Other... and choosing the path to a folder which is preferably empty and different than the current workspace folder).
If things worked in the new workspace, my fix then was one of the following, in increasing order extremeness :
-clean
parameter to clean out the workspace ( See this). This might specially be worth doing if you used a workspace from an older version of eclipse.WORKSPACE_FOLDER/.metadata/.plugins/org.eclipse.jdt.core
:not()
pseudo class:For selecting everything but a certain element (or elements). We can use the :not()
CSS pseudo class. The :not()
pseudo class requires a CSS
selector as its argument. The selector will apply the styles to all the elements except for the elements which are specified as an argument.
/* This query selects All div elements except for */_x000D_
div:not(.foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Selects all hovered nav elements inside section element except_x000D_
for the nav elements which have the ID foo*/_x000D_
section nav:hover:not(#foo) {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* selects all li elements inside an ul which are not odd */_x000D_
ul li:not(:nth-child(odd)) { _x000D_
color: red;_x000D_
}
_x000D_
<div>test</div>_x000D_
<div class="foo">test</div>_x000D_
_x000D_
<br>_x000D_
_x000D_
<section>_x000D_
<nav id="foo">test</nav>_x000D_
<nav>Hover me!!!</nav>_x000D_
</section>_x000D_
<nav></nav>_x000D_
_x000D_
<br>_x000D_
_x000D_
<ul>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
</ul>
_x000D_
We can already see the power of this pseudo class, it allows us to conveniently fine tune our selectors by excluding certain elements. Furthermore, this pseudo class increases the specificity of the selector. For example:
/* This selector has a higher specificity than the #foo below */_x000D_
#foo:not(#bar) {_x000D_
color: red;_x000D_
}_x000D_
_x000D_
/* This selector is lower in the cascade but is overruled by the style above */_x000D_
#foo {_x000D_
color: green;_x000D_
}
_x000D_
<div id="foo">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor_x000D_
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>
_x000D_
File protocol URIs are like this
file://[HOST]/[PATH]
that's why you often see file URLs like this (3 slashes) file:///c:\path...
So if the host is server01, you want
file://server01/folder/path....
This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.
I didn't understand your problem clearly but I think this is what you're looking for(Based on my understanding)
person = {"name"=>"BillGates", "company_name"=>"Microsoft", "position"=>"Chairman"}
person.delete_if {|key, value| key == "name"} #doing something if the key == "something"
Output: {"company_name"=>"Microsoft", "position"=>"Chairman"}
Yes, it is possible. Try this:
body { background-image:
url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='%23F00'/><stop offset='90%' stop-color='%23fcc'/> </linearGradient><rect fill='url(%23gradient)' x='0' y='0' width='100%' height='100%'/></svg>");
}
(Note that the SVG content needs to be url-escaped for this to work, e.g. #
gets replaced with %23
.)
This works in IE 9 (which supports SVG). Data-URLs work in older versions of IE too (with limitations), but they don’t natively support SVG.
You can also use the arrow library. This is a simple example:
from datetime import datetime
import arrow
start = datetime(2014, 1, 17)
end = datetime(2014, 6, 20)
for d in arrow.Arrow.range('month', start, end):
print d.month, d.format('MMMM')
This will print:
1 January
2 February
3 March
4 April
5 May
6 June
Hope this helps!
In my point of view,
If you dont use Integrated security=SSPI,then you need to hardcode the username and password in the connection string which means "relatively insecure" why because, all the employees have the access even ex-employee could use the information maliciously.
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
You may be able to simply access a pre-arranged file path on the system. This is preferable since files added to the webapp directory might be lost or the webapp may not be unpacked depending on system configuration.
In our server, we define a system property set in the App Server's JVM which points to the "home directory" for our app's external data. Of course this requires modification of the App Server's configuration (-DAPP_HOME=... added to JVM_OPTS at startup), we do it mainly to ease testing of code run outside the context of an App Server.
You could just as easily retrieve a path from the servlet config:
<web-app>
<context-param>
<param-name>MyAppHome</param-name>
<param-value>/usr/share/myapp</param-value>
</context-param>
...
</web-app>
Then retrieve this path and use it as the base path to read the file supplied by the client.
public class MyAppConfig implements ServletContextListener {
// NOTE: static references are not a great idea, shown here for simplicity
static File appHome;
static File customerDataFile;
public void contextInitialized(ServletContextEvent e) {
appHome = new File(e.getServletContext().getInitParameter("MyAppHome"));
File customerDataFile = new File(appHome, "SuppliedFile.csv");
}
}
class DataProcessor {
public void processData() {
File dataFile = MyAppConfig.customerDataFile;
// ...
}
}
As I mentioned the most likely problem you'll encounter is security restrictions. Nothing guarantees webapps can ready any files above their webapp root. But there are generally simple methods for granting exceptions for specific paths to specific webapps.
Regardless of the code in which you then need to access this file, since you are running within a web application you are guaranteed this is initialized first, and can stash it's value somewhere convenient for the rest of your code to refer to, as in my example or better yet, just simply pass the path as a paramete to the code which needs it.
Well, technically speaking we can pass a parameter to a computed function, the same way we can pass a parameter to a getter function in vuex. Such a function is a function that returns a function.
For instance, in the getters of a store:
{
itemById: function(state) {
return (id) => state.itemPool[id];
}
}
This getter can be mapped to the computed functions of a component:
computed: {
...mapGetters([
'ids',
'itemById'
])
}
And we can use this computed function in our template as follows:
<div v-for="id in ids" :key="id">{{itemById(id).description}}</div>
We can apply the same approach to create a computed method that takes a parameter.
computed: {
...mapGetters([
'ids',
'itemById'
]),
descriptionById: function() {
return (id) => this.itemById(id).description;
}
}
And use it in our template:
<div v-for="id in ids" :key="id">{{descriptionById(id)}}</div>
This being said, I'm not saying here that it's the right way of doing things with Vue.
However, I could observe that when the item with the specified ID is mutated in the store, the view does refresh its contents automatically with the new properties of this item (the binding seems to be working just fine).
I would say that the consultant is right in the theory, and you are right in practice. As the saying goes:
In theory, theory and practice are the same. In practice, they are not.
The Java spec says that System.gc suggests to call garbage collection. In practice, it just spawns a thread and runs right away on the Sun JVM.
Although in theory you could be messing up some finely tuned JVM implementation of garbage collection, unless you are writing generic code intended to be deployed on any JVM out there, don't worry about it. If it works for you, do it.
No need to import anything when using lambda functions.
The following sorts list
by the first element, then by the second element.
sorted(list, key=lambda x: (x[0], -x[1]))
GNU coreutils has it in lib/base64. It's a little bloated but deals with stuff like EBCDIC. You can also play around on your own, e.g.,
char base64_digit (n) unsigned n; {
if (n < 10) return n - '0';
else if (n < 10 + 26) return n - 'a';
else if (n < 10 + 26 + 26) return n - 'A';
else assert(0);
return 0;
}
unsigned char base64_decode_digit(char c) {
switch (c) {
case '=' : return 62;
case '.' : return 63;
default :
if (isdigit(c)) return c - '0';
else if (islower(c)) return c - 'a' + 10;
else if (isupper(c)) return c - 'A' + 10 + 26;
else assert(0);
}
return 0xff;
}
unsigned base64_decode(char *s) {
char *p;
unsigned n = 0;
for (p = s; *p; p++)
n = 64 * n + base64_decode_digit(*p);
return n;
}
Know ye all persons by these presents that you should not confuse "playing around on your own" with "implementing a standard." Yeesh.
I've encountered this error while running Git Bash on a windows box. In my particular case I just needed to open Git Bash as administrator.
cgvector answer didn't work for me, but this did:
document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });
I wouldn't leave it just like that, a smarter logic is needed to select when to prevent the scrolling, but this is a good start.
Taken from here: Disable scrolling in an iPhone web application?
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
As for the inverse, the function is inv(A)
, but I won't recommend using it, since for huge matrices it is very computationally costly and unstable. Instead, you should use an approximation to the inverse, or if you want to solve Ax = b you don't really need A-1.
string FilePath = ConfigurationReader.FileLocation; //Getting path value from web.config
XmlSerializer serializer = new XmlSerializer(typeof(Devices)); //typeof(object)
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, lstDevices);//lstdevices : I take result as a list.
FileStream file = new FileStream(folderName + "\\Data.xml", FileMode.Create, FileAccess.ReadWrite); //foldername:Specify the path to store the xml file
memStream.WriteTo(file);
file.Close();
You can create and store the result as xml file in the desired location.
Use f-string
:
print(f'Total score for {name} is {score}')
Or
Use .format
:
print("Total score for {} is {}".format(name, score))
In concerns make file filename.rb
For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by
module TestConcern
extend ActiveSupport::Concern
def checkattributes
if self.has_attribute?(:created_by)
self.update_attributes(created_by: 1)
end
if self.has_attribute?(:updated_by)
self.update_attributes(updated_by: 0)
end
end
end
If you want to pass arguments in action
included do
before_action only: [:create] do
blaablaa(options)
end
end
after that include in your model like this:
class Role < ActiveRecord::Base
include TestConcern
end
If we load script in partial view then this issue coming
This solution working fine for me
After running your local host you get http://localhost:[port number]/
here you found your port number.
Then get your IP address from Command, Open your windows command and type ipconfig
In my case, IP was 192.168.10.33
so my URL will be http://192.168.10.33:[port number]/.
In Android, the studio uses this URL as your URL. And after that set your URL and your port number in manual proxy for the emulator.
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
You would need to add a property to your Production class and set it to point back at its parent, this doesn't exist by default.
To expand on Dennis's answer, use awk
's -v
option to pass the i
and j
values:
# print the j'th field of the i'th line
awk -v i=5 -v j=3 'FNR == i {print $j}'
Try this it works for me:
(echo "Hello XYX" ; uuencode /export/home/TOTAL_SI_COUNT_10042016.csv TOTAL_SI_COUNT_10042016.csv ) | mailx -s 'Script test' [email protected]
@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU
system, they can do this:
tar cvf - folderToCompress | gzip > compressFileName
To expand the archive:
zcat compressFileName | tar xvf -
To convert your integer input to an array of bool of any size, just use LINQ.
bool[] ToBits(int input, int numberOfBits) {
return Enumerable.Range(0, numberOfBits)
.Select(bitIndex => 1 << bitIndex)
.Select(bitMask => (input & bitMask) == bitMask)
.ToArray();
}
So to convert an integer to a bool array of up to 32 bits, simply use it like so:
bool[] bits = ToBits(65, 8); // true, false, false, false, false, false, true, false
You may wish to reverse the array depending on your needs.
Array.Reverse(bits);
one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details
When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.
First we get an array of keys for this enum. Then, using the map () function, we convert the data to the desired format. id is obtained from the key, name is obtained from enum by the same key.
const converted = Object.keys(GoalProgressMeasurements).map(key => {
return {
id: GoalProgressMeasurements[key],
name: key,
};
});
From version 0.8.0, dplyr
offers a handy function called group_split()
:
# On sample data from @Aus_10
df %>%
group_split(g)
[[1]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 2.04 0.627 A
2 0.530 -0.703 A
3 -0.475 0.541 A
4 1.20 -0.565 A
5 -0.380 -0.126 A
6 1.25 -1.69 A
7 -0.153 -1.02 A
8 1.52 -0.520 A
9 0.905 -0.976 A
10 0.517 -0.535 A
# … with 15 more rows
[[2]]
# A tibble: 25 x 3
ran_data1 ran_data2 g
<dbl> <dbl> <fct>
1 1.61 0.858 B
2 1.05 -1.25 B
3 -0.440 -0.506 B
4 -1.17 1.81 B
5 1.47 -1.60 B
6 -0.682 -0.726 B
7 -2.21 0.282 B
8 -0.499 0.591 B
9 0.711 -1.21 B
10 0.705 0.960 B
# … with 15 more rows
To not include the grouping column:
df %>%
group_split(g, keep = FALSE)
Found a solution with pop
and map
d = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'b', 'c']
list(map(d.pop, keys))
print(d)
The output of this:
{'d': 'valueD'}
I have answered this question so late just because I think it will help in the future if anyone searches the same. And this might help.
Update
The above code will throw an error if a key does not exist in the dict.
DICTIONARY = {'a': 'valueA', 'b': 'valueB', 'c': 'valueC', 'd': 'valueD'}
keys = ['a', 'l', 'c']
def remove_keys(key):
try:
DICTIONARY.pop(key, None)
except:
pass # or do any action
list(map(remove_key, keys))
print(DICTIONARY)
output:
DICTIONARY = {'b': 'valueB', 'd': 'valueD'}
Where are you spending your time? Are you CPU bound? Memory bound? Disk bound? Can you use more cores? More RAM? Do you need RAID? Do you simply want to improve the efficiency of your current system?
Under gcc/g++, have you looked at ccache? It can be helpful if you are doing make clean; make
a lot.
Here is my method made with pure PHP and CSS :
/** PHP code */
<?php
$string = "the string with linebreaks";
$string = strtr($string,array("."=>".\r\r",":"=>" : \r","-"=>"\r - "));
?>
And the CSS :
.your_textarea_class {
style='white-space:pre-wrap';
}
You can do the same with regex (I'm learning how to build regex with pregreplace using an associative array, seems to be better for adding the \n\r which makes the breaks display).
Try this...
$('p').append('<span id="add_here">new-dynamic-text</span>');
OR if there is an existing span, do this.
$('p').children('span').text('new-dynamic-text');
Here is the snippets from my code.. If it solves your problems..
Set jsonpCallBack : 'photos' and dataType:'jsonp'
$('document').ready(function() {
var pm_url = 'http://localhost:8080/diztal/rest/login/test_cor?sessionKey=4324234';
$.ajax({
crossDomain: true,
url: pm_url,
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'photos'
});
});
function photos (data) {
alert(data);
$("#twitter_followers").html(data.responseCode);
};
@Path("/test_cor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String testCOR(@QueryParam("sessionKey") String sessionKey, @Context HttpServletRequest httpRequest) {
ResponseJSON<LoginResponse> resp = new ResponseJSON<LoginResponse>();
resp.setResponseCode(sessionKey);
resp.setResponseText("Wrong Passcode");
resp.setResponseTypeClass("Login");
Gson gson = new Gson();
return "photos("+gson.toJson(resp)+")"; // CHECK_THIS_LINE
}
A compact, flexible method for timestamps without fractional seconds would be:
SELECT * FROM table_name
WHERE field_name
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')
If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >=
and <
operators as per Wouter's answer.
Here is an example of temporal fields defined with fractional second precision (maximum precision in use):
mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)
mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)
mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)
That meta tag basically specifies which character set a website is written with.
Here is a definition of UTF-8:
UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.
Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:
bar <- foo[foo[ ,1] == "there", ]
This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).
This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:
foo[foo[ ,c(1:N)], ]
Or specific columns, as you would expect.
foo[foo[ ,c(1,5,9)], ]
if your port is 7001, since it's the default it might not be mentioned in the config.xml. config.xml only reports stuff which differs from the default, for sake of simplicity.
apart from the config.xml, you should look into a number of other places under your domain-home:
bin/stopWebLogic.sh
bin/stopManagedWebLogic.sh
bin/startManagedWebLogic.sh
config/fmwconfig/servers/osbts1as/applications/em/META-INF/emoms.properties
config/config.xml
init-info/startscript.xml
init-info/tokenValue.properties
servers/osbts1as/data/nodemanager/osbts1as.url
servers/osbts1as/data/ldap/conf/replicas.prop
servers/osbts1ms1/data/nodemanager/osbts1ms1.url
servers/osbts1ms1/data/nodemanager/startup.properties
servers/osbts1ms2/data/nodemanager/osbts1ms2.url
servers/osbts1ms2/data/nodemanager/startup.properties
startManagedWebLogic_readme.txt
sysman/state/targets.xml
And don't forget to update any internal URIs of your deployed code.
See also http://www.javamonamour.org/2013/04/weblogic-change-admin-port-number.html
Especially changing the listen address/port of the admin can be troublesome. If you change only the managed server, it's a lot easier.
The best option is just rebuilding the domain.
The answers above are great. If you are in need of parsing all numbers out of a string that are nonconsecutive then the following may be of some help:
string input = "1-205-330-2342";
string result = Regex.Replace(input, @"[^\d]", "");
Console.WriteLine(result); // >> 12053302342
Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select
, and need to prepend a select
also to the list. Finally, you need to provide aliases for the table and column in you subselect:
Create Table #IMEIS(
imei varchar(15)
)
INSERT INTO #IMEIS(imei)
SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;
But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.
You got an extra }
to many as seen below:
var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
nav[i].addEventListener('click',function(){
console.log('haha');
} // <-- REMOVE THIS :)
}, false);
};
A very good tool for those things is jsFiddle. I have created a fiddle with your invalid code and when clicking the TidyUp
button it formats your code which makes it clearer if there are any possible mistakes with missing braces.
DEMO - Your code in a fiddle, have a play :)
No doubt that NLTK is the most suitable for the purpose. But getting started with NLTK is quite painful (But once you install it - you just reap the rewards)
So here is simple re based code available at http://pythonicprose.blogspot.com/2009/09/python-split-paragraph-into-sentences.html
# split up a paragraph into sentences
# using regular expressions
def splitParagraphIntoSentences(paragraph):
''' break a paragraph into sentences
and return a list '''
import re
# to split by multile characters
# regular expressions are easiest (and fastest)
sentenceEnders = re.compile('[.!?]')
sentenceList = sentenceEnders.split(paragraph)
return sentenceList
if __name__ == '__main__':
p = """This is a sentence. This is an excited sentence! And do you think this is a question?"""
sentences = splitParagraphIntoSentences(p)
for s in sentences:
print s.strip()
#output:
# This is a sentence
# This is an excited sentence
# And do you think this is a question
You are iterating over one string (word
), but then using the index into that to look up a character in so_far
. There is no guarantee that these two strings have the same length.
Try opening config-db.php, it's inside /etc/phpmyadmin. In my case, the user was phpmyadmin, and my password was correct. Maybe your problem is that you're using the usual 'root' username, and your password could be correct.
Deploying the code after enabling CORS for both POST
and OPTIONS
worked for me.
If you need a lambda to remember state between calls, I would recommend either a function declared in the local namespace or a class with an overloaded __call__
. Now that all my cautions against what you are trying to do is out of the way, we can get to an actual answer to your query.
If you really need to have your lambda to have some memory between calls, you can define it like:
f = lambda o, ns = {"flag":True}: [ns["flag"] or o.name, ns.__setitem__("flag", ns["flag"] and o.name)][0]
Then you just need to pass f
to filter()
. If you really need to, you can get back the value of flag
with the following:
f.__defaults__[0]["flag"]
Alternatively, you can modify the global namespace by modifying the result of globals()
. Unfortunately, you cannot modify the local namespace in the same way as modifying the result of locals()
doesn't affect the local namespace.
The compiler may well optimize the second form into the first form, but it doesn't have to.
#include <iostream>
class A
{
public:
A() { std::cerr << "Empty constructor" << std::endl; }
A(const A&) { std::cerr << "Copy constructor" << std::endl; }
A(const char* str) { std::cerr << "char constructor: " << str << std::endl; }
~A() { std::cerr << "destructor" << std::endl; }
};
void direct()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void assignment()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a = A(__FUNCTION__);
static_cast<void>(a); // avoid warnings about unused variables
}
void prove_copy_constructor_is_called()
{
std::cerr << std::endl << "TEST: " << __FUNCTION__ << std::endl;
A a(__FUNCTION__);
A b = a;
static_cast<void>(b); // avoid warnings about unused variables
}
int main()
{
direct();
assignment();
prove_copy_constructor_is_called();
return 0;
}
Output from gcc 4.4:
TEST: direct
char constructor: direct
destructor
TEST: assignment
char constructor: assignment
destructor
TEST: prove_copy_constructor_is_called
char constructor: prove_copy_constructor_is_called
Copy constructor
destructor
destructor
The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html
The method DocumentBuilder.parse(String)
takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream
or Reader
, for example a StringReader
. ... Welcome to the Java standard levels of indirections !
Basically :
DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));
Note that if you read your XML from a file, you can directly give the File
object to DocumentBuilder.parse()
.
As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !
Provide a module whose responsibility is to execute requests sequentially, while tracking the current index of each operation in an ordinal manner. Define the operation in a Command Pattern for flexibility.
execute
method to chain & track each operation. SequentialPromise returns a Promise-Chain from all operations performed.execute
method while passing in an ordinal list of options for each operation.Use SequentialPromise when ordinal behavior of Promise resolution is needed. SequentialPromise will track the index for which a Promise was rejected.
clear();
var http = {
get(url) {
var delay = Math.floor( Math.random() * 10 ), even = !(delay % 2);
var xhr = new Promise(exe);
console.log(`REQUEST`, url, delay);
xhr.then( (data) => console.log(`SUCCESS: `, data) ).catch( (data) => console.log(`FAILURE: `, data) );
function exe(resolve, reject) {
var action = { 'true': reject, 'false': resolve }[ even ];
setTimeout( () => action({ url, delay }), (1000 * delay) );
}
return xhr;
}
};
var SequentialPromise = new (function SequentialPromise() {
var PRIVATE = this;
return class SequentialPromise {
constructor(context, action) {
this.index = 0;
this.requests = [ ];
this.context = context;
this.action = action;
return this;
}
log() {}
execute(url, ...more) {
var { context, action, requests } = this;
var chain = context[action](url);
requests.push(chain);
chain.then( (data) => this.index += 1 );
if (more.length) return chain.then( () => this.execute(...more) );
return chain;
}
};
})();
var sequence = new SequentialPromise(http, 'get');
var urls = [
'url/name/space/0',
'url/name/space/1',
'url/name/space/2',
'url/name/space/3',
'url/name/space/4',
'url/name/space/5',
'url/name/space/6',
'url/name/space/7',
'url/name/space/8',
'url/name/space/9'
];
var chain = sequence.execute(...urls);
var promises = sequence.requests;
chain.catch( () => console.warn(`EXECUTION STOPPED at ${sequence.index} for ${urls[sequence.index]}`) );
// console.log('>', chain, promises);
If you are using an old version of FFMPEG and you cant upgrade you can do the following:
ffmpeg -i PATH/VIDEO_FILE_NAME.mp4 -i PATH/AUDIO_FILE_NAME.mp3 -vcodec copy -shortest DESTINATION_PATH/NEW_VIDEO_FILE_NAME.mp4
Notice that I used -vcodec
Here's another way of getting a Bash array with the example JSON given by @anubhava in his answer:
arr=($(jq --raw-output 'keys_unsorted | @sh' file.json))
echo ${arr[0]} # 'Archiver-Version'
echo ${arr[1]} # 'Build-Id'
echo ${arr[2]} # 'Build-Jdk'
So i had a adifferent case where i needed to assign values before running a session, So this was the easiest way to do that:
other_variable = tf.get_variable("other_variable", dtype=tf.int32,
initializer=tf.constant([23, 42]))
here i'm creating a variable as well as assigning it values at the same time
You also should set border:none
to that css class.
"This is my string with date in specified format $($theDate.ToString('u'))"
or
"This is my string with date in specified format $(Get-Date -format 'u')"
The sub-expression ($(...)
) can include arbitrary expressions calls.
MSDN Documents both standard and custom DateTime
format strings.
Since Python 2.6.X you might want to use:
"my {0} string: {1}".format("cool", "Hello there!")
try running:
su -c "Your command right here" -s /bin/sh username
This will run the command as username given that you have permissions to sudo as that user.
In Python 2.x, it is not guaranteed at all:
>>> False = 5
>>> 0 == False
False
So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.
In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1
, but on Python 3.x, this will always be the case, no matter what.
An alternative that has not been mentioned yet is to type the onChange function instead of the props that it receives. Using React.ChangeEventHandler:
const stateChange: React.ChangeEventHandler<HTMLInputElement> = (event) => {
console.log(event.target.value);
};
I tried with one column of string values with nan.
To remove the nan and fill the empty string:
df.columnname.replace(np.nan,'',regex = True)
To remove the nan and fill some values:
df.columnname.replace(np.nan,'value',regex = True)
I tried df.iloc also. but it needs the index of the column. so you need to look into the table again. simply the above method reduced one step.
Try adding root path.
app.get('/', function(req, res) {
res.sendFile('index.html', { root: __dirname });
});
I got pretty close to what I wanted by doing something like this
cat my.json | jq '.my.prefix[] | .primary_key + ":", (.sub.prefix[] | " - " + .sub_key)' | tr -d '"'
The output of which is close enough to yaml for me to usually import it into other tools without much problem. (I am still looking for a way to basicallt export a subset of the input json)
SQL%ROWCOUNT
can also be used without being assigned (at least from Oracle 11g).
As long as no operation (updates, deletes or inserts) has been performed within the current block, SQL%ROWCOUNT
is set to null. Then it stays with the number of line affected by the last DML operation:
say we have table CLIENT
create table client (
val_cli integer
,status varchar2(10)
)
/
We would test it this way:
begin
dbms_output.put_line('Value when entering the block:'||sql%rowcount);
insert into client
select 1, 'void' from dual
union all select 4, 'void' from dual
union all select 1, 'void' from dual
union all select 6, 'void' from dual
union all select 10, 'void' from dual;
dbms_output.put_line('Number of lines affected by previous DML operation:'||sql%rowcount);
for val in 1..10
loop
update client set status = 'updated' where val_cli = val;
if sql%rowcount = 0 then
dbms_output.put_line('no client with '||val||' val_cli.');
elsif sql%rowcount = 1 then
dbms_output.put_line(sql%rowcount||' client updated for '||val);
else -- >1
dbms_output.put_line(sql%rowcount||' clients updated for '||val);
end if;
end loop;
end;
Resulting in:
Value when entering the block:
Number of lines affected by previous DML operation:5
2 clients updated for 1
no client with 2 val_cli.
no client with 3 val_cli.
1 client updated for 4
no client with 5 val_cli.
1 client updated for 6
no client with 7 val_cli.
no client with 8 val_cli.
no client with 9 val_cli.
1 client updated for 10
This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.
import random
from datetime import datetime
import operator
import numpy as np
def explicit(l):
max_val = max(l)
max_idx = l.index(max_val)
return max_idx, max_val
def implicit(l):
max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
return max_idx, max_val
def npmax(l):
max_idx = np.argmax(l)
max_val = l[max_idx]
return (max_idx, max_val)
if __name__ == "__main__":
from timeit import Timer
t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
"import random; import operator; import numpy as np;"
"l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
"import random; import operator;"
"l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000 * t.timeit(number=10)/10 )
Results on my computer:
Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass
Use this as a method with x being any number initially. The string y being passed in by console and v is the array to search!
public static int getIndex(int x, String y, String[]v){
for(int m = 0; m < v.length; m++){
if (v[m].equalsIgnoreCase(y)){
x = m;
}
}
return x;
}
It's in fact almost the same in Python.. :-)
import datetime
year = datetime.date.today().year
Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:
import datetime
year = datetime.datetime.today().year
(Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).
One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
sending 2 images vb.net code convert for C# online converter.
Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") As Boolean
Dim client As SmtpClient = New SmtpClient ''("FMSERVER.FMINNOVATIONS.COM.AU")
'Dim fromAddress As MailAddress = New MailAddress(Me.FromEmail, "WSMenterprise")
'Dim toAddress As MailAddress
Try
Dim aMessage As New MailMessage()
'(New MailAddress(Me.FromEmail, "WSMenterprise"), New MailAddress(anAdd))
If _fromAddress IsNot Nothing Then
If _fromName IsNot Nothing Then
aMessage.From = New MailAddress(_fromAddress, _fromName)
Else
aMessage.From = New MailAddress(_fromAddress)
End If
End If
For Each anAdd As String In _To
aMessage.To.Add(New MailAddress(anAdd))
Next
For Each cc As String In _CC
aMessage.CC.Add(New MailAddress(cc))
Next
For Each bcc As String In _BCC
aMessage.Bcc.Add(New MailAddress(bcc))
Next
aMessage.Subject = _Subject
aMessage.IsBodyHtml = p_AsHTML
If _EmailLogo Is Nothing Then
aMessage.Body = _Body
Else
If p_themEmail.ToString().ToLower.Contains("dexus") Then
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "Dexuslogo1"
Dim logo1 As New LinkedResource(_EmailLogo1)
logo1.ContentId = "Dexuslogo2"
htmlView.LinkedResources.Add(logo)
htmlView.LinkedResources.Add(logo1)
aMessage.AlternateViews.Add(htmlView)
Else
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "companylogo"
htmlView.LinkedResources.Add(logo)
aMessage.AlternateViews.Add(htmlView)
End If
End If
For Each anAttach As Attachment In _Attachments
aMessage.Attachments.Add(anAttach)
Next
If _ReplyTo IsNot Nothing Then aMessage.ReplyToList.Add(New MailAddress(_ReplyTo))
client.Host = "smtpi.cbre.com.au"
client.UseDefaultCredentials = True
client.Send(aMessage)
Catch exRecipUnk As SmtpFailedRecipientException
Return False
Catch exSmtp As SmtpException
''exSmtp.StatusCode
Return False
Catch ex As Exception
Return False
End Try
Return True
End Function
If p_Gmap_code = "DE" Then
Dim p_Theme As New Theme("Dexus")
Dim passwordlink As String = ""
Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png")
Dim DexuslogoImage2 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\DexusTenantNotice.png")
passwordlink = "<a href='" + p_Theme.TenantLoginPage + "?accesstype=email&te=" + a.Encrypt(p_TenantEmail) + "' target='_blank'>here.</a><br/>"
bodys += "<div align='Center'><table border='0' cellpadding='0' cellspacing='0'><tr style='height:50px;'><td width='623px' ></td><td valign='top' width='180'><p align='right'><a href='http://www.dexus.com/'><img border='0' height='50' src=cid:Dexuslogo1 width='174' alt=''/></a></p></td></tr><tr><td colspan='2' width='803' style='height:25px;'></td></tr> <tr><td width='623px'><p align='left' style='font-family:Arial;font-size:14pt;'><strong> Your Dexus Response Password is about to expire</strong></p></td>"
bodys += " <td width='180'><p align='right' style='font-family:Arial;font-size:10pt;'>" + DateTime.Now.ToString("dd/MM/yyyy") + " </p>"
bodys += "</td></tr><tr><td colspan='2' width='803' style='height:30px;'> </td></tr> <tr> <td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
bodys += "<p>" + wishes + " " + p_TenantName.Trim().ToString() + "</p>"
bodys += "</td></tr><tr><td colspan='2' width='803' style='height:25px;'></td> </tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToString() + " days.<br /><br /> To reset your password and update your details, please click " + passwordlink.ToString() + "<br /><br />Please note that if you do not update your password by " + p_date + ",then your account will be set to inactive and you will not be able to access Dexus Response.</br></br>Please contact Dexus Response if you require assistance in accessing the portal.</p></td>" 'edit
bodys += " </tr><tr><td colspan='2' width='803' style='height:30px;'></td></tr><tr><td colspan='2' width='803'><table align='left' border='0' cellpadding='0' cellspacing='0'><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><strong>Dexus Response</strong></p></td></tr><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><a href='mailto:[email protected]'>[email protected]</a> <strong>|</strong> 1300 339 870 <strong>|</strong> <a href='https://response.dexus.com/'>response.dexus.com</a></p></td></tr></table></td></tr><tr><td colspan='2' width='803' style='height:15px;'></td></tr><tr> <td colspan='2' width='803'><p> </p><p><a href='https://response.dexus.com/' border='0' target='_blank'><img border='0' height='133'"
bodys += "src=cid:Dexuslogo2 alt='' width='800' /></a></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'><p><a href='http://www.dexus.com/who-we-are/terms-and-conditions' style=' color:#000000;'>Terms and Conditions</a><strong> | </strong><a href='http://www.dexus.com/who-we-are/privacy-policy' style=' color:#000000;'> Privacy Policy</a></p></td></tr><tr><td colspan='2' width='803' style='height:40px;'></td></tr><tr><td colspan='2' width='803'><p></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr></tr><tr><td colspan='2' width='803' style='height:20px;'></td></tr></table></div>"
email = New Common.Email(emailHeading, bodys, p_Theme.EmailFrom, DexuslogoImage1, DexuslogoImage2)
email.ToEmail = p_TenantEmail
email.SendEmail(True, p_Theme.EmailFrom)
You are using .index()
which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0)
will always return 2
, no matter how many times 1.0
occurs in the list.
Use enumerate()
to add indices to your loop instead:
def find(lst, a, b):
result = []
for i, x in enumerate(lst):
if x<a or x>b:
result.append(i)
return result
You can collapse this into a list comprehension:
def find(lst, a, b):
return [i for i, x in enumerate(lst) if x<a or x>b]
Try this all four way to take input with space :)
#include<iostream>
#include<stdio.h>
using namespace std;
void dinput(char *a)
{
for(int i=0;; i++)
{
cin >> noskipws >> a[i];
if(a[i]=='\n')
{
a[i]='\0';
break;
}
}
}
void input(char *a)
{
//cout<<"\nInput string: ";
for(int i=0;; i++)
{
*(a+i*sizeof(char))=getchar();
if(*(a+i*sizeof(char))=='\n')
{
*(a+i*sizeof(char))='\0';
break;
}
}
}
int main()
{
char a[20];
cout<<"\n1st method\n";
input(a);
cout<<a;
cout<<"\n2nd method\n";
cin.get(a,10);
cout<<a;
cout<<"\n3rd method\n";
cin.sync();
cin.getline(a,sizeof(a));
cout<<a;
cout<<"\n4th method\n";
dinput(a);
cout<<a;
return 0;
}
Here is an extension method that overloads the AppendText
method with a color parameter:
public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}
And this is how you would use it:
var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
{
Dock = DockStyle.Fill,
Font = new Font("Courier New", 10)
};
box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);
new Form {Controls = {box}}.ShowDialog();
Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.
For me, the top level VC needed to implement the orientation overrides. Using VC's down the stack will have no effect if the top VC is not implementing.
VC-main
|
-> VC 2
|
-> VC 3
Only VC-Main is listened to, essentially in my testing.
You are dealing with the raw DOM element .. need to wrap it in a jquery object
console.info("cat_id: ",$(value).attr('cat_id'));
I like this one, that hasn't been mentioned above.
require 'pathname'
Pathname.new('/my/dir').children.each do |path|
puts path
end
The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.
In my case, I had a my-plugin
repository and a main-project
repository, and I wanted to pretend that my-plugin
had always been developed in the plugins
subdirectory of main-project
.
Basically, I rewrote the history of the my-plugin
repository so that it appeared all development took place in the plugins/my-plugin
subdirectory. Then, I added the development history of my-plugin
into the main-project
history, and merged the two trees together. Since there was no plugins/my-plugin
directory already present in the main-project
repository, this was a trivial no-conflicts merge. The resulting repository contained all history from both original projects, and had two roots.
$ cp -R my-plugin my-plugin-dirty
$ cd my-plugin-dirty
$ git filter-branch -f --tree-filter "zsh -c 'setopt extended_glob && setopt glob_dots && mkdir -p plugins/my-plugin && (mv ^(.git|plugins) plugins/my-plugin || true)'" -- --all
$ cd ../main-project
$ git checkout master
$ git remote add --fetch my-plugin ../my-plugin-dirty
$ git merge my-plugin/master --allow-unrelated-histories
$ cd ..
$ rm -rf my-plugin-dirty
First, create a copy of the my-plugin
repository, because we're going to be rewriting the history of this repository.
Now, navigate to the root of the my-plugin
repository, check out your main branch (probably master
), and run the following command. Of course, you should substitute for my-plugin
and plugins
whatever your actual names are.
$ git filter-branch -f --tree-filter "zsh -c 'setopt extended_glob && setopt glob_dots && mkdir -p plugins/my-plugin && (mv ^(.git|plugins) plugins/my-plugin || true)'" -- --all
Now for an explanation. git filter-branch --tree-filter (...) HEAD
runs the (...)
command on every commit that is reachable from HEAD
. Note that this operates directly on the data stored for each commit, so we don't have to worry about notions of "working directory", "index", "staging", and so on.
If you run a filter-branch
command that fails, it will leave behind some files in the .git
directory and the next time you try filter-branch
it will complain about this, unless you supply the -f
option to filter-branch
.
As for the actual command, I didn't have much luck getting bash
to do what I wanted, so instead I use zsh -c
to make zsh
execute a command. First I set the extended_glob
option, which is what enables the ^(...)
syntax in the mv
command, as well as the glob_dots
option, which allows me to select dotfiles (such as .gitignore
) with a glob (^(...)
).
Next, I use the mkdir -p
command to create both plugins
and plugins/my-plugin
at the same time.
Finally, I use the zsh
"negative glob" feature ^(.git|plugins)
to match all files in the root directory of the repository except for .git
and the newly created my-plugin
folder. (Excluding .git
might not be necessary here, but trying to move a directory into itself is an error.)
In my repository, the initial commit did not include any files, so the mv
command returned an error on the initial commit (since nothing was available to move). Therefore, I added a || true
so that git filter-branch
would not abort.
The --all
option tells filter-branch
to rewrite the history for all branches in the repository, and the extra --
is necessary to tell git
to interpret it as a part of the option list for branches to rewrite, instead of as an option to filter-branch
itself.
Now, navigate to your main-project
repository and check out whatever branch you want to merge into. Add your local copy of the my-plugin
repository (with its history modified) as a remote of main-project
with:
$ git remote add --fetch my-plugin $PATH_TO_MY_PLUGIN_REPOSITORY
You will now have two unrelated trees in your commit history, which you can visualize nicely using:
$ git log --color --graph --decorate --all
To merge them, use:
$ git merge my-plugin/master --allow-unrelated-histories
Note that in pre-2.9.0 Git, the --allow-unrelated-histories
option does not exist. If you are using one of these versions, just omit the option: the error message that --allow-unrelated-histories
prevents was also added in 2.9.0.
You should not have any merge conflicts. If you do, it probably means that either the filter-branch
command did not work correctly or there was already a plugins/my-plugin
directory in main-project
.
Make sure to enter an explanatory commit message for any future contributors wondering what hackery was going on to make a repository with two roots.
You can visualize the new commit graph, which should have two root commits, using the above git log
command. Note that only the master
branch will be merged. This means that if you have important work on other my-plugin
branches that you want to merge into the main-project
tree, you should refrain from deleting the my-plugin
remote until you have done these merges. If you don't, then the commits from those branches will still be in the main-project
repository, but some will be unreachable and susceptible to eventual garbage collection. (Also, you will have to refer to them by SHA, because deleting a remote removes its remote-tracking branches.)
Optionally, after you have merged everything you want to keep from my-plugin
, you can remove the my-plugin
remote using:
$ git remote remove my-plugin
You can now safely delete the copy of the my-plugin
repository whose history you changed. In my case, I also added a deprecation notice to the real my-plugin
repository after the merge was complete and pushed.
Tested on Mac OS X El Capitan with git --version 2.9.0
and zsh --version 5.2
. Your mileage may vary.
References:
I have made a jsfiddle for you.
<canvas id="canvas" width="480" height="320"></canvas>
<button id="download">Download Pdf</button>
'
html2canvas($("#canvas"), {
onrendered: function(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
}
});
jsfiddle: http://jsfiddle.net/rpaul/p4s5k59s/5/
Tested in Chrome38, IE11 and Firefox 33. Seems to have issues with Safari. However, Andrew got it working in Safari 8 on Mac OSx by switching to JPEG from PNG. For details, see his comment below.
Not a full answer but perhaps a useful hint. If it is really the first item you want*, then
next(iter(q))
is much faster than
list(q)[0]
for large dicts, since the whole thing doesn't have to be stored in memory.
For 10.000.000 items I found it to be almost 40.000 times faster.
*The first item in case of a dict being just a pseudo-random item before Python 3.6 (after that it's ordered in the standard implementation, although it's not advised to rely on it).
If you use Arch Linux (distributions like Manjaro
or Antegros
) simply type:
sudo pacman -S tk
And all will work perfectly!
Potatoswatter's answer is all right, but I prefer to use find
or lower_bound
instead. lower_bound
is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.
map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) { // not found
// ...
my_map.insert(iter, make_pair(key, value)); // hinted insertion
} else {
// ... use iter->second here
}
This is an aggregation problem, not a reshaping problem as the question originally suggested -- we wish to aggregate each column into a mean and standard deviation by ID. There are many packages that handle such problems. In the base of R it can be done using aggregate
like this (assuming DF
is the input data frame):
ag <- aggregate(. ~ ID, DF, function(x) c(mean = mean(x), sd = sd(x)))
Note 1: A commenter pointed out that ag
is a data frame for which some columns are matrices. Although initially that may seem strange, in fact it simplifies access. ag
has the same number of columns as the input DF
. Its first column ag[[1]]
is ID
and the ith column of the remainder ag[[i+1]]
(or equivalanetly ag[-1][[i]]
) is the matrix of statistics for the ith input observation column. If one wishes to access the jth statistic of the ith observation it is therefore ag[[i+1]][, j]
which can also be written as ag[-1][[i]][, j]
.
On the other hand, suppose there are k
statistic columns for each observation in the input (where k=2 in the question). Then if we flatten the output then to access the jth statistic of the ith observation column we must use the more complex ag[[k*(i-1)+j+1]]
or equivalently ag[-1][[k*(i-1)+j]]
.
For example, compare the simplicity of the first expression vs. the second:
ag[-1][[2]]
## mean sd
## [1,] 36.333 10.2144
## [2,] 32.250 4.1932
## [3,] 43.500 4.9497
ag_flat <- do.call("data.frame", ag) # flatten
ag_flat[-1][, 2 * (2-1) + 1:2]
## Obs_2.mean Obs_2.sd
## 1 36.333 10.2144
## 2 32.250 4.1932
## 3 43.500 4.9497
Note 2: The input in reproducible form is:
Lines <- "ID Obs_1 Obs_2 Obs_3
1 43 48 37
1 27 29 22
1 36 32 40
2 33 38 36
2 29 32 27
2 32 31 35
2 25 28 24
3 45 47 42
3 38 40 36"
DF <- read.table(text = Lines, header = TRUE)
This is a bit of an old question, but I thought I would contribute my 2 cents anyway since this thread came up in conversation today.
This doesn't exactly answer why is there no const? but how to make your classes immutable. (Unfortunately I have not enough reputation yet to post as a comment to the accepted answer)
The way to guarantee immutability on an object is to design your classes more carefully to be immutable. This requires a bit more care than a mutable class.
This goes back to Josh Bloch's Effective Java Item 15 - Minimize Mutability. If you haven't read the book, pick up a copy and read it over a few times I guarantee it will up your figurative "java game".
In item 15 Bloch suggest that you should limit the mutability of classes to ensure the object's state.
To quote the book directly:
An immutable class is simply a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object. The Java platform libraries contain many immutable classes, including String, the boxed primitive classes, and BigInte- ger and BigDecimal. There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.
Bloch then describes how to make your classes immutable, by following 5 simple rules:
final
).final
.private
. For more details I highly recommend picking up a copy of the book.
Maybe you could do
SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)
Per the specification, the JSON grammar's char production can take the following values:
"
-or-\
-or-control-character\"
\\
\/
\b
\f
\n
\r
\t
\u
four-hex-digitsNewlines are "control characters", so no, you may not have a literal newline within your string. However, you may encode it using whatever combination of \n
and \r
you require.
The JSONLint tool confirms that your JSON is invalid.
And, if you want to write newlines inside your JSON syntax without actually including newlines in the data, then you're doubly out of luck. While JSON is intended to be human-friendly to a degree, it is still data and you're trying to apply arbitrary formatting to that data. That is absolutely not what JSON is about.
Custom SerDe might be a way to do it. Or you could use some kind of mediation process with regex_replace:
create table tableB as
select
columnA
regexp_replace(description, '\\t', '') as description
from tableA
;
You can use boolean indexing
:
df = pd.DataFrame({'Sales':[10,20,30,40,50], 'A':[3,4,7,6,1]})
print (df)
A Sales
0 3 10
1 4 20
2 7 30
3 6 40
4 1 50
s = 30
df1 = df[df['Sales'] >= s]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
df2 = df[df['Sales'] < s]
print (df2)
A Sales
0 3 10
1 4 20
It's also possible to invert mask
by ~
:
mask = df['Sales'] >= s
df1 = df[mask]
df2 = df[~mask]
print (df1)
A Sales
2 7 30
3 6 40
4 1 50
print (df2)
A Sales
0 3 10
1 4 20
print (mask)
0 False
1 False
2 True
3 True
4 True
Name: Sales, dtype: bool
print (~mask)
0 True
1 True
2 False
3 False
4 False
Name: Sales, dtype: bool
I also get same error while running project react-native run-ios
But when i run project from xcode, that is work for me.
Try like
$('.printMe').click(function(){
window.print();
});
or if you want to print selected area try like
$('.printMe').click(function(){
$("#outprint").print();
});
I got similar message when running command line mvn (version 3.3.3) on Linux with Java 8. By opening maven script /$MAVEN-HOME/bin/mvn, found the following line
MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS"
Where $MAVEN_PROJECTBASEDIR by default is your home directory. So two places you can take a look, first is file $MAVEN_PROJECTBASEDIR/.mvn/jvm.config if it exists. Secondly look at files possibly set up the environment variable MAVEN_OPTS. Candidate files are .bashrc, .bash_profile, .profile and those files included by them such as /etc/profile, /etc/bash.bashrc
I located
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=256m"
in .bashrc in my system, change it to
export MAVEN_OPTS="-Xmx512m"
issue resolved
You need to use the fn:contains()
or fn:containsIgnoreCase()
function.
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
...
<c:if test="${not fn:containsIgnoreCase(mylist, 'apple')}">
<p>Doesn't contain 'apple'</p>
</c:if>
or
<c:if test="${not fn:contains(mylist, 'Apple')}">
<p>Contains 'Apple'</p>
</c:if>
Note:
This will work like mylist.toString().contains("apple")
and if this is not what you are looking for better use a other approach.
I clone entire directory by SPL Directory Iterator.
function recursiveCopy($source, $destination)
{
if (!file_exists($destination)) {
mkdir($destination);
}
$splFileInfoArr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($splFileInfoArr as $fullPath => $splFileinfo) {
//skip . ..
if (in_array($splFileinfo->getBasename(), [".", ".."])) {
continue;
}
//get relative path of source file or folder
$path = str_replace($source, "", $splFileinfo->getPathname());
if ($splFileinfo->isDir()) {
mkdir($destination . "/" . $path);
} else {
copy($fullPath, $destination . "/" . $path);
}
}
}
#calling the function
recursiveCopy(__DIR__ . "/source", __DIR__ . "/destination");
As c69 mentioned there is no way to do it with pure CSS.
but you can use HTML instead:
use
<head>
<base target="_blank">
</head>
in your HTML <head>
tag for making all of page links which not include target
attribute to be opened in a new blank window by default.
otherwise you can set target attribute for each link like this:
<a href="/yourlink.html" target="_blank">test-link</a>
and it will override
<head>
<base target="_blank">
</head>
tag if it was defined previously.
You should set your RecyclerView
LayoutManager
to Gridlayout mode. Just change your code when you want to set your RecyclerView
LayoutManager
:
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));
Select mymethod()
and press ctrl+alt+h.
To see some detailed Information about any method you can use this by selecting that particular Object or method and right click. you can see the "OpenCallHierarchy" (Ctrl+Alt+H). Like that many tools are there to make your work Easier like "Quick Outline" (Ctrl+O) to view the Datatypes and methods declared in a particular .java file.
To know more about this, refer this eclipse Reference
You can use preg_replace in this case;
$res = preg_replace("/[^0-9]/", "", "Every 6 Months" );
$res return 6 in this case.
If want also to include decimal separator or thousand separator check this example:
$res = preg_replace("/[^0-9.]/", "", "$ 123.099");
$res returns "123.099" in this case
Include period as decimal separator or thousand separator: "/[^0-9.]/"
Include coma as decimal separator or thousand separator: "/[^0-9,]/"
Include period and coma as decimal separator and thousand separator: "/[^0-9,.]/"
In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.
So your example:
<span style="color:blue" style="font-style:italic">Test</span>
is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.
Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.
(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:
Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)
SELECT COUNT (COL_NAME)
FROM TABLE
WHERE TRIM (COL_NAME) IS NULL
or COL_NAME='NULL'
Try this MSDN blog
Also, try the following example:
Xaml:
<DataGrid AutoGenerateColumns="False" Name="DataGridTest" CanUserAddRows="True" ItemsSource="{Binding TestBinding}" Margin="0,50,0,0" >
<DataGrid.Columns>
<DataGridTextColumn Header="Line" IsReadOnly="True" Binding="{Binding Path=Test1}" Width="50"></DataGridTextColumn>
<DataGridTextColumn Header="Account" IsReadOnly="True" Binding="{Binding Path=Test2}" Width="130"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<Button Content="Add new row" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
CS:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var data = new Test { Test1 = "Test1", Test2 = "Test2" };
DataGridTest.Items.Add(data);
}
}
public class Test
{
public string Test1 { get; set; }
public string Test2 { get; set; }
}
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
Update:
I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.
I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.
There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com
it's well documented here:
https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6
How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:
http://tomcat.apache.org/tomcat-7.0-doc/config/http.html
Standard Implementation -> address
"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."
For those running into this issue (granted 4 years after this post was made) while running Mac OS High Sierra - the steps outlined here solved the problem for me. Essentially just outlines uninstalling and reinstalling brew.
After running those steps, brew link
worked like a charm!
string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string";
var match = Regex.Match(input, @"FirstString (.+?) SecondString ").Groups[1].Value;
No need to clone and add to the DOM to use .html(), you can do:
$('#item-of-interest').wrap('<div></div>').html()
you'd use another join, something along these lines:
SELECT toD.dom_url AS ToURL,
fromD.dom_url AS FromUrl,
rvw.*
FROM reviews AS rvw
LEFT JOIN domain AS toD
ON toD.Dom_ID = rvw.rev_dom_for
LEFT JOIN domain AS fromD
ON fromD.Dom_ID = rvw.rev_dom_from
EDIT:
All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).
At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.
Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.
For more info about aliasing in SQL, read here.
It seems to be working fine:
List<BigDecimal> list = Arrays.asList(new BigDecimal("24.455"), new BigDecimal("23.455"), new BigDecimal("28.455"), new BigDecimal("20.455"));
System.out.println("Unsorted list: " + list);
final List<BigDecimal> sortedList = list.stream().sorted((o1, o2) -> o1.compareTo(o2)).collect(Collectors.toList());
System.out.println("Sorted list: " + sortedList);
Example Input/Output
Unsorted list: [24.455, 23.455, 28.455, 20.455]
Sorted list: [20.455, 23.455, 24.455, 28.455]
Are you sure you are not verifying list instead of sortedList
[in above example] i.e. you are storing the result of stream()
in a new List
object and verifying that object?
I was able to copy all the sheets in a workbook that had a vba app running, to a new workbook w/o the app macros, with:
ActiveWorkbook.Sheets.Copy
Try this
$(function() {
$( "#datepicker" ).datepicker({ maxDate: new Date() });
});
Or you can achieve this using as below:
$(function() {
$( "#datepicker" ).datepicker({ maxDate: 0 });
});
If you use Thymeleaf 3:
<script th:inline="javascript">
var username = [[${session.user.name}]];
</script>
ES6 Map version :
getTreeData = (items) => {
if (items && items.length > 0) {
const data = [];
const map = {};
items.map((item) => {
const id = item.id; // custom id selector !!!
if (!map.hasOwnProperty(id)) {
// in case of duplicates
map[id] = {
...item,
children: [],
};
}
});
for (const id in map) {
if (map.hasOwnProperty(id)) {
let mappedElem = [];
mappedElem = map[id];
/// parentId : use custom id selector for parent
if (
mappedElem.parentId &&
typeof map[mappedElem.parentId] !== "undefined"
) {
map[mappedElem.parentId].children.push(mappedElem);
} else {
data.push(mappedElem);
}
}
}
return data;
}
return [];
};
/// use like this :
const treeData = getTreeData(flatList);
Functional requirements are those which are related to the technical functionality of the system.
non-functional requirement is a requirement that specifies criteria that can be used to judge the operation of a system in particular conditions, rather than specific behaviors.
For example if you consider a shopping site, adding items to cart, browsing different items, applying offers and deals and successfully placing orders comes under functional requirements.
Where as performance of the system in peak hours, time taken for the system to retrieve data from DB, security of the user data, ability of the system to handle if large number of users login comes under non functional requirements.
There is a file in your git root directory named .gitignore
. It's a file, not a command. You just need to insert the names of the files that you want to ignore, and they will automatically be ignored. For example, if you wanted to ignore all emacs autosave files, which end in ~
, then you could add this line:
*~
If you want to remove the unwanted files from your branch, you can use git add -A
, which "removes files that are no longer in the working tree".
Note: What I called the "git root directory" is simply the directory in which you used git init
for the first time. It is also where you can find the .git
directory.
From the PHP-documentation:
Returns FALSE if var has a non-empty and non-zero value.
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)
In case someone is interested, I was looking for something similar and ended writing the following:
public static string NormalizeStringForUrl(string name)
{
String normalizedString = name.Normalize(NormalizationForm.FormD);
StringBuilder stringBuilder = new StringBuilder();
foreach (char c in normalizedString)
{
switch (CharUnicodeInfo.GetUnicodeCategory(c))
{
case UnicodeCategory.LowercaseLetter:
case UnicodeCategory.UppercaseLetter:
case UnicodeCategory.DecimalDigitNumber:
stringBuilder.Append(c);
break;
case UnicodeCategory.SpaceSeparator:
case UnicodeCategory.ConnectorPunctuation:
case UnicodeCategory.DashPunctuation:
stringBuilder.Append('_');
break;
}
}
string result = stringBuilder.ToString();
return String.Join("_", result.Split(new char[] { '_' }
, StringSplitOptions.RemoveEmptyEntries)); // remove duplicate underscores
}
You can remove "JavaAppletPlugin.plugin" found in Spotlight or Finder, then re-install downloaded Java 8.
This will simply solve your problem.
When I refer to Dijkstra’s algorithm in my explanation I will be talking about the Dijkstra's Algorithm as implemented below,
So starting out the values (the distance from the source to the vertex) initially assigned to each vertex are,
We first extract the vertex in Q = [A,B,C] which has smallest value, i.e. A, after which Q = [B, C]. Note A has a directed edge to B and C, also both of them are in Q, therefore we update both of those values,
Now we extract C as (2<5), now Q = [B]. Note that C is connected to nothing, so line16
loop doesn't run.
Finally we extract B, after which . Note B has a directed edge to C but C isn't present in Q therefore we again don't enter the for loop in line16
,
So we end up with the distances as
Note how this is wrong as the shortest distance from A to C is 5 + -10 = -5, when you go .
So for this graph Dijkstra's Algorithm wrongly computes the distance from A to C.
This happens because Dijkstra's Algorithm does not try to find a shorter path to vertices which are already extracted from Q.
What the line16
loop is doing is taking the vertex u and saying "hey looks like we can go to v from source via u, is that (alt or alternative) distance any better than the current dist[v] we got? If so lets update dist[v]"
Note that in line16
they check all neighbors v (i.e. a directed edge exists from u to v), of u which are still in Q. In line14
they remove visited notes from Q. So if x is a visited neighbour of u, the path is not even considered as a possible shorter way from source to v.
In our example above, C was a visited neighbour of B, thus the path was not considered, leaving the current shortest path unchanged.
This is actually useful if the edge weights are all positive numbers, because then we wouldn't waste our time considering paths that can't be shorter.
So I say that when running this algorithm if x is extracted from Q before y, then its not possible to find a path - which is shorter. Let me explain this with an example,
As y has just been extracted and x had been extracted before itself, then dist[y] > dist[x] because otherwise y would have been extracted before x. (line 13
min distance first)
And as we already assumed that the edge weights are positive, i.e. length(x,y)>0. So the alternative distance (alt) via y is always sure to be greater, i.e. dist[y] + length(x,y)> dist[x]. So the value of dist[x] would not have been updated even if y was considered as a path to x, thus we conclude that it makes sense to only consider neighbors of y which are still in Q (note comment in line16
)
But this thing hinges on our assumption of positive edge length, if length(u,v)<0 then depending on how negative that edge is we might replace the dist[x] after the comparison in line18
.
So any dist[x] calculation we make will be incorrect if x is removed before all vertices v - such that x is a neighbour of v with negative edge connecting them - is removed.
Because each of those v vertices is the second last vertex on a potential "better" path from source to x, which is discarded by Dijkstra’s algorithm.
So in the example I gave above, the mistake was because C was removed before B was removed. While that C was a neighbour of B with a negative edge!
Just to clarify, B and C are A's neighbours. B has a single neighbour C and C has no neighbours. length(a,b) is the edge length between the vertices a and b.
It sounds like your application might gain advantage from the use of a Bloom Filter data structure.
In short, a bloom filter look-up can tell you very quickly if a value is DEFINITELY NOT present in a set. Otherwise, you can do a slower look-up to get the index of a value that POSSIBLY MIGHT BE in the list. So if your application tends to get the "not found" result much more often then the "found" result, you might see a speed up by adding a Bloom Filter.
For details, Wikipedia provides a good overview of how Bloom Filters work, and a web search for "python bloom filter library" will provide at least a couple useful implementations.
It is often required to move both body and html objects together.
$('html,body').animate({
scrollTop: $("#divToBeScrolledTo").offset().top
});
ShiftyThomas is right:
$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.
So to increase the margin use:
$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.
Using Powershell V2 and below, get-content reads the entire file, so it was of no use to me. The following code works for what I needed, though there are likely some issues with character encodings. This is effectively tail -f, but it could be easily modified to get the last x bytes, or last x lines if you want to search backwards for line breaks.
$filename = "\wherever\your\file\is.txt"
$reader = new-object System.IO.StreamReader(New-Object IO.FileStream($filename, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read, [IO.FileShare]::ReadWrite))
#start at the end of the file
$lastMaxOffset = $reader.BaseStream.Length
while ($true)
{
Start-Sleep -m 100
#if the file size has not changed, idle
if ($reader.BaseStream.Length -eq $lastMaxOffset) {
continue;
}
#seek to the last max offset
$reader.BaseStream.Seek($lastMaxOffset, [System.IO.SeekOrigin]::Begin) | out-null
#read out of the file until the EOF
$line = ""
while (($line = $reader.ReadLine()) -ne $null) {
write-output $line
}
#update the last max offset
$lastMaxOffset = $reader.BaseStream.Position
}
I found most of the code to do this here.
The documentation for this is good if not a little difficult to find.
Facebook Graph API - Page Tokens
After initializing node's fbgraph, you can run:
var facebookAccountID = yourAccountIdHere
graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
console.log(res);
});
and receive a JSON response with the token you want to grab, located at:
res.data[0].access_token
The numbers starting with 0x
are hexadecimal (base 16).0x6400
represents 25600
.
To convert,
The factors 1, 16, 256, etc. are the increasing powers of 16.
0x6400 = (0*1) + (0*16^1) + (4*16^2) + (6*16^3) = 25600
or
0x6400 = (0*1) + (0*16) + (4*256) + (6*4096) = 25600
try
$('#select_all').click( function() {
$('#countries option').each(function(){
$(this).attr('selected', 'selected');
});
});
this will give you more scope in the future to write things like
$('#select_all').click( function() {
$('#countries option').each(function(){
if($(this).attr('something') != 'omit parameter')
{
$(this).attr('selected', 'selected');
}
});
});
Basically allows for you to do a select all EU members or something if required later down the line
You have two options:
Extend your .paging
class definition:
.paging:hover {
border:1px solid #999;
color:#000;
}
Use the DOM hierarchy to apply the CSS style:
div.paginate input:hover {
border:1px solid #999;
color:#000;
}
The one line answer is -
String path = this.getClass().getClassLoader().getResource(<resourceFileName>).toExternalForm()
Basically getResource
method gives the URL.
From this URL you can extract the path by calling toExternalForm()
References:
At this point you'll have a clean 'develop' branch to which you can merge your feature brach as you regularly do.
[Based on Android source code:]
At the C++ side, the SurfaceFlinger implements the captureScreen API. This is exposed over the binder IPC interface, returning each time a new ashmem area that contains the raw pixels from the screen. The actual screenshot is taken through OpenGL.
For the system C++ clients, the interface is exposed through the ScreenshotClient class, defined in <surfaceflinger_client/SurfaceComposerClient.h>
for Android < 4.1; for Android > 4.1 use <gui/SurfaceComposerClient.h>
Before JB, to take a screenshot in a C++ program, this was enough:
ScreenshotClient ssc;
ssc.update();
With JB and multiple displays, it becomes slightly more complicated:
ssc.update(
android::SurfaceComposerClient::getBuiltInDisplay(
android::ISurfaceComposer::eDisplayIdMain));
Then you can access it:
do_something_with_raw_bits(ssc.getPixels(), ssc.getSize(), ...);
Using the Android source code, you can compile your own shared library to access that API, and then expose it through JNI to Java. To create a screen shot form your app, the app has to have the READ_FRAME_BUFFER
permission.
But even then, apparently you can create screen shots only from system applications, i.e. ones that are signed with the same key as the system. (This part I still don't quite understand, since I'm not familiar enough with the Android Permissions system.)
Here is a piece of code, for JB 4.1 / 4.2:
#include <utils/RefBase.h>
#include <binder/IBinder.h>
#include <binder/MemoryHeapBase.h>
#include <gui/ISurfaceComposer.h>
#include <gui/SurfaceComposerClient.h>
static void do_save(const char *filename, const void *buf, size_t size) {
int out = open(filename, O_RDWR|O_CREAT, 0666);
int len = write(out, buf, size);
printf("Wrote %d bytes to out.\n", len);
close(out);
}
int main(int ac, char **av) {
android::ScreenshotClient ssc;
const void *pixels;
size_t size;
int buffer_index;
if(ssc.update(
android::SurfaceComposerClient::getBuiltInDisplay(
android::ISurfaceComposer::eDisplayIdMain)) != NO_ERROR ){
printf("Captured: w=%d, h=%d, format=%d\n");
ssc.getWidth(), ssc.getHeight(), ssc.getFormat());
size = ssc.getSize();
do_save(av[1], pixels, size);
}
else
printf(" screen shot client Captured Failed");
return 0;
}
that's just a shorthand notation in most languages.which means that
x=x+1;
we can do the same operation for x-=1,x*=1,x/=1; which means
var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item
if (in_array($value, range($min, $max), true)) {
echo "You can be sure that $min <= $value <= $max";
}
if ($value === min(max($value, $min), $max)) {
echo "You can be sure that $min <= $value <= $max";
}
Actually this is what is use to cast a value which is out of the range to the closest end of it.
$value = min(max($value, $min), $max);
/**
* This is un-sanitized user input.
*/
$posts_per_page = 999;
/**
* Sanitize $posts_per_page.
*/
$posts_per_page = min(max($posts_per_page, 5), 30);
/**
* Use.
*/
var_dump($posts_per_page); // Output: int(30)
I have this error while I tried to use JDK 1.7. When I upgraded my JDK to jdk1.8.0_66 all started to work fine.
So the simplest solution for this problem could be - upgrade your JDK and it could start to work well.
How about this:
//Repeats a character specified number of times
public static string Repeat(char character,int numberOfIterations)
{
return "".PadLeft(numberOfIterations, character);
}
//Call the Repeat method
Console.WriteLine(Repeat('\t',40));
I understand that the Q does not want to use a library, but I will offer this for others coming from Google searches. @EricRowell mentioned a good plugin, but, there is also another plugin you can try, html2canvas.
In our case we are using layered transparent PNG's with z-index
as a "product builder" widget. Html2canvas worked brilliantly to boil the stack down without pushing images, nor using complexities, workarounds, and the "non-responsive" canvas itself. We were not able to do this smoothly/sane with the vanilla canvas+JS.
First use z-index
on absolute divs to generate layered content within a relative positioned wrapper. Then pipe the wrapper through html2canvas to get a rendered canvas, which you may leave as-is, or output as an image so that a client may save it.
Use options(scipen=5)
or some other high enough number. The scipen option determines how likely R is to switch to scientific notation, the higher the value the less likely it is to switch. Set the option before making your plot, if it still has scientific notation, set it to a higher number.
Best and easiest way is to use anchor tag in CodeIgniter like eg.
<?php
$this->load->helper('url');
echo anchor('name_of_controller_file/function_name_if_any', 'Sign Out', array('class' => '', 'id' => ''));
?>
Refer https://www.codeigniter.com/user_guide/helpers/url_helper.html for details
This will surely work.
You won't find the component if it hasn't been installed.
In Visual Studio 2019 go to:
Tools > Get Tools and Features > Select the Individual Components tab > Type wcf
in the search box and install it.
This installs the component, and you should be able to load it from the command prompt or other methods suggested in the answer.
One easy solution is to use overflow
values other than visible
to make the text flex basis width reset as expected.
Here with value auto
the text wraps as expected and the article content does not overflow main container.
Also, the article flex
value must either have a auto
basis AND be able to shrink, OR, only grow AND explicit 0
basis
main, aside, article {_x000D_
margin: 10px;_x000D_
border: solid 1px #000;_x000D_
border-bottom: 0;_x000D_
height: 50px;_x000D_
overflow: auto; /* 1. overflow not `visible` */_x000D_
}_x000D_
main {_x000D_
display: flex;_x000D_
}_x000D_
aside {_x000D_
flex: 0 0 200px;_x000D_
}_x000D_
article {_x000D_
flex: 1 1 auto; /* 2. Allow auto width content to shrink */_x000D_
/* flex: 1 0 0; /* Or, explicit 0 width basis that grows */_x000D_
}
_x000D_
<main>_x000D_
<aside>x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x x </aside>_x000D_
<article>don't let flex item overflow container.... y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y y </article>_x000D_
</main>
_x000D_
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.
Offers an arsenal of new functions and operators to add "json-processing".
The answer to the original question in Postgres 9.3:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
Advanced example:
For bigger tables you may want to add an expression index to increase performance:
Adds jsonb
(b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb
also supports GIN, btree and hash indexes, GIN being the most potent of these.
json
and jsonb
data types and functions.The manual goes as far as suggesting:
In general, most applications should prefer to store JSON data as
jsonb
, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.
Bold emphasis mine.
Performance benefits from general improvements to GIN indexes.
Complete jsonb
functions and operators. Add more functions to manipulate jsonb
in place and for display.
You can write:
python
import keras
keras.__version__
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
Correct way of embedding images into Outlook and avoiding security problems is the next:
Do not access properties via getters or you will get security warnings on some machines.
public static void PrepareEmail()
{
var attachFile = Path.Combine(
Application.StartupPath, "mySuperImage.png"); // pay attention that image must not contain spaces, because Outlook cannot inline such images
Microsoft.Office.Interop.Outlook.Application outlook = null;
NameSpace space = null;
MAPIFolder folder = null;
MailItem mail = null;
Attachment attachment = null;
try
{
outlook = new Microsoft.Office.Interop.Outlook.Application();
space = outlook.GetNamespace("MAPI");
space.Logon(null, null, true, true);
folder = space.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
mail = (MailItem) outlook.CreateItem(OlItemType.olMailItem);
mail.SaveSentMessageFolder = folder;
mail.Subject = "Hi Everyone";
mail.Attachments.Add(attachFile, OlAttachmentType.olByValue, 0, Type.Missing);
// Last Type.Missing - is for not to show attachment in attachments list.
string attachmentId = Path.GetFileName(attachFile);
mail.BodyFormat = OlBodyFormat.olFormatHTML;
mail.HTMLBody = string.Format("<br/><img src=\'cid:{0}\' />", attachmentId);
mail.Display(false);
}
finally
{
ReleaseComObject(outlook, space, folder, mail, attachment);
}
}
First make sure that the folder in which your .mdf file resides is not read only. If it is, un-check that option and make sure it reflects to folders and files within that folder.
Once that is done, Open Management Studio, in the Object Explorer right click on the Database which is read only and select Properties. In the Options Menu, check that the Read-Only property is false.
Build URL '/search'
as string. Like
"/search?fname="+fname"+"&lname="+lname
Actually I didn't use
`$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}})`
but I'm sure "params" should be JSON.stringify
like for POST
var jsonData = JSON.stringify(
{
fname: fname,
lname: lname
}
);
After:
$http({
method:'GET',
url:'/search',
params: jsonData
});
Put from before where, and order_by on last:
$this->db->select('*');
$this->db->from('courses');
$this->db->where('tennant_id',$tennant_id);
$this->db->order_by("UPPER(course_name)","desc");
Or try BINARY:
ORDER BY BINARY course_name DESC;
You should add manually on codeigniter for binary sorting.
And set "course_name" character column.
If sorting is used on a character type column, normally the sort is conducted in a case-insensitive fashion.
What type of structure data in courses table?
If you frustrated you can put into array and return using PHP:
Use natcasesort for order in "natural order": (Reference: http://php.net/manual/en/function.natcasesort.php)
Your array from database as example: $array_db = $result_from_db
:
$final_result = natcasesort($array_db);
print_r($final_result);
Check this fully functional directive for MEAN.JS (Angular.js, bootstrap, Express.js and MongoDb)
Based on @Blackhole ´s response, we just finished it to be used with mongodb and express.
It will allow you to save and load dates from a mongoose connector
Hope it Helps!!
angular.module('myApp')
.directive(
'dateInput',
function(dateFilter) {
return {
require: 'ngModel',
template: '<input type="date" class="form-control"></input>',
replace: true,
link: function(scope, elm, attrs, ngModelCtrl) {
ngModelCtrl.$formatters.unshift(function (modelValue) {
return dateFilter(modelValue, 'yyyy-MM-dd');
});
ngModelCtrl.$parsers.push(function(modelValue){
return angular.toJson(modelValue,true)
.substring(1,angular.toJson(modelValue).length-1);
})
}
};
});
The JADE/HTML:
div(date-input, ng-model="modelDate")
Using this code you can get the notification in background/foreground and also put action:
//Data should come in this format from the notification
{
"to": "/xyz/Notifications",
"data": {
"key1": "title notification",
"key2": "description notification"
}
}
In-App use this code:
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
String key1Data = remoteMessage.getData().get("key1");
// use key1Data to according to your need
}
put x=0 outside the for loop that is the problem
This is one of the simplest query for the same that I came across and we use it for monitoring as well:
SELECT TABLESPACE_NAME,SUM(BYTES)/1024/1024/1024 "FREE SPACE(GB)"
FROM DBA_FREE_SPACE GROUP BY TABLESPACE_NAME;
A complete article about Oracle Tablespace: Tablespace
Mine is a 64 bit system with 64bit java installation. what worked for me was the following:
In the target field point it to the correct java 64 bit installations home path using the vm argument with the java_home path enclosed in quotes like so :
D:\Scala_eclipse\eclipse.exe -vm "C:\Program Files\Java\jdk1.8.0_11"
This almost always solves all my Eclipse (scala eclipse as well) related problems. As mentioned in the answer , please make sure you are using the right combination of eclipse and java
I created .pfx file from .key and .pem files.
Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx
That's not the direct answer but still maybe it helps out someone else.
I was getting similar error and I got it resolved this way.
Try to set Build Active Architecture Only to NO for 'Pods' project and your app's target
Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/
Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.
EDIT: Youtube renders the object
and embed
with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:
a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements
b) Find a way for youtube to specify those.
I created a package called json-dry. It supports (circular) references and also class instances.
You have to define 2 new methods in your class (toDry
on the prototype and unDry
as a static method), register the class (Dry.registerClass
), and off you go.
I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.
.divtagABS {
width: 100px;
position: absolute;
left: 50%;
margin-left: -50px;
}
Basically, you use left: 50%, then back it out half of it's width with a negative margin.
const img = '../../img/splash/splash_bg.png';
<ImageBackground source={{ uri: img }} style={styles.backgroundImage} >
</ImageBackground>
This worked for me. Reference to RN docs can be found here.I wrote mine by reading this- https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting
I ran into a similar problem. Simply moving my tsconfig.json from the root of my project up to a different scope helped. In my project, I moved tsconfig.json from the root up to wwwroot.
In the case like me that you aquired a repo and are now switching the remote origin to a different repo, a new empty one...
So you have your repo and all the branches inside, but you still need to checkout those branches for the git push --all
command to actually push those too.
You should do this before you push:
for remote in `git branch -r | grep -v master `; do git checkout --track $remote ; done
Followed by
git push --all
Actually the last one is not weird. Code is setting the timezone for working instead of working2.
SimpleDateFormat working2 = new SimpleDateFormat("hh:mm:ss");
working.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
kk goes from 1 to 24, HH from 0 to 23 and hh from 1 to 12 (AM/PM).
Fixing this error gives:
24:00:00
00:00:00
01:00:00
You can use a HTML table:
<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>
One .Net build with x86/x64 Dependencies
While all other answers give you a solution to make different Builds according to the platform, I give you an option to only have the "AnyCPU" configuration and make a build that works with your x86 and x64 dlls.
You have to write some plumbing code for this.
Resolution of correct x86/x64-dlls at runtime
Steps:
<ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
Add this postbuild script to your startup project, use and modify the paths of this script sp that it copies all your x86/x64 dlls in corresponding subfolders of your build bin\x86\ bin\x64\
xcopy /E /H /R /Y /I /D $(SolutionDir)\YourPathToX86Dlls $(TargetDir)\x86
xcopy /E /H /R /Y /I /D $(SolutionDir)\YourPathToX64Dlls $(TargetDir)\x64
--> When you would start application now, you get an exception that the assembly could not be found.
Register the AssemblyResolve event right at the beginning of your application entry point
AppDomain.CurrentDomain.AssemblyResolve += TryResolveArchitectureDependency;
withthis method:
/// <summary>
/// Event Handler for AppDomain.CurrentDomain.AssemblyResolve
/// </summary>
/// <param name="sender">The app domain</param>
/// <param name="resolveEventArgs">The resolve event args</param>
/// <returns>The architecture dependent assembly</returns>
public static Assembly TryResolveArchitectureDependency(object sender, ResolveEventArgs resolveEventArgs)
{
var dllName = resolveEventArgs.Name.Substring(0, resolveEventArgs.Name.IndexOf(","));
var anyCpuAssemblyPath = $".\\{dllName}.dll";
var architectureName = System.Environment.Is64BitProcess ? "x64" : "x86";
var assemblyPath = $".\\{architectureName}\\{dllName}.dll";
if (File.Exists(assemblyPath))
{
return Assembly.LoadFrom(assemblyPath);
}
return null;
}
Benefits:
Drawbacks: - No errors at compile time when x86/x64 dlls do not match. - You should still run test in both modes!
Optionally create a second executable that is exclusive for x64 architecture with Corflags.exe in postbuild script
Other Variants to try out: - You don't need the AssemblyResolve event handler if you assure that the right dlls are copied to your binary folder at start (Evaluate Process architecture -> move corresponding dlls from x64/x86 to bin folder and back.) - In Installer evaluate architecture and delete binaries for wrong architecture and move the right ones to the bin folder.
Simply run this command. Don't forget to replace portnumber
, with your port ;)
kill -9 $(sudo lsof -t -i:portnumber)
When debugging lines of code, here are the usual scenarios:
Eclipse has other advanced debugging features, but these are the basic fundamentals.
For docker-compose
you can use following docker-compose.yml
version: '2'
services:
nginx:
image: nginx
container_name: nginx-container
networks:
static-network:
ipv4_address: 172.20.128.2
networks:
static-network:
ipam:
config:
- subnet: 172.20.0.0/16
#docker-compose v3+ do not use ip_range
ip_range: 172.28.5.0/24
from host you can test using:
docker-compose up -d
curl 172.20.128.2
Modern docker-compose
does not change ip address that frequently.
To find ips of all containers in your docker-compose
in a single line use:
for s in `docker-compose ps -q`; do echo ip of `docker inspect -f "{{.Name}}" $s` is `docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $s`; done
If you want to automate, you can use something like this example gist
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
If you are trying to do an in-place update of text within a file, this is much easier to reason about in my mind.
grep -Rl text_to_find directory_to_search 2>/dev/null | while read line; do sed -i 's/text_to_find/replacement_text/g' $line; done
For anyone still confused about how to define the service name parameter, the forward slash goes immediately after the application package name in the fully qualified class name.
So given an application package name of: app.package.name
And a full path to the service of: app.package.name.example.package.path.MyServiceClass
Then the command would look like this:
adb shell am startservice app.package.name/.example.package.path.MyServiceClass
This is a good catch by Joe. The code example above has two problems - one - the response object isn't an instance of Bitmap (when my URL references a jpg, like http:\website.com\image.jpg, its a
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl$LimitedInputStream).
Second, as Joe points out, no caching occurs without a response cache being configured. Android developers are left to roll their own cache. Here's an example for doing so, but it only caches in memory, which really isn't the full solution.
http://codebycoffee.com/2010/06/29/using-responsecache-in-an-android-app/
The URLConnection caching API is described here:
http://download.oracle.com/javase/6/docs/technotes/guides/net/http-cache.html
I still think this is an OK solution to go this route - but you still have to write a cache. Sounds like fun, but I'd rather write features.
Try this:
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<Man> Men = new List<Man>();
Man m1 = new Man();
m1.Number = "+1-9169168158";
m1.Message = "Hello Bob from 1";
m1.UniqueCode = "0123";
m1.State = 0;
Man m2 = new Man();
m2.Number = "+1-9296146182";
m2.Message = "Hello Bob from 2";
m2.UniqueCode = "0125";
m2.State = 0;
Men.AddRange(new Man[] { m1, m2 });
string result = JsonConvert.SerializeObject(Men);
Console.WriteLine(result);
List<Man> NewMen = JsonConvert.DeserializeObject<List<Man>>(result);
foreach(Man m in NewMen) Console.WriteLine(m.Message);
}
}
public class Man
{
public string Number{get;set;}
public string Message {get;set;}
public string UniqueCode {get;set;}
public int State {get;set;}
}
Around 1:51 in the video, notice how she puts a <script>
tag in there? The way it works is like this:
Create an html file (that's just a text file with a .html
ending) somewhere on your computer. In the same folder that you put index.html
, put a javascript file (that's just a textfile with a .js
ending - let's call it game.js
). Then, in your index.html
file, put some html that includes the script tag with game.js
, like Mary did in the video. index.html
should look something like this:
<html>
<head>
<script src="game.js"></script>
</head>
</html>
Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).
Good luck on your journey, hope it's as fun for you as it has been for me so far :)
Your code was very close to working.
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
Here's some code that writes each key/value pair on a separate row:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
Here are some variations on Sotirios Delimanolis' answer, which was pretty good to begin with (+1). Consider the following:
static <X, Y, Z> Map<X, Z> transform(Map<? extends X, ? extends Y> input,
Function<Y, Z> function) {
return input.keySet().stream()
.collect(Collectors.toMap(Function.identity(),
key -> function.apply(input.get(key))));
}
A couple points here. First is the use of wildcards in the generics; this makes the function somewhat more flexible. A wildcard would be necessary if, for example, you wanted the output map to have a key that's a superclass of the input map's key:
Map<String, String> input = new HashMap<String, String>();
input.put("string1", "42");
input.put("string2", "41");
Map<CharSequence, Integer> output = transform(input, Integer::parseInt);
(There is also an example for the map's values, but it's really contrived, and I admit that having the bounded wildcard for Y only helps in edge cases.)
A second point is that instead of running the stream over the input map's entrySet
, I ran it over the keySet
. This makes the code a little cleaner, I think, at the cost of having to fetch values out of the map instead of from the map entry. Incidentally, I initially had key -> key
as the first argument to toMap()
and this failed with a type inference error for some reason. Changing it to (X key) -> key
worked, as did Function.identity()
.
Still another variation is as follows:
static <X, Y, Z> Map<X, Z> transform1(Map<? extends X, ? extends Y> input,
Function<Y, Z> function) {
Map<X, Z> result = new HashMap<>();
input.forEach((k, v) -> result.put(k, function.apply(v)));
return result;
}
This uses Map.forEach()
instead of streams. This is even simpler, I think, because it dispenses with the collectors, which are somewhat clumsy to use with maps. The reason is that Map.forEach()
gives the key and value as separate parameters, whereas the stream has only one value -- and you have to choose whether to use the key or the map entry as that value. On the minus side, this lacks the rich, streamy goodness of the other approaches. :-)
Here are some functions I created for working with fullscreen in the browser.
They provide both enter/exit fullscreen across most major browsers.
function isFullScreen()
{
return (document.fullScreenElement && document.fullScreenElement !== null)
|| document.mozFullScreen
|| document.webkitIsFullScreen;
}
function requestFullScreen(element)
{
if (element.requestFullscreen)
element.requestFullscreen();
else if (element.msRequestFullscreen)
element.msRequestFullscreen();
else if (element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if (element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
}
function exitFullScreen()
{
if (document.exitFullscreen)
document.exitFullscreen();
else if (document.msExitFullscreen)
document.msExitFullscreen();
else if (document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.webkitExitFullscreen)
document.webkitExitFullscreen();
}
function toggleFullScreen(element)
{
if (isFullScreen())
exitFullScreen();
else
requestFullScreen(element || document.documentElement);
}
Another way is to use purrr package
# example data like what is said above
@A Handcart And Mohair
set.seed(1)
m <- data.frame(matrix(sample(100, 20, replace = TRUE), ncol = 4))
library(purrr)
means <- map_dbl(m, mean)
> means
# X1 X2 X3 X4
#47.0 64.4 44.8 67.8
var d map[string]string
value, ok := d["key"]
if ok {
fmt.Println("Key Present ", value)
} else {
fmt.Println(" Key Not Present ")
}
A simple way to do this is using ifelse
, which is vectorized. If the condition is satisfied, we use a replacement value, otherwise we use the original value.
v <- c(3, 2, 1, 0, 4, 0)
ifelse(v == 0, 1, v)
We can avoid a named variable by using a pipe.
c(3, 2, 1, 0, 4, 0) %>% ifelse(. == 0, 1, .)
A common task is to do multiple replacements. Instead of nested ifelse
statements, we can use case_when
from dplyr:
case_when(v == 0 ~ 1,
v == 1 ~ 2,
TRUE ~ v)
Old answer:
For factor or character vectors, we can use revalue
from plyr
:
> revalue(c("a", "b", "c"), c("b" = "B"))
[1] "a" "B" "c"
This has the advantage of only specifying the input vector once, so we can use a pipe like
x %>% revalue(c("b" = "B"))
When a CSS property shows as struck-through, it means that the crossed-out style was applied, but then overridden by a more specific selector, a more local rule, or by a later property within the same rule.
(Special cases: a style will also be shown as struck-through if a style exists in an matching rule but is commented out, or if you've manually disabled it by unchecking it within the Chrome developer tools. It will also show as crossed out, but with an error icon, if the style has a syntax error.)
For example, if a background color was applied to all div
s, but a different background color was applied to div
s with a certain id, the first color will show up but will be crossed out, as the second color has replaced it (in the property list for the div
with that id).
You can iterate over the index values if your dataframe has already been created.
df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
print name
print df.loc[name]
This one seems the easiest to me: http://jsfiddle.net/thomporter/DwKZh/
(Code is not mine, I accidentally stumbled upon it)
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// this next if is necessary for when using ng-required on your input.
// In such cases, when a letter is typed first, this parser will be called
// again, and the 2nd time, the value will be undefined
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
Below is an example of multiple figures that I used recently in Latex. You need to call these packages
\usepackage{graphicx}
\usepackage{subfig})
\begin{figure}[H]%
\centering
\subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%
\subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%
\subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
\hfill
\subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%
\subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%
\caption{Multiple figures in latex.}%
\label{fig:MFL}%
\end{figure}
sudo
command not found
to check whether the sudo package is installed on your system, type sudo
, and press Enter . If you have sudo
installed the system will display a short help message, otherwise you will see something like sudo: command not found
To install sudo, run one of the following commands using root account:
apt-get install sudo
# If your system based on apt package manager
yum install sudo
# If your system based on yum package manager
It is worth noting that what you're doing isn't rounding, it's casting. Casting using (int) x
truncates the decimal value of x
. As in your example, if x = 3.9995
, the .9995
gets truncated and x = 3
.
As proposed by many others, one solution is to add 0.5
to x
, and then cast.
For me - the folder from which the service was to run, and the files in it, were encrypted using the Windows "Encrypt" option. Removing that and - voila!
You can do it with OpenCV's function imwrite
:
import cv2
cv2.imwrite('Path/Image.jpg', image_name)
Ram Narasimhan explained the concept very nicely here below is an alternative explanation through the code example of Naive Bayes in action
It uses an example problem from this book on page 351
This is the data set that we will be using
In the above dataset if we give the hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
then what is the probability that he will buy or will not buy a computer.
The code below exactly answers that question.
Just create a file called named new_dataset.csv
and paste the following content.
Age,Income,Student,Creadit_Rating,Buys_Computer
<=30,high,no,fair,no
<=30,high,no,excellent,no
31-40,high,no,fair,yes
>40,medium,no,fair,yes
>40,low,yes,fair,yes
>40,low,yes,excellent,no
31-40,low,yes,excellent,yes
<=30,medium,no,fair,no
<=30,low,yes,fair,yes
>40,medium,yes,fair,yes
<=30,medium,yes,excellent,yes
31-40,medium,no,excellent,yes
31-40,high,yes,fair,yes
>40,medium,no,excellent,no
Here is the code the comments explains everything we are doing here! [python]
import pandas as pd
import pprint
class Classifier():
data = None
class_attr = None
priori = {}
cp = {}
hypothesis = None
def __init__(self,filename=None, class_attr=None ):
self.data = pd.read_csv(filename, sep=',', header =(0))
self.class_attr = class_attr
'''
probability(class) = How many times it appears in cloumn
__________________________________________
count of all class attribute
'''
def calculate_priori(self):
class_values = list(set(self.data[self.class_attr]))
class_data = list(self.data[self.class_attr])
for i in class_values:
self.priori[i] = class_data.count(i)/float(len(class_data))
print "Priori Values: ", self.priori
'''
Here we calculate the individual probabilites
P(outcome|evidence) = P(Likelihood of Evidence) x Prior prob of outcome
___________________________________________
P(Evidence)
'''
def get_cp(self, attr, attr_type, class_value):
data_attr = list(self.data[attr])
class_data = list(self.data[self.class_attr])
total =1
for i in range(0, len(data_attr)):
if class_data[i] == class_value and data_attr[i] == attr_type:
total+=1
return total/float(class_data.count(class_value))
'''
Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
(Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x P(EvidenceN|outcome) x P(Outcome)
scaled by P(Multiple Evidence)
'''
def calculate_conditional_probabilities(self, hypothesis):
for i in self.priori:
self.cp[i] = {}
for j in hypothesis:
self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
print "\nCalculated Conditional Probabilities: \n"
pprint.pprint(self.cp)
def classify(self):
print "Result: "
for i in self.cp:
print i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i]
if __name__ == "__main__":
c = Classifier(filename="new_dataset.csv", class_attr="Buys_Computer" )
c.calculate_priori()
c.hypothesis = {"Age":'<=30', "Income":"medium", "Student":'yes' , "Creadit_Rating":'fair'}
c.calculate_conditional_probabilities(c.hypothesis)
c.classify()
output:
Priori Values: {'yes': 0.6428571428571429, 'no': 0.35714285714285715}
Calculated Conditional Probabilities:
{
'no': {
'<=30': 0.8,
'fair': 0.6,
'medium': 0.6,
'yes': 0.4
},
'yes': {
'<=30': 0.3333333333333333,
'fair': 0.7777777777777778,
'medium': 0.5555555555555556,
'yes': 0.7777777777777778
}
}
Result:
yes ==> 0.0720164609053
no ==> 0.0411428571429
Hope it helps in better understanding the problem
peace
This approach can be used in case commands 'ps', 'pidof' and rest are not available. I personally use procfs very frequently in my tools/scripts/programs.
egrep -m1 "mysqld$|httpd$" /proc/[0-9]*/status | cut -d'/' -f3
Little explanation what is going on:
I find the above answers really lengthy, so to summarize:
The mysqli extension has a number of benefits, the key enhancements over the mysql extension being:
- Object-oriented interface
- Support for Prepared Statements
- Support for Multiple Statements
- Support for Transactions
- Enhanced debugging capabilities
- Embedded server support
Source: MySQLi overview
As explained in the above answers, the alternatives to mysql are mysqli and PDO (PHP Data Objects).
Both MySQLi and PDO were introduced in PHP 5.0, whereas MySQL was introduced prior to PHP 3.0. A point to note is that MySQL is included in PHP5.x though deprecated in later versions.
Get by Location:
moment.locale('pt-br')
return moment().format('DD/MM/YYYY HH:mm:ss')
I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.
This worked for me:
background-image: url('/assets/image.jpg');
Don't fret too much if your initial API is fully RESTful or not (specially when you are just in the alpha stages). Get the back-end plumbing to work first. You can always do some sort of URL transformation/re-writing to map things out, refining iteratively until you get something stable enough for widespread testing ("beta").
You can define URIs whose parameters are encoded by position and convention on the URIs themselves, prefixed by a path you know you'll always map to something. I don't know PHP, but I would assume that such a facility exists (as it exists in other languages with web frameworks):
.ie. Do a "user" type of search with param[i]=value[i] for i=1..4 on store #1 (with value1,value2,value3,... as a shorthand for URI query parameters):
1) GET /store1/search/user/value1,value2,value3,value4
or
2) GET /store1/search/user,value1,value2,value3,value4
or as follows (though I would not recommend it, more on that later)
3) GET /search/store1,user,value1,value2,value3,value4
With option 1, you map all URIs prefixed with /store1/search/user
to the search handler (or whichever the PHP designation) defaulting to do searches for resources under store1 (equivalent to /search?location=store1&type=user
.
By convention documented and enforced by the API, parameters values 1 through 4 are separated by commas and presented in that order.
Option 2 adds the search type (in this case user
) as positional parameter #1. Either option is just a cosmetic choice.
Option 3 is also possible, but I don't think I would like it. I think the ability of search within certain resources should be presented in the URI itself preceding the search itself (as if indicating clearly in the URI that the search is specific within the resource.)
The advantage of this over passing parameters on the URI is that the search is part of the URI (thus treating a search as a resource, a resource whose contents can - and will - change over time.) The disadvantage is that parameter order is mandatory.
Once you do something like this, you can use GET, and it would be a read-only resource (since you can't POST or PUT to it - it gets updated when it's GET'ed). It would also be a resource that only comes to exist when it is invoked.
One could also add more semantics to it by caching the results for a period of time or with a DELETE causing the cache to be deleted. This, however, might run counter to what people typically use DELETE for (and because people typically control caching with caching headers.)
How you go about it would be a design decision, but this would be the way I'd go about. It is not perfect, and I'm sure there will be cases where doing this is not the best thing to do (specially for very complex search criteria).
I am not sure in your case. But as I know to run any jar file from cmd we can use following command:
Go up to the directory where your jar file is saved:
java -jar <jarfilename>.jar
But you can check following links. I hope it'll help you:
Run Netbeans maven project from command-line?
http://www.sonatype.com/books/mvnref-book/reference/running-sect-options.html
public string MakeRelativePath(string workingDirectory, string fullPath)
{
string result = string.Empty;
int offset;
// this is the easy case. The file is inside of the working directory.
if( fullPath.StartsWith(workingDirectory) )
{
return fullPath.Substring(workingDirectory.Length + 1);
}
// the hard case has to back out of the working directory
string[] baseDirs = workingDirectory.Split(new char[] { ':', '\\', '/' });
string[] fileDirs = fullPath.Split(new char[] { ':', '\\', '/' });
// if we failed to split (empty strings?) or the drive letter does not match
if( baseDirs.Length <= 0 || fileDirs.Length <= 0 || baseDirs[0] != fileDirs[0] )
{
// can't create a relative path between separate harddrives/partitions.
return fullPath;
}
// skip all leading directories that match
for (offset = 1; offset < baseDirs.Length; offset++)
{
if (baseDirs[offset] != fileDirs[offset])
break;
}
// back out of the working directory
for (int i = 0; i < (baseDirs.Length - offset); i++)
{
result += "..\\";
}
// step into the file path
for (int i = offset; i < fileDirs.Length-1; i++)
{
result += fileDirs[i] + "\\";
}
// append the file
result += fileDirs[fileDirs.Length - 1];
return result;
}
This code is probably not bullet-proof but this is what I came up with. It's a little more robust. It takes two paths and returns path B as relative to path A.
example:
MakeRelativePath("c:\\dev\\foo\\bar", "c:\\dev\\junk\\readme.txt")
//returns: "..\\..\\junk\\readme.txt"
MakeRelativePath("c:\\dev\\foo\\bar", "c:\\dev\\foo\\bar\\docs\\readme.txt")
//returns: "docs\\readme.txt"
Try just:
powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"
To force git stash pop
run this command
git stash show -p | git apply && git stash drop
I've had a very similar issue using spring-boot-starter-data-redis
. To my implementation there was offered a @Bean
for RedisTemplate
as follows:
@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));
// Add some specific configuration here. Key serializers, etc.
return template;
}
The fix was to specify an array of RoutePlantCache
as following:
template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));
Below the exception I had:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]