Just FYI, you could use the VB.NET Like-Operator:
string text = "x is not the same as X and yz not the same as YZ";
bool contains = LikeOperator.LikeString(text,"*X*YZ*", Microsoft.VisualBasic.CompareMethod.Binary);
Use CompareMethod.Text
if you want to ignore the case.
You need to add using Microsoft.VisualBasic.CompilerServices;
.
Sometimes using libraries are cool when you do not want to reinvent the wheel, but in this case one can do the same job with fewer lines of code and easier to read compared to using libraries. Here is a different approach which I find very easy to use.
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//Define pattern
Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
//Separating columns to array
string[] X = CSVParser.Split(line);
/* Do something with X */
}
}
This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active
next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache
(where all of jQuery.data()
goes).
I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart()
and $.ajaxStop()
(which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.
When jQuery starts an AJAX request, this happens:
if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" );
}
This is what causes the $.ajaxStart()
event to fire, the number of connections just went from 0 to 1 (jQuery.active++
isn't 0 after this one, and !0 == true
), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend
abort via return false
or an ajax call complete
function runs):
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
This is what causes the $.ajaxStop()
event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.
This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.
For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "\n"
or "\r"
.
For example:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
This will result in a script error : integer expression expected
because $a
contains a non-digit newline character "\n"
. You have to remove this character using the instructions here: How to remove carriage return from a string in Bash
So use something like this:
#!/bin/bash
# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'
# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'\t\r\n ']}"
if [ "$a" -gt 1233 ] ; then
echo "number is bigger"
else
echo "number is smaller"
fi
You can also use set -xv
to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/
Change the backend to automatic:
Tools > preferences > IPython console > Graphics > Graphics backend > Backend: Automatic
Then close and open Spyder.
I might just have just gotten a way to bust the frame buster buster javascript. Using the getElementsByName in my javascript function, i've set a loop between the frame buster and the actual frame buster buster script. check this post out. http://www.phcityonweb.com/frame-buster-buster-buster-2426
If you want the value you are assigning in the constructor, you need to add a method in the enum definition to return that value.
If you want a unique number that represent the enum value, you can use ordinal()
.
You can compare a string to an enum item as follow,
public class Main {
enum IaaSProvider{
aws,
microsoft,
google
}
public static void main(String[] args){
IaaSProvider iaaSProvider = IaaSProvider.google;
if("google".equals(iaaSProvider.toString())){
System.out.println("The provider is google");
}
}
}
You are just outside the directory which you are working. Enter into the directory which your project is there and run command ng g c name
.
Just paste this into your line of codes:
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
NOTE: "Asepsis is no longer under active development and supported under OS X 10.11 (El Capitan) and later."
Here's a comprehensive review of your options. Asepsis (the second solution mentioned) seems to be what you're looking for, it re-routes .DS_Store creation to a unified cache instead of being located on every folder.
You need something like this :
UPDATE P
SET ExtrasPrice = E.TotalPrice
FROM dbo.BookingPitches AS P
INNER JOIN (SELECT BPE.PitchID, Sum(BPE.Price) AS TotalPrice
FROM BookingPitchExtras AS BPE
WHERE BPE.[Required] = 1
GROUP BY BPE.PitchID) AS E ON P.ID = E.PitchID
WHERE P.BookingID = 1
There is no interoperable way to encode non-ASCII names in Content-Disposition
. Browser compatibility is a mess.
The theoretically correct syntax for use of UTF-8 in Content-Disposition
is very weird: filename*=UTF-8''foo%c3%a4
(yes, that's an asterisk, and no quotes except an empty single quote in the middle)
This header is kinda-not-quite-standard (HTTP/1.1 spec acknowledges its existence, but doesn't require clients to support it).
There is a simple and very robust alternative: use a URL that contains the filename you want.
When the name after the last slash is the one you want, you don't need any extra headers!
This trick works:
/real_script.php/fake_filename.doc
And if your server supports URL rewriting (e.g. mod_rewrite
in Apache) then you can fully hide the script part.
Characters in URLs should be in UTF-8, urlencoded byte-by-byte:
/mot%C3%B6rhead # motörhead
One way to retain new-line info with JSoup is to precede all new line tags with some dummy string, execute JSoup and replace dummy string with "\n".
String html = "<p>Line one</p><p>Line two</p>Line three<br/>etc.";
String NEW_LINE_MARK = "NEWLINESTART1234567890NEWLINEEND";
for (String tag: new String[]{"</p>","<br/>","</h1>","</h2>","</h3>","</h4>","</h5>","</h6>","</li>"}) {
html = html.replace(tag, NEW_LINE_MARK+tag);
}
String text = Jsoup.parse(html).text();
text = text.replace(NEW_LINE_MARK + " ", "\n\n");
text = text.replace(NEW_LINE_MARK, "\n\n");
I had a situation where I needed to obtain the next available key in an array, which is the highest+1.
For example, if the array is $data=['1'=>'something,'34'=>'something else'] then I needed to calculate 35 to add a new element to the array that had a key higher than any of the others. In the case of an empty array I needed 1 as next available key.
This is the solution that worked:
$highest = 0;
foreach($data as $idx=>$dummy)
{
if($idx > $highest)$highest=$idx;
}
$highest++;
It will work in all cases, empty array or not. If you only need to find the highest key rather than highest key + 1, delete the last line. You will then get a value of 0 if the array is empty.
Put this .gitignore
into the folder, then git add .gitignore
.
*
*/
!.gitignore
The *
line tells git to ignore all files in the folder, but !.gitignore
tells git to still include the .gitignore
file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore
it needs.
Edit: May be obvious but also add */
to the .gitignore
to also ignore subfolders.
In practice, it is possible, if you use span
element instead of font
:
<style>
u { color: black; }
.red { color: red }
</style>
<u><span class='red'><br>$username</span></u>
See jsfiddle. Appears to work on Chrome, Safari, Firefox, IE, Opera (tested on Win 7 with newest versions).
The code in the question should work, too, but it does not work for some reason on WebKit browsers (Chrome, Safari).
By the CSS spec: “The color(s) required for the text decoration must be derived from the 'color' property value of the element on which 'text-decoration' is set. The color of decorations must remain the same even if descendant elements have different 'color' values.”
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
In my case conda Path was properly set (in .bashrc) by the conda installation bash. But to make it works I had to give executable file permissions to files in bin sub folder with chmod +x *
.
My system info:
conda 4.2.9
Operating System: Debian GNU/Linux 8 (jessie)
Kernel: Linux 3.16.0-4-amd64
Architecture: x86-64
This command actually works
\curl -L https://get.rvm.io | bash -s stable --ruby
Suppose you have two arraylist of String type . Like
ArrayList<String> firstArrayList ;//This array list is not having any data.
ArrayList<String> secondArrayList = new ArrayList<>();//Having some data.
Now we have to copy the data of second array to first arraylist like this,
firstArrayList = new ArrayList<>(secondArrayList );
Done!!
Not enough rep for a comment.
The getElementById()
based method in the selected answer won't work if the anchor has name
but not id
set (which is not recommended, but does happen in the wild).
Something to bare in mind if you don't have control of the document markup (e.g. webextension).
The location
based method in the selected answer can also be simplified with location.replace
:
function jump(hash) { location.replace("#" + hash) }
The simplest way to log to file and to stderr:
import logging
logging.basicConfig(filename="logfile.txt")
stderrLogger=logging.StreamHandler()
stderrLogger.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
logging.getLogger().addHandler(stderrLogger)
How to build an image with custom name without using yml file:
docker build -t image_name .
How to run a container with custom name:
docker run -d --name container_name image_name
This worked for me:
sudo pip install numpy --upgrade --ignore-installed
Don't forget the use of """ comments. These need precise indentation too (a 1/2 hr job for me resolving this damn error too!)
Add below line to your pg_hba.conf file. which will be present in installation directory of postgres
hostnossl all all 0.0.0.0/0 trust
It will start working.
As mentioned by @leocaseiro on github issue.
I found 3 solutions for those who are looking for easy fixes.
1) Moving from
ngAfterViewInit
tongAfterContentInit
2) Moving to
ngAfterViewChecked
combined withChangeDetectorRef
as suggested on #14748 (comment)3) Keep with ngOnInit() but call
ChangeDetectorRef.detectChanges()
after your changes.
Both of the above two answers work for me with a similar problem.
However, the body {-webkit-transform} approach causes all elements on the page to effectively be rendered in 3D. This isn't the worst thing, but it slightly changes the rendering of text and other CSS-styled elements.
It may be an effect you want. It may be useful if you're doing a lot of transform on your page. Otherwise, -webkit-backface-visibility:hidden on the element your transforming is the least invasive option.
Judging from your example, shouldn't it be {% url myproject.login.views.login_view %}
and end of story? (replace myproject
with your actual project name)
Just a suggestion SharePoint 2013 online & on-prem file encoding is UTF-8 BOM. Make sure your file is UTF-8 BOM, otherwise your uploaded html and scripts may not rendered correctly in browser.
I translated the code sample in this blog post into Python: How to detect when the client closes the connection?, and it works well for me:
from ctypes import (
CDLL, c_int, POINTER, Structure, c_void_p, c_size_t,
c_short, c_ssize_t, c_char, ARRAY
)
__all__ = 'is_remote_alive',
class pollfd(Structure):
_fields_ = (
('fd', c_int),
('events', c_short),
('revents', c_short),
)
MSG_DONTWAIT = 0x40
MSG_PEEK = 0x02
EPOLLIN = 0x001
EPOLLPRI = 0x002
EPOLLRDNORM = 0x040
libc = CDLL(None)
recv = libc.recv
recv.restype = c_ssize_t
recv.argtypes = c_int, c_void_p, c_size_t, c_int
poll = libc.poll
poll.restype = c_int
poll.argtypes = POINTER(pollfd), c_int, c_int
class IsRemoteAlive: # not needed, only for debugging
def __init__(self, alive, msg):
self.alive = alive
self.msg = msg
def __str__(self):
return self.msg
def __repr__(self):
return 'IsRemoteClosed(%r,%r)' % (self.alive, self.msg)
def __bool__(self):
return self.alive
def is_remote_alive(fd):
fileno = getattr(fd, 'fileno', None)
if fileno is not None:
if hasattr(fileno, '__call__'):
fd = fileno()
else:
fd = fileno
p = pollfd(fd=fd, events=EPOLLIN|EPOLLPRI|EPOLLRDNORM, revents=0)
result = poll(p, 1, 0)
if not result:
return IsRemoteAlive(True, 'empty')
buf = ARRAY(c_char, 1)()
result = recv(fd, buf, len(buf), MSG_DONTWAIT|MSG_PEEK)
if result > 0:
return IsRemoteAlive(True, 'readable')
elif result == 0:
return IsRemoteAlive(False, 'closed')
else:
return IsRemoteAlive(False, 'errored')
I hope I understand your question, but the ng-model
directive creates a two-way binding between the selected item in the control and the value of item.selectedVariant
. This means that changing item.selectedVariant
in JavaScript, or changing the value in the control, updates the other. If item.selectedVariant
has a value of 0
, that item should get selected.
If variants
is an array of objects, item.selectedVariant
must be set to one of those objects. I do not know which information you have in your scope, but here's an example:
JS:
$scope.options = [{ name: "a", id: 1 }, { name: "b", id: 2 }];
$scope.selectedOption = $scope.options[1];
HTML:
<select data-ng-options="o.name for o in options" data-ng-model="selectedOption"></select>
This would leave the "b" item to be selected.
Jean-François Fabre set.intesection(*list_of_sets) answer is definetly the most Pyhtonic and is rightly the accepted answer.
For those that want to use reduce, the following will also work:
reduce(set.intersection, list_of_sets)
Python and just about every other computer language use the same principles as (I hope) you would use when finding a word in a printed dictionary:
(1) Depending on the human language involved, you have a notion of character ordering: 'a' < 'b' < 'c' etc
(2) First character has more weight than second character: 'az' < 'za' (whether the language is written left-to-right or right-to-left or boustrophedon is quite irrelevant)
(3) If you run out of characters to test, the shorter string is less than the longer string: 'foo' < 'food'
Typically, in a computer language the "notion of character ordering" is rather primitive: each character has a human-language-independent number ord(character)
and characters are compared and sorted using that number. Often that ordering is not appropriate to the human language of the user, and then you need to get into "collating", a fun topic.
It is simple. So follow this code.
decimal d = 10.5;
int roundNumber = (int)Math.Floor(d + 0.5);
Result is 11
For me nothing of the above worked. I use the Tk backend on Ubuntu 14.04 which contains matplotlib 1.3.1.
The following code creates a fullscreen plot window which is not the same as maximizing but it serves my purpose nicely:
from matplotlib import pyplot as plt
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
It's netstat -ano|findstr port no
Result would show process id in last column
Unity is an IoC. The point of IoC is to abstract the wiring of dependencies between types outside of the types themselves. This has a couple of advantages. First of all, it is done centrally which means you don't have to change a lot of code when dependencies change (which may be the case for unit tests).
Furthermore, if the wiring is done using configuration data instead of code, you can actually rewire the dependencies after deployment and thus change the behavior of the application without changing the code.
Its the Windows OS that make the problem. I got the same problem. Then I tried some other app which use JavaVM to connect the internet, and they fails. Try update JRE, you will notice it. If JRE cannot update itself, then there is some socket inaccessibility that prevent internet access apart from using native windows API. I reinstall Win7 and it fixed the problem.
Try the following:
zip [zipfile] [file to update]
An example:
$ zip test.zip test/test.txt
updating: test/test.txt (stored 0%)
The usernames are shown in the dba_users's username
column, there is a script you can run called:
alter user username identified by password
You can get more information here - https://community.oracle.com/thread/632617?tstart=0
You can use std::ifstream
, funcion like is_open
, fail
, for example as below code (the cout "open" means file exist or not):
cited from this answer
Those do both mean non-breaking space, yes.  
is another synonym, in hex.
You should not map score to player. You should map player (or his name) to score:
Map<Player, Integer> player2score = new HashMap<Player, Integer>();
Then add players to map: int score = .... Player player = new Player(); player.setName("John"); // etc. player2score.put(player, score);
In this case the task is trivial:
int score = player2score.get(player);
Note: This answer is less current than it was when posted in 2009. Using the subprocess
module shown in other answers is now recommended in the docs
(Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions.)
If you want your process to start in the background you can either use system()
and call it in the same way your shell script did, or you can spawn
it:
import os
os.spawnl(os.P_DETACH, 'some_long_running_command')
(or, alternatively, you may try the less portable os.P_NOWAIT
flag).
See the documentation here.
There is no cross-browser way of styling option elements, certainly not to the extent of your second screenshot. You might be able to make them bold, and set the font-size, but that will be about it...
Try
$(document).ready(
instead of
$('document').ready(
or you can use a shorthand form
$(function(){
});
The problem is that .click only works for elements already on the page.
You have to use something like on
if you are wiring up future elements
$("#LangTable").on("click",".deletelanguage", function(){
alert("success");
});
Assuming you have a class such as
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
calling dir
on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.
>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
You can always filter out the special methods by using a list comprehension.
>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
or if you prefer map/filters.
>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
If you want to filter out the methods, you can use the builtin callable
as a check.
>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']
You could also inspect the difference between your class and its instance object using.
>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])
From SQL Server you can set a Unique key index on the table for (Columns that needs to be unique)
Override the onBackPressed method and do nothing if you meant to handle the back button on the device.
@Override
public void onBackPressed() {
if (shouldAllowBack()) {
super.onBackPressed();
} else {
doSomething();
}
}
Well, if you have Visual Studio (I know it's in 2005, not sure about earlier versions though), you can add the remote machine to your "Server Explorer" tag. At that point, you'll have access to the SERVICES that are running, or can be ran, from that machine (as well as event logs, and queues, and a couple other interesting things).
Use str.split()
:
>>> "42 0".split() # or .split(" ")
['42', '0']
Note that str.split(" ")
is identical in this case, but would behave differently if there were more than one space in a row. As well, .split()
splits on all whitespace, not just spaces.
Using map
usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int
, float
, str
, etc. In Python 2:
>>> map(int, "42 0".split())
[42, 0]
In Python 3, map
will return a lazy object. You can get it into a list with list()
:
>>> map(int, "42 0".split())
<map object at 0x7f92e07f8940>
>>> list(map(int, "42 0".split()))
[42, 0]
Simply use the third parameter for selected value in mvc4
@Html.DropDownList("CountryList", new SelectList(ViewBag.Countries, "Value", "Text","974"))
Here "974" is selected Value Specified
In my result selected country is now qatar.in C# as below`
foreach (CountryModel item in CountryModel.GetCountryList())
{
if (item.CountryPhoneCode.Trim() != "974")
{
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode });
}
else {
countries.Add(new SelectListItem { Text = item.CountryName + " +(" + item.CountryPhoneCode + ")", Value = item.CountryPhoneCode,Selected=true });
}
}
you can use np.int_
:
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> np.int_(x)
array([[1, 2],
[1, 2]])
I was able to do that with :
var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))
the 04/04/2013 is just for testing, replace with your Date Object.
You can run it through the Apache proxy, but it would have to be running in a virtual directory (e.g. http://mysite.something/myreactapp ).
This may seem sort of redundant but if you have other pages that are not part of your React app (e.g. PHP pages), you can serve everything via port 80 and make it apear that the whole thing is a cohesive website.
1.) Start your react app with npm run, or whatever command you are using to start the node server. Assuming it is running on http://127.0.0.1:8080
2.) Edit httpd-proxy.conf and add:
ProxyRequests On
ProxyVia On
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /myreactapp http://127.0.0.1:8080/
ProxyPassReverse /myreactapp http://127.0.0.1:8080/
3.) Restart Apache
CR has changed the Version No of Assemblies. The Old Version is 13.0.2000.0 (this is a incompatible version problem). The New Version is 13.0.3500.0 or 13.0.4000.0 - this is for my test case of Visual Studio 2019 and .net 4.7.2 and Window Server 2019. You need to open all your projects, Remove the old dll reference and add the new references. Then build the application again.
I learnt from source:
Best Answer: https://answers.sap.com/questions/303438/could-not-load-file-or-assembly-%27crystaldecisionsr.html
Installation Notes Crystal Reports for Visual Studio 2017: https://www.tektutorialshub.com/crystal-reports/crystal-reports-download-for-visual-studio/#Service-Pack-16
TO remove: Right click on an assembly under references to remove it.
This is where the error comes from - it is exactly what the error message outputs:
error message:
Could not load file or assembly ... The located assembly's manifest definition does not match the assembly reference ...
location error message referring to:
"C:\Visual-Studio-2019-Proj\Proj Windows Inventory\Proj Windows Inventory\obj\x86\Debug\Press HDL Windows Inventory.exe.manifest"
And it looks like this:
-The older version of .net 3.5 and CReports version="13.0.2000.0" and VS2012:
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="372736">
<assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.2000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />
-The newer version of .net 4.7.2 and CReport version="13.0.4000.0" and VS2019:
<dependentAssembly dependencyType="install" allowDelayedBinding="true" codebase="CrystalDecisions.CrystalReports.Engine.dll" size="373248">
<assemblyIdentity name="CrystalDecisions.CrystalReports.Engine" version="13.0.4000.0" publicKeyToken="692FBEA5521E1304" language="neutral" processorArchitecture="msil" />
To pass variables from node.js to html by using the res.render() method.
Example:
var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set('views', __dirname);
app.get('/', function(req, res){
res.render('index.html',{email:data.email,password:data.password});
});
you can use
var FirstString = YourString.Split().First();
to split string .
In ES6/2015 you can loop through an object like this: (using arrow function)
Object.keys(myObj).forEach(key => {
console.log(key); // the name of the current key.
console.log(myObj[key]); // the value of the current key.
});
In ES7/2016 you can use Object.entries
instead of Object.keys
and loop through an object like this:
Object.entries(myObj).forEach(([key, val]) => {
console.log(key); // the name of the current key.
console.log(val); // the value of the current key.
});
The above would also work as a one-liner:
Object.entries(myObj).forEach(([key, val]) => console.log(key, val));
In case you want to loop through nested objects as well, you can use a recursive function (ES6):
const loopNestedObj = obj => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.
else console.log(key, obj[key]); // or do something with key and val.
});
};
Same as function above, but with ES7 Object.entries()
instead of Object.keys()
:
const loopNestedObj = obj => {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val === "object") loopNestedObj(val); // recurse.
else console.log(key, val); // or do something with key and val.
});
};
Here we loop through nested objects change values and return a new object in one go using Object.entries()
combined with Object.fromEntries()
(ES10/2019):
const loopNestedObj = obj =>
Object.fromEntries(
Object.entries(obj).map(([key, val]) => {
if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse
else [key, updateMyVal(val)]; // or do something with key and val.
})
);
Another way of looping through objects is by using for ... in and for ... of. See @vdegenne's nicely written answer.
To top up on @Tim Schmelter, in which to get back the List<int>
instead,
List<string> selectedValues = CBLGold.Items.Cast<ListItem>()
.Where(li => li.Selected)
.Select(li => li.Value)
.Select(int.Parse)
.ToList();
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
You didn't specify a GradientType
:
background: #f0f0f0; /* Old browsers */
background: -moz-linear-gradient(top, #ffffff 0%, #eeeeee 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffffff), color-stop(100%,#eeeeee)); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* Opera11.10+ */
background: -ms-linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eeeeee',GradientType=0 ); /* IE6-9 */
background: linear-gradient(top, #ffffff 0%,#eeeeee 100%); /* W3C */
TLDR; Pandas groupby.agg
has a new, easier syntax for specifying (1) aggregations on multiple columns, and (2) multiple aggregations on a column. So, to do this for pandas >= 0.25, use
df.groupby('dummy').agg(Mean=('returns', 'mean'), Sum=('returns', 'sum'))
Mean Sum
dummy
1 0.036901 0.369012
OR
df.groupby('dummy')['returns'].agg(Mean='mean', Sum='sum')
Mean Sum
dummy
1 0.036901 0.369012
Pandas has changed the behavior of GroupBy.agg
in favour of a more intuitive syntax for specifying named aggregations. See the 0.25 docs section on Enhancements as well as relevant GitHub issues GH18366 and GH26512.
From the documentation,
To support column-specific aggregation with control over the output column names, pandas accepts the special syntax in
GroupBy.agg()
, known as “named aggregation”, where
- The keywords are the output column names
- The values are tuples whose first element is the column to select and the second element is the aggregation to apply to that column. Pandas provides the pandas.NamedAgg namedtuple with the fields ['column', 'aggfunc'] to make it clearer what the arguments are. As usual, the aggregation can be a callable or a string alias.
You can now pass a tuple via keyword arguments. The tuples follow the format of (<colName>, <aggFunc>)
.
import pandas as pd
pd.__version__
# '0.25.0.dev0+840.g989f912ee'
# Setup
df = pd.DataFrame({'kind': ['cat', 'dog', 'cat', 'dog'],
'height': [9.1, 6.0, 9.5, 34.0],
'weight': [7.9, 7.5, 9.9, 198.0]
})
df.groupby('kind').agg(
max_height=('height', 'max'), min_weight=('weight', 'min'),)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
Alternatively, you can use pd.NamedAgg
(essentially a namedtuple) which makes things more explicit.
df.groupby('kind').agg(
max_height=pd.NamedAgg(column='height', aggfunc='max'),
min_weight=pd.NamedAgg(column='weight', aggfunc='min')
)
max_height min_weight
kind
cat 9.5 7.9
dog 34.0 7.5
It is even simpler for Series, just pass the aggfunc to a keyword argument.
df.groupby('kind')['height'].agg(max_height='max', min_height='min')
max_height min_height
kind
cat 9.5 9.1
dog 34.0 6.0
Lastly, if your column names aren't valid python identifiers, use a dictionary with unpacking:
df.groupby('kind')['height'].agg(**{'max height': 'max', ...})
In more recent versions of pandas leading upto 0.24, if using a dictionary for specifying column names for the aggregation output, you will get a FutureWarning
:
df.groupby('dummy').agg({'returns': {'Mean': 'mean', 'Sum': 'sum'}})
# FutureWarning: using a dict with renaming is deprecated and will be removed
# in a future version
Using a dictionary for renaming columns is deprecated in v0.20. On more recent versions of pandas, this can be specified more simply by passing a list of tuples. If specifying the functions this way, all functions for that column need to be specified as tuples of (name, function) pairs.
df.groupby("dummy").agg({'returns': [('op1', 'sum'), ('op2', 'mean')]})
returns
op1 op2
dummy
1 0.328953 0.032895
Or,
df.groupby("dummy")['returns'].agg([('op1', 'sum'), ('op2', 'mean')])
op1 op2
dummy
1 0.328953 0.032895
Swift 3 @objc Inference The use of Swift 3 @objc inference in Swift 4 mode is deprecated. Please address deprecated @objc inference warnings, test your code with “Use of deprecated Swift 3 @objc inference” logging enabled, and then disable inference by changing the "Swift 3 @objc Inference" build setting to "Default" for the "XMLParsingURL" target.
got to the
First step got Build Setting
Search in to Build Setting Inference
change swift 3 @objc Inference Default
Even after this my code is working fine , so i just removed all warning messages with this statement at line 1 .
<?php error_reporting(E_ERROR); ?>
You can create your custom helper function here
function plusToDate(currentDate, unit, howMuch) {
var config = {
second: 1000, // 1000 miliseconds
minute: 60000,
hour: 3600000,
day: 86400000,
week: 604800000,
month: 2592000000, // Assuming 30 days in a month
year: 31536000000 // Assuming 365 days in year
};
var now = new Date(currentDate);
return new Date(now + config[unit] * howMuch);
}
var today = new Date();
var theDayAfterTommorow = plusToDate(today, 'day', 2);
By the way, this is generic solution for adding seconds or minutes or days whatever you want.
try this one.. (guys I am a new bee.. so if I wrong then I am really sorry. But I found a solution by this way.)
var suggestion = [];
$('#health_condition_name:checked').each(function (j, ob) {
var odata = {
health_condition_name: $(ob).val()
};
health.push(odata);
});
I am supporting iOS 5, 6, & 7. My app is iPad only. I needed to use all of the following:
[[UIApplication sharedApplication] setStatusBarHidden:YES];
View Controller:
- (BOOL)prefersStatusBarHidden{ return YES; }
Info.plist
<key>UIStatusBarHidden</key>
<string>YES</string>
<key>UIStatusBarHidden~ipad</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<string>NO</string>
Push and Pop make sense in terms of the metaphor of a stack of plates or trays in a cafeteria or buffet, specifically the ones in type of holder that has a spring underneath so the top plate is (more or less... in theory) in the same place no matter how many plates are under it.
If you remove a tray, the weight on the spring is a little less and the stack "pops" up a little, if you put the plate back, it "push"es the stack down. So if you think about the list as a stack and the last element as being on top, then you shouldn't have much confusion.
HAVING
operates on aggregates. Since COUNT
is an aggregate function, you can't use it in a WHERE
clause.
Here's some reading from MSDN on aggregate functions.
Be aware that one of PowerShell's security features is that users can NOT launch script with a double click. Use great care if you modify this setting. An alternative might be to package your script. Some editors like PrimalScript can do that. The users still need PowerShell installed but then they can double-click the exe. And it sounds like your team needs a little education.
Try this code, works 100% for me:
FOR Landscape:
<head>
<style type="text/css">
@page{
size: auto A4 landscape;
margin: 3mm;
}
</style>
</head>
FOR Portait:
<head>
<style type="text/css">
@page{
size: auto;
margin: 3mm;
}
</style>
</head>
If you want a localized number of days between two dates (startDate
, endDate
):
var currentLocaleData = moment.localeData("en");
var duration = moment.duration(endDate.diff(startDate));
var nbDays = Math.floor(duration.asDays()); // complete days
var nbDaysStr = currentLocaleData.relativeTime(returnVal.days, false, "dd", false);
nbDaysStr
will contain something like '3 days';
See https://momentjs.com/docs/#/i18n/changing-locale/ for information on how to display the amount of hours or month, for example.
If you don't mind using your mouse a little bit:
This creates a new tab on the terminal which you can run Vim on. Now use your mouse to shift to/from the terminal. I prefer this instead of always having to type (:shell
and exit).
webpack
is not only in your node-modules/webpack/bin/
directory, it's also linked in node_modules/.bin
.
You have the npm bin
command to get the folder where npm will install executables.
You can use the scripts
property of your package.json
to use webpack from this directory which will be exported.
"scripts": {
"scriptName": "webpack --config etc..."
}
For example:
"scripts": {
"build": "webpack --config webpack.config.js"
}
You can then run it with:
npm run build
Or even with arguments:
npm run build -- <args>
This allow you to have you webpack.config.js
in the root folder of your project without having webpack globally installed or having your webpack configuration in the node_modules
folder.
Working perfectly.This exmple will help alot.
<script>
function check()
{
var val = frm1.uname.value;
//alert(val);
if (val.indexOf("@") > 0)
{
alert ("email");
document.getElementById('isEmail1').value = true;
//alert( document.getElementById('isEmail1').value);
}else {
alert("usernam");
document.getElementById('isEmail1').value = false;
//alert( document.getElementById('isEmail1').value);
}
}
</script>
<body>
<h1>My form </h1>
<form action="v1.0/user/login" method="post" id = "frm1">
<p>
UserName : <input type="text" id = "uname" name="username" />
</p>
<p>
Password : <input type="text" name="password" />
</p>
<p>
<input type="hidden" class="email" id = "isEmail1" name = "isEmail"/>
</p>
<input type="submit" id = "submit" value="Add User" onclick="return check();"/>
</form>
</body>
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
I switch between zsh and bash somewhat frequently. For a while, I used to have to source my bash_profile every switch. Then I found out you can (typically) do
exec bash --login
or just
exec bash -l
it is not possible to do using only html
num1=0.555
num2=2.555
if [ `echo "$num1>$num2"|bc` -eq 1 ]; then
echo "$num1 is greater then $num2"
else
echo "$num2 is greater then $num1"
fi
Basic method
$query = parse_url($url, PHP_URL_QUERY);
// Returns a string if the URL has parameters or NULL if not
if ($query) {
$url .= '&category=1';
} else {
$url .= '?category=1';
}
More advanced
$url = 'http://example.com/search?keyword=test&category=1&tags[]=fun&tags[]=great';
$url_parts = parse_url($url);
// If URL doesn't have a query string.
if (isset($url_parts['query'])) { // Avoid 'Undefined index: query'
parse_str($url_parts['query'], $params);
} else {
$params = array();
}
$params['category'] = 2; // Overwrite if exists
$params['tags'][] = 'cool'; // Allows multiple values
// Note that this will url_encode all values
$url_parts['query'] = http_build_query($params);
// If you have pecl_http
echo http_build_url($url_parts);
// If not
echo $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'] . '?' . $url_parts['query'];
You should put this in a function at least, if not a class.
You can use the the click function to trigger the click event on the selected element.
Example:
$( 'selector for your link' ).click ();
You can learn about various selectors in jQuery's documentation.
EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined. You could solve this with something like this:
var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
document.location = linkEl.attr ( 'href' );
} else {
linkEl.click ();
}
Don't know about addEventListener though.
Use:
$filenameFormat = "mybackup.zip" + " " + (Get-Date -Format "yyyy-MM-dd")
Rename-Item -Path "C:\temp\mybackup.zip" -NewName $filenameFormat
Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently
Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10
I recently ran into this problem and discovered that it was caused by the "Adblock" extension (my best guess is that it's because I had the words "banner" and "ad" in the filename).
As a quick test to see if that's your problem, start Chrome in incognito mode with extensions disabled (ctrl+shift+n) and see if your page works now. Note that by default all extensions will be already disabled in incognito mode unless you've specifically set them to run (via chrome://extensions
).
Check out your php.ini, you can set these values there.
Here's the description in the php manual: http://php.net/manual/en/mail.configuration.php
If you want to use several different SMTP servers in your application, I recommend using a "bigger" mailing framework, p.e. Swiftmailer
TL;DR: Do not omit username@
in your remote URLs when on Windows.
On Linux and on Windows with the default ssh, you can omit the username from remote URLs, like so:
git clone server-name:/srv/git/repo-name
Because ssh's default behavior is to just use whatever username you're currently logged in with. If you're on Windows and have set up git to use plink.exe
so that you can use the key loaded in your pageant
, then this will not work, because plink
does not have this same automatic username behavior, resulting in those cryptic error messages, because it will prompt for the username:
$ plink server-name
login as: _
Versus:
$ plink username@server-name
...logs you in...
If you already cloned a repository somehow you can fix the remotes in your .git/config
by adding the username@
to the remote URL.
Try removing the .
before the .bmp
(it isn't matching BMP
as expected). As you can see from the error, the save_handler
is upper-casing the format
you provided and then looking for a match in SAVE
. However the corresponding key in that object is BMP
(instead of .BMP
).
I don't know a great deal about PIL
, but from some quick searching around it seems that it is a problem with the mode
of the image. Changing the definition of j
to:
j = Image.fromarray(b, mode='RGB')
Seemed to work for me (however note that I have very little knowledge of PIL
, so I would suggest using @mmgp's solution as s/he clearly knows what they are doing :) ). For the types of mode
, I used this page - hopefully one of the choices there will work for you.
The X-Powered-By header is added by IIS to the HTTP response, so you can remove it even on server level via IIS Manager:
You can use the web.config directly:
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
As simple as:
your_map.begin()->first // key
your_map.begin()->second // value
mins = minutes + 1
should be
minutes = minutes + 1
Also,
minutes = 0
needs to be outside of the while loop.
Here is how you define a react onClick event handler, which was answering the question title... using es6 syntax
import React, { Component } from 'react';
export default class Test extends Component {
handleClick(e) {
e.preventDefault()
console.log(e.target)
}
render() {
return (
<a href='#' onClick={e => this.handleClick(e)}>click me</a>
)
}
}
I found an article under the above topic.There by I could take the full code .I will mention it.
Here are steps mentioned in the article:
Add embedded/result/ at the end of the JSFiddle URL you wanna grab.
Show the frame or the frame’s source code: right-click anywhere in the page and view the frame in a new tab or the source right-away (requires Firefox).
Finally, save the page in your preferred format (MHT, HTML, TXT, etc.) and voilà!
also you can find it : https://sirusdark.wordpress.com/2014/04/10/how-to-save-and-download-jsfiddle-code/
If you are looking for a single result, rather than an array, may I suggest reduce?
Here is a solution in plain 'ole javascript that returns a matching object if one exists, or null if not.
var result = arr.reduce(function(prev, curr) { return (curr.b === 6) ? curr : prev; }, null);
I found handy place to use friend access: Unittest of private functions.
You basically can loop over a Range
Get a sheet
myWs = (Worksheet)MyWb.Worksheets[1];
Get the Range you're interested in If you really want to check every cell use Excel's limits
The Excel 2007 "Big Grid" increases the maximum number of rows per worksheet from 65,536 to over 1 million, and the number of columns from 256 (IV) to 16,384 (XFD). from here http://msdn.microsoft.com/en-us/library/aa730921.aspx#Office2007excelPerf_BigGridIncreasedLimitsExcel
and then loop over the range
Range myBigRange = myWs.get_Range("A1", "A256");
string myValue;
foreach(Range myCell in myBigRange )
{
myValue = myCell.Value2.ToString();
}
If you're using HTML5, you can use the placeholder
attribute.
<input type="text" name="user" placeholder="Username">
If you have windows 64 bits, try to install oracle driver 32 bits first then 64 bits driver, thats what i do and is working
On a button in jQuery mobile, for instance, you can tweak it a bit by applying this style to the image:
.btn-image {
vertical-align:middle;
margin:0 0 3px 0;
}
$ dseditgroup -o edit -u <adminusername> -t user -a <developerusername> _developer
You can add this line on top of your script:
#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt
OR else to redirect only stdout use:
exec > logfile.txt
Barebones C program to produce the above error:
#include <iostream>
using namespace std;
int main(){
char *p;
*p = 'c';
cout << *p[0];
//error: invalid type argument of `unary *'
//peeking too deeply into p, that's a paddlin.
cout << **p;
//error: invalid type argument of `unary *'
//peeking too deeply into p, you better believe that's a paddlin.
}
ELI5:
The master puts a shiny round stone inside a small box and gives it to a student. The master says: "Open the box and remove the stone". The student does so.
Then the master says: "Now open the stone and remove the stone". The student said: "I can't open a stone".
The student was then enlightened.
Naming convention for collection
In order to name a collection few precautions to be taken :
Things to keep in mind while creating a database name are :
For more information. Please check the below link : http://www.tutorial-points.com/2016/03/schema-design-and-naming-conventions-in.html
We made a little tool for this type of thing https://github.com/taskrabbit/elasticsearch-dump
If you know the viewport angle of the camera, you can use the height in pixels to determine the angle from the top to bottom of the object. Then, using the distance and arctangent calculate the height:
height = arctan(angle) * distance
To find the viewport angle, point the camera at something which is of known height, and make it exactly fill the screen. For example, point it at a ruler, and make it just far enough away that you can only barely see the ends of the ruler. Measure the distance from the camera, and then your total viewport angle is
viewportAngle = tan(ruler_length / distance)
Then, suppose your camera is 480px tall (cheap webcam), and the view angle is 20°. If you have an object onscreen which is 240px tall, then its angle is 10°. If you know it's 2 feet away, you would say 2 feet * arctan(10°) = ~4.1 inches
tall. (I think... it's 2am so this may be a little off)
You could also use this:
$('.slider').slick({
//other settings ................
respondTo: 'slider', //makes the slider to change width depending on the container it is in
adaptiveHeight: true //makes the height change depending on the height of the element inside
})
use the format 'mm/dd/yyyy'. For example :- new Date('02/28/2015'). It works well in all browsers.
You can also configure CXFNonSpringJAXRSServlet (assuming JSONProvider is used):
<init-param>
<param-name>jaxrs.providers</param-name>
<param-value>
org.apache.cxf.jaxrs.provider.JSONProvider
(writeXsiType=false)
</param-value>
</init-param>
For those who want to do this in pure javascript, look at:
As Joe comment it, KeyboardEvent is now the standard.
Same example to fire an enter (keyCode 13):
const ke = new KeyboardEvent('keydown', {
bubbles: true, cancelable: true, keyCode: 13
});
document.body.dispatchEvent(ke);
You can use this page help you to find the right keyboard event.
Outdated answer:
You can do something like (here for Firefox)
var ev = document.createEvent('KeyboardEvent');
// Send key '13' (= enter)
ev.initKeyEvent(
'keydown', true, true, window, false, false, false, false, 13, 0);
document.body.dispatchEvent(ev);
"getops" and "getopt" are very limited. While "getopt" is suggested not to be used at all, it does offer long options. Where as "getopts" does only allow single character options such as "-a" "-b". There are a few more disadvantages when using either one.
So i've written a small script that replaces "getopts" and "getopt". It's a start, it could probably be improved a lot.
Update 08-04-2020: I've added support for hyphens e.g. "--package-name".
Usage: "./script.sh package install --package "name with space" --build --archive"
# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
PREVIOUS_ITEM=''
COUNT=0
for CURRENT_ITEM in "${@}"
do
if [[ ${CURRENT_ITEM} == "--"* ]]; then
printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
else
if [[ $PREVIOUS_ITEM == "--"* ]]; then
printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
else
printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
fi
fi
PREVIOUS_ITEM="${CURRENT_ITEM}"
(( COUNT++ ))
done
}
# Format argument.
function formatArgument() {
ARGUMENT="${1^^}" # Capitalize.
ARGUMENT="${ARGUMENT/--/}" # Remove "--".
ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
echo "${ARGUMENT}"
}
You need to modify 3 things in order to make Google USB driver work for any android phone on any Windows:
android_winusb.inf
fileadb_usb.ini
whitelist (no longer required)and here are the details:
1. Add your device's ID to android_winusb.inf
file
the format to add is:
;Comment usually the device name
%SingleAdbInterface% = USB_Install, USB\; here you put VID and PID
%CompositeAdbInterface% = USB_Install, USB\; same as above but add the MI
before I go on, VID
is the USB Vendor ID.
How to get the vid and pid : they are in drivers you are merging; but if you don’t have a driver for the device you can get it by opening device manager; then right-click the device – select properties-in new dialog go to Details tab >in property drop menu select hardware ids. for example you see something like:
USB\VID_2207&PID_0000&REV_0222&MI_01
USB\VID_2207&PID_0000&MI_01
take this value for composite adb device and remove MI for single adb device, you get
;MSI WindPad Enjoy 7 plus
%SingleAdbInterface% = USB_Install, USB\VID_2207&PID_0000
%CompositeAdbInterface% = USB_Install, USB\VID_2207&PID_0000&REV_0222&MI_01
;
copy this 2 line TWICE , once to [Google.NTx86] section and another to [Google.NTamd64] section
REPEAT for every device you want to support
Now an optional edit for [Strings] Section: edit
[Strings]
ProviderName = “Google, Inc.”
SingleAdbInterface = “Android ADB Interface”
CompositeAdbInterface = “Android Composite ADB Interface”
SingleBootLoaderInterface = “Android Bootloader Interface”
WinUSB_SvcDesc = “Android USB Driver”
DISK_NAME = “Android WinUsb installation disk”
ClassName = “Android Device”
To:
[Strings]
ProviderName = “Google, Inc.”
SingleAdbInterface = “MSI ADB Interface”
CompositeAdbInterface = “MSI Composite ADB Interface”
SingleBootLoaderInterface = “MSI Bootloader Interface”
WinUSB_SvcDesc = “MSI USB Driver”
DISK_NAME = “MSI WinUsb installation disk”
ClassName = “MSI Tablet”
2. Digitally sign the modified driver:
Although the original google usb driver was signed by google , modifying android_winusb.inf will prevent installing it on windows 8 showning an error message
The hash file is not present in the specified catalog file. The file is likely
corrupt or the victim of tampering.
This is only in Windows 8. Windows 7 or earlier do not show this error message. You have to regenerate catalog file (probably with Windows SDK) and sign
Workaround: A workaround for internal tesing is to diable windows signature verification : either temporarily or permanently:
temporarily:
Go to left upper or lower corner of screen to open charms bar and click settings charm.
choose Change PC settings
choose General
Scroll down, and click ‘Restart now’ under ‘Advanced startup’.
Click ‘Troubleshoot’. Click ‘Advanced Options’ Click ‘Windows Startup Settings’ Click Restart.
or
run cmd and type:
shutdown -o -r -t 0
then after restarting choose ‘Disable driver signature enforcement‘ from the list . install your driver before restarting.
Permanently:
press Window+Q
search for cmd
right click cmd
choose run as administrator from action bar
type in cmd:
bcdedit -set loadoptions DISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON
3. Add your device's vendor ID to adb_usb.ini
whitelist (no longer required):
adb
used to have a hard-coded whitelist of supported Vendor IDs. If your device's vendor was not on the list - the adb
was ignoring it completely. To make adb
recognize such devices users had to manually add their vendor IDs to %USERPROFILE%\.android\adb_usb.ini
- one ID per line.
in the command line:
echo 0x2207 >> "%USERPROFILE%\.android\adb_usb.ini"
Fortunately, Google has removed the VendorID filtering in more recent adb
versions. So this step is no longer required.
Finally you can test installation by :
adb kill-server
adb start-server
adb devices
and enabling debugging in developer options on android device
This should restart ADB Server and list devices. If driver is working ok, the device should be listed.
I like this method a little more for Javascript but it seems worth including here because it has not been mentioned yet.
$var = "pizza";
$text = implode(" ", [
"I love me some",
"really large",
$var,
"pies.",
]);
// "I love me some really large pizza pies."
For smaller things, I find it is often easier to work with array structures compared to concatenated strings.
Related: implode vs concat performance
update 2 ::slotted
::slotted
is now supported by all new browsers and can be used with ViewEncapsulation.ShadowDom
https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted
update 1 ::ng-deep
/deep/
was deprecated and replaced by ::ng-deep
.
::ng-deep
is also already marked deprecated, but there is no replacement available yet.
When ViewEncapsulation.Native
is properly supported by all browsers and supports styling accross shadow DOM boundaries, ::ng-deep
will probably be discontinued.
original
Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using [innerHTML]
these classes are not added and the rewritten CSS doesn't match.
As a workaround try
/* :host /deep/ mySelector { */
:host ::ng-deep mySelector {
background-color: blue;
}
index.html
/* body /deep/ mySelector { */
body ::ng-deep mySelector {
background-color: green;
}
>>>
(and the equivalent/deep/
but /deep/
works better with SASS) and ::shadow
were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with encapsulation: ViewEncapsulation.Emulated
which is the default in Angular2. They probably also work with ViewEncapsulation.None
but are then only ignored because they are not necessary.
These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.
Another approach is to use
@Component({
...
encapsulation: ViewEncapsulation.None,
})
for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be all components in your application)
Update
1) Why does the x-axis (frequency) end at 500? How do I know that there aren't more frequencies or are they just ignored?
It ends at 500Hz because that is the Nyquist frequency of the signal when sampled at 1000Hz. Look at this line in the Mathworks example:
f = Fs/2*linspace(0,1,NFFT/2+1);
The frequency axis of the second plot goes from 0 to Fs/2, or half the sampling frequency. The Nyquist frequency is always half the sampling frequency, because above that, aliasing occurs:
The signal would "fold" back on itself, and appear to be some frequency at or below 500Hz.
2) How do I know the frequencies are between 0 and 500? Shouldn't the FFT tell me, in which limits the frequencies are?
Due to "folding" described above (the Nyquist frequency is also commonly known as the "folding frequency"), it is physically impossible for frequencies above 500Hz to appear in the FFT; higher frequencies will "fold" back and appear as lower frequencies.
Does the FFT only return the amplitude value without the frequency?
Yes, the MATLAB FFT function only returns one vector of amplitudes. However, they map to the frequency points you pass to it.
Let me know what needs clarification so I can help you further.
use zzz instead of TZD
Example:
DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");
Response:
2011-08-09T11:50:00:02+02:00
Best solution IMHO:
in fragment:
protected void addClick(int id) {
try {
getView().findViewById(id).setOnClickListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
public void onClick(View v) {
if (v.getId()==R.id.myButton) {
onMyButtonClick(v);
}
}
then in Fragment's onViewStateRestored:
addClick(R.id.myButton);
Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/
The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.
Setting Up a Custom SSH Server
The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.
You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.
How Do I Do That? Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.
Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.
To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.
Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.
Example 10-1. sshserver.py
from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os
class SSHDemoProtocol(recvline.HistoricRecvLine):
def __init__(self, user):
self.user = user
def connectionMade(self) :
recvline.HistoricRecvLine.connectionMade(self)
self.terminal.write("Welcome to my test SSH server.")
self.terminal.nextLine()
self.do_help()
self.showPrompt()
def showPrompt(self):
self.terminal.write("$ ")
def getCommandFunc(self, cmd):
return getattr(self, ‘do_’ + cmd, None)
def lineReceived(self, line):
line = line.strip()
if line:
cmdAndArgs = line.split()
cmd = cmdAndArgs[0]
args = cmdAndArgs[1:]
func = self.getCommandFunc(cmd)
if func:
try:
func(*args)
except Exception, e:
self.terminal.write("Error: %s" % e)
self.terminal.nextLine()
else:
self.terminal.write("No such command.")
self.terminal.nextLine()
self.showPrompt()
def do_help(self, cmd=”):
"Get help on a command. Usage: help command"
if cmd:
func = self.getCommandFunc(cmd)
if func:
self.terminal.write(func.__doc__)
self.terminal.nextLine()
return
publicMethods = filter(
lambda funcname: funcname.startswith(‘do_’), dir(self))
commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods]
self.terminal.write("Commands: " + " ".join(commands))
self.terminal.nextLine()
def do_echo(self, *args):
"Echo a string. Usage: echo my line of text"
self.terminal.write(" ".join(args))
self.terminal.nextLine()
def do_whoami(self):
"Prints your user name. Usage: whoami"
self.terminal.write(self.user.username)
self.terminal.nextLine()
def do_quit(self):
"Ends your session. Usage: quit"
self.terminal.write("Thanks for playing!")
self.terminal.nextLine()
self.terminal.loseConnection()
def do_clear(self):
"Clears the screen. Usage: clear"
self.terminal.reset()
class SSHDemoAvatar(avatar.ConchUser):
implements(conchinterfaces.ISession)
def __init__(self, username):
avatar.ConchUser.__init__(self)
self.username = username
self.channelLookup.update({‘session’:session.SSHSession})
def openShell(self, protocol):
serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
serverProtocol.makeConnection(protocol)
protocol.makeConnection(session.wrapProtocol(serverProtocol))
def getPty(self, terminal, windowSize, attrs):
return None
def execCommand(self, protocol, cmd):
raise NotImplementedError
def closed(self):
pass
class SSHDemoRealm:
implements(portal.IRealm)
def requestAvatar(self, avatarId, mind, *interfaces):
if conchinterfaces.IConchUser in interfaces:
return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
else:
raise Exception, "No supported interfaces found."
def getRSAKeys():
if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
# generate a RSA keypair
print "Generating RSA keypair…"
from Crypto.PublicKey import RSA
KEY_LENGTH = 1024
rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
publicKeyString = keys.makePublicKeyString(rsaKey)
privateKeyString = keys.makePrivateKeyString(rsaKey)
# save keys for next time
file(‘public.key’, ‘w+b’).write(publicKeyString)
file(‘private.key’, ‘w+b’).write(privateKeyString)
print "done."
else:
publicKeyString = file(‘public.key’).read()
privateKeyString = file(‘private.key’).read()
return publicKeyString, privateKeyString
if __name__ == "__main__":
sshFactory = factory.SSHFactory()
sshFactory.portal = portal.Portal(SSHDemoRealm())
users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
sshFactory.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))
pubKeyString, privKeyString =
getRSAKeys()
sshFactory.publicKeys = {
‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
sshFactory.privateKeys = {
‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}
from twisted.internet import reactor
reactor.listenTCP(2222, sshFactory)
reactor.run()
{mospagebreak title=Setting Up a Custom SSH Server continued}
sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:
$ ssh admin@localhost -p 2222
admin@localhost’s password: aaa
>>> Welcome to my test SSH server.
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit
Connection to localhost closed.
I reproduced this just now by accident:
lists the remote branches
git branch -r
origin/Feature/f1234
origin/master
I want to checkout one locally, so I cut paste:
git checkout origin/Feature/f1234
Presto! Detached HEAD state
You are in 'detached HEAD' state. [...])
Solution #1:
Do not include origin/
at the front of my branch spec when checking it out:
git checkout Feature/f1234
Solution #2:
Add -b
parameter which creates a local branch from the remote
git checkout -b origin/Feature/f1234
or
git checkout -b Feature/f1234
it will fall back to origin automatically
For Windows - Open your Default Browser - Tested on VS Code v 1.1.0
Answer to both opening a specific file (name is hard-coded) OR opening ANY other file.
Steps:
Use ctrl + shift + p (or F1) to open the Command Palette.
Type in Tasks: Configure Task
or on older versions Configure Task Runner
. Selecting it will open the tasks.json file. Delete the script displayed and replace it by the following:
{
"version": "0.1.0",
"command": "explorer",
"windows": {
"command": "explorer.exe"
},
"args": ["test.html"]
}
Remember to change the "args" section of the tasks.json file to the name of your file. This will always open that specific file when you hit F5.
You may also set the this to open whichever file you have open at the time by using ["${file}"]
as the value for "args". Note that the $
goes outside the {...}
, so ["{$file}"]
is incorrect.
Save the file.
Switch back to your html file (in this example it's "text.html"), and press ctrl + shift + b to view your page in your Web Browser.
If you don't want a "library" for that, you can use this badly hack:
((ViewGroup)((ViewGroup)getDialog().getWindow().getDecorView()).getChildAt(0)) //ie LinearLayout containing all the dialog (title, titleDivider, content)
.getChildAt(1) // ie the view titleDivider
.setBackgroundColor(getResources().getColor(R.color.yourBeautifulColor));
This was tested and work on 4.x; not tested under, but if my memory is good it should work for 2.x and 3.x
$("#myTable > tbody").empty();
It won't touch the headers.
I know the question has been asked a long time ago, but I am surprised that nobody has given the most straightforward unix answer:
split -l 5000 -d --additional-suffix=.txt $FileName file
-l 5000
: split file into files of 5,000 lines each.-d
: numerical suffix. This will make the suffix go from 00 to 99 by default instead of aa to zz.--additional-suffix
: lets you specify the suffix, here the extension$FileName
: name of the file to be split.file
: prefix to add to the resulting files.As always, check out man split
for more details.
For Mac, the default version of split
is apparently dumbed down. You can install the GNU version using the following command. (see this question for more GNU utils)
brew install coreutils
and then you can run the above command by replacing split
with gsplit
. Check out man gsplit
for details.
You can also check run time. Put one breakpoint in code and inside (lldb) console write
(lldb) po [yourObject class]
Like this..
I use this:
interface IObjectKeys {
[key: string]: string | number;
}
interface IDevice extends IObjectKeys {
id: number;
room_id: number;
name: string;
type: string;
description: string;
}
If you use the optional property in your object:
interface IDevice extends IObjectKeys {
id: number;
room_id?: number;
name?: string;
type?: string;
description?: string;
}
... you should add 'undefined' value into the IObjectKeys interface:
interface IObjectKeys {
[key: string]: string | number | undefined;
}
You need the "correlation id" (the "AS SS" thingy) on the sub-select to reference the fields in the "ON" condition. The id's assigned inside the sub select are not usable in the join.
SELECT
cs.CUSID
,dp.DEPID
FROM
CUSTMR cs
LEFT OUTER JOIN (
SELECT
DEPID
,DEPNAME
FROM
DEPRMNT
WHERE
dp.DEPADDRESS = 'TOKYO'
) ss
ON (
ss.DEPID = cs.CUSID
AND ss.DEPNAME = cs.CUSTNAME
)
WHERE
cs.CUSID != ''
Update for Swift 4:
let now = Date() // the current date/time
let oneDayFromNow = Calendar.current.date(byAdding: .day, value: 1, to: now) // Tomorrow with same time of day as now
SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
What is the difference between
<init-param>
and<context-param>
!?
Single servlet versus multiple servlets.
Other Answers give details, but here is the summary:
A web app, that is, a “context”, is made up of one or more servlets.
<init-param>
defines a value available to a single specific servlet within a context.<context-param>
defines a value available to all the servlets within a context.You are trying to access a menu item from an activity, which dont have the access to scope. The call to find the menu item will return null, because the view is not binded with neither the activity nor the layout you are calling from.
The menu items are binded with items such as "Navigation Bar" which in turn are binded with the corresponding activity.
So initialize those views in activity (), and then access the menu items withing that views.
Navigation navView;
navView = findViewById(R.id.navigationView);
MenuItem item = navView.getMenu().findItem(R.id.item_hosting);
item.setVisible(false);
You can catch form input values using FormData and send them by fetch
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {_x000D_
fetch(form.action,{method:'post', body: new FormData(form)});_x000D_
_x000D_
console.log('We send post asynchronously (AJAX)');_x000D_
e.preventDefault();_x000D_
}
_x000D_
<form method="POST" action="myapi/send" onsubmit="send(event,this)">_x000D_
<input hidden name="crsfToken" value="a1e24s1">_x000D_
<input name="email" value="[email protected]">_x000D_
<input name="phone" value="123-456-789">_x000D_
<input type="submit"> _x000D_
</form>_x000D_
_x000D_
Look on chrome console>network before 'submit'
_x000D_
I had the same problem. Here's what I did:
I downloaded pywin32 Wheel file from here, then
I uninstalled the pywin32 module. To uninstall execute the following command in Command Prompt.
pip uninstall pywin32
Then, I reinstalled pywin32. To install it, open the Command Prompt in the same directory where the pywin32 wheel file lies. Then execute the following command.
pip install <Name of the wheel file with extension>
Wheel file will be like: piwin32-XXX-cpXX-none-win32.whl
It solvs the problem for me. You may also like to give it a try. Hope it work for you as well.
This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.
There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.
You wan't to either change the user that the Service runs under from "System" or find a sneaky way to run your mapping as System.
The funny thing is that this is possible by using the "at" command, simply schedule your drive mapping one minute into the future and it will be run under the System account making the drive visible to your service.
Yes you just need to install the other version of python, and define the location of your other version of python in your command like :
virtualenv /home/payroll/Documents/env -p /usr/bin/python3
List<Item> list;
Map<Key,Item> map = new HashMap<Key,Item>();
for (Item i : list) map.put(i.getKey(),i);
Assuming of course that each Item has a getKey()
method that returns a key of the proper type.
Set the html tag, too. This way no weird position hacks are required.
html, body {height: 100%}
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
0xA0 (Unicode) is 0xC2A0 in UTF-8. .encode('utf8')
will just take your Unicode 0xA0 and replace with UTF-8's 0xC2A0. Hence the apparition of 0xC2s... Encoding is not replacing, as you've probably realized now.
Just wrap it around then.
<?php
if ( ($cart->count_product) > 0)
{
echo "<div class='my_class'>";
print $cart->count_product;
echo "</div>";
}
?>
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
A little late but this could help: http://webdesign.tutsplus.com/tutorials/how-to-make-responsive-scrollable-panels-with-flexbox--cms-23269
Basically you need to put html
,body
to height: 100%;
and wrap all your content into a <div class="wrap"> <!-- content --> </div>
CSS:
html, body {
height: 100%;
}
.wrap {
height: 100vh;
display: flex;
}
Worked for me. Hope it helps
The following solution reads from a file if the script is called
with a file name as the first parameter $1
otherwise from standard input.
while read line
do
echo "$line"
done < "${1:-/dev/stdin}"
The substitution ${1:-...}
takes $1
if defined otherwise
the file name of the standard input of the own process is used.
Instead of:
void foo(char *s);
foo("constant string");
This works:
void foo(const char s[]);
foo("constant string");
To get instance classname:
type(instance).__name__
or
instance.__class__.__name__
both are the same
The only easy way to do this is to use snprintf
to print to a buffer that's long enough to hold the entire, exact value, then truncate it as a string. Something like:
char buf[2*(DBL_MANT_DIG + DBL_MAX_EXP)];
snprintf(buf, sizeof buf, "%.*f", (int)sizeof buf, x);
char *p = strchr(buf, '.'); // beware locale-specific radix char, though!
p[2+1] = 0;
puts(buf);
VUE_APP_API_ENDPOINT ='http://localtest.me:8000'
axios.defaults.baseURL = process.env.VUE_APP_API_ENDPOINT
And that's it. Axios default base Url is replaced with build mode specific API endpoint. If you need specific baseURL for specific request, do it like this:
this.$axios({ url: 'items', baseURL: 'http://new-url.com' })
For Linux the F12 combination does not work. Instead, use:
Left Ctrl + F11
You should use the string replace function, with a single regex. Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";_x000D_
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
You can use String.Join
. If you have a List<string>
then you can call ToArray
first:
List<string> names = new List<string>() { "John", "Anna", "Monica" };
var result = String.Join(", ", names.ToArray());
In .NET 4 you don't need the ToArray
anymore, since there is an overload of String.Join
that takes an IEnumerable<string>
.
Results:
John, Anna, Monica
Thanks for the answers guys. My problem was that I changed a x64 solution in Visual Studio to 32 bit in the Configuration Manager only. I ended up just creating a new solution as 32 bit and then copying my C++ code and this error was gone. I think l00g33k and RogerAttrill's suggestions may have been the solution, but mine worked, too.
this problem arises when you have some file that is not yet added and committed to git.
git add .
git commit -m "commit done"
git push heroku master
When slicing in Python the third parameter is the step. As others mentioned, see Extended Slices for a nice overview.
With this knowledge, [::3]
just means that you have not specified any start or end indices for your slice. Since you have specified a step, 3
, this will take every third entry of something
starting at the first index. For example:
>>> '123123123'[::3]
'111'
just in case someone comes to this question, I have the easier version.
public static MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button);
Button b2 = (Button) findViewById(R.id.button2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.game);
mp.start();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
// mp.start();
}
});
}
Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):
There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.
Note that Apache recommends using apachectl -k
as the command, and for systemd, the command is replaced by httpd -k
apachectl -k graceful
or httpd -k graceful
Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.
apachectl -k restart
or httpd -k restart
This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.
Ternjs is a new alternative for getting JS autocompletion. http://ternjs.net/
Sublime Plugin
The most well-maintained Tern plugin for Sublime Text is called 'tern_for_sublime'
There is also an older plugin called 'TernJS'. It is unmaintained and contains several performance related bugs, that cause Sublime Text to crash, so avoid that.
You can also modify your config/routes.rb file like:
get 'ajax/:action', to: 'ajax#:action', :defaults => { :format => 'json' }
Which will default the format to json. It is working fine for me in Rails 4.
Or if you want to go even further and you are using namespaces, you can cut down the duplicates:
namespace :api, defaults: {format: 'json'} do
#your controller routes here ...
end
with the above everything under /api
will be formatted as json by default.
FileUtils
is class from apache org.apache.commons.io
package, you need to download org.apache.commons.io.jar
and then configure that jar
file in your class path.
Thread interruption is based on flag interrupt status. For every thread default value of interrupt status is set to false. Whenever interrupt() method is called on thread, interrupt status is set to true.
If your server is Apache, you should be able to configure it to see the repository list with viewvc - this is the most basic one, other more complex interfaces exist but this is not your purpose here.
In some versions, ViewVC is an option of the standard installation now, for instance from Collabnet.
Edit: Nevermind my previous idea just above, Peter has a much simpler way of sending the repository list.
From there, you will have to:
Unfortunately in this case I cannot think of something more straightforward.
There are examples on SO on how to extract text from HTML pages in Python, this would be a good option since Python also has bindings for SVN, to perform the repository search - you can still call svn
directly from Python if you prefer.
If Python is not your cup of tea, you will have to process that differently with GNU tools (wget, then parsing tools or existing packages - I can't be of much help there, Carl gave you some more details in this post).
TL;DR: This would very likely work:
python mypkg/tests/test_module.py MyCase.testItIsHot
The explanation:
The convenient way
python mypkg/tests/test_module.py MyCase.testItIsHot
would work, but its unspoken assumption is you already have this conventional code snippet inside (typically at the end of) your test file.
if __name__ == "__main__":
unittest.main()
The inconvenient way
python -m unittest mypkg.tests.test_module.TestClass.test_method
would always work, without requiring you to have that if __name__ == "__main__": unittest.main()
code snippet in your test source file.
So why is the second method considered inconvenient? Because it would be a pain in the <insert one of your body parts here> to type that long, dot-delimited path by hand. While in the first method, the mypkg/tests/test_module.py
part can be auto-completed, either by a modern shell, or by your editor.
Installing libpq-dev did not work for me. I also needed to install build-essential
sudo apt-get install libpq-dev build-essential
Ok, folks I've been slowly building a catch all method for this over some years lol! The trick is to:
For an example (or to see how I dealt with the problem) look at the following code on github: https://github.com/elycruz/sjljs/blob/master/src/sjl/sjl.js and search for:
classOf =
,
classOfIs =
, and or
defineSubClass =
(without the backticks (`)).
As you can see I have some mechanisms in place to force classOf
to always give me the classes/constructors type name regardless of whether it is a primitive, a user defined class, a value created using a native constructor, Null, NaN, etc.. For every single javascript value I will get it's unique type name from the classOf
function. In addition I can pass in actual constructors into sjl.classOfIs
to check a value's type in addition to being able to pass in it's type name as well! So for example:
``` // Please forgive long namespaces! I had no idea on the impact until after using them for a while (they suck haha)
var SomeCustomClass = sjl.package.stdlib.Extendable.extend({
constructor: function SomeCustomClass () {},
// ...
}),
HelloIterator = sjl.ns.stdlib.Iterator.extend(
function HelloIterator () {},
{ /* ... methods here ... */ },
{ /* ... static props/methods here ... */ }
),
helloIt = new HelloIterator();
sjl.classOfIs(new SomeCustomClass(), SomeCustomClass) === true; // `true`
sjl.classOfIs(helloIt, HelloIterator) === true; // `true`
var someString = 'helloworld';
sjl.classOfIs(someString, String) === true; // `true`
sjl.classOfIs(99, Number) === true; // true
sjl.classOf(NaN) === 'NaN'; // true
sjl.classOf(new Map()) === 'Map';
sjl.classOf(new Set()) === 'Set';
sjl.classOfIs([1, 2, 4], Array) === true; // `true`
// etc..
// Also optionally the type you want to check against could be the type's name
sjl.classOfIs(['a', 'b', 'c'], 'Array') === true; // `true`!
sjl.classOfIs(helloIt, 'HelloIterator') === true; // `true`!
```
If you are interested in reading more on how I use the setup mentioned above take a look at the repo: https://github.com/elycruz/sjljs
Also books with content on the subject: - "JavaScript Patterns" by Stoyan Stefanov. - "Javascript - The Definitive Guide." by David Flanagan. - and many others.. (search le` web).
Also you can quickly test the features I'm talking about here: - http://sjljs.elycruz.com/0.5.18/tests/for-browser/ (also the 0.5.18 path in the url has the sources from github on there minus the node_modules and such).
Happy Coding!
create your fixedheader inside the "success" of your ajax call, you will not have any alignment problem in header and rows.
success: function (result) {
/* Your code goes here */
var table = $(SampleTablename).DataTable();
new $.fn.dataTable.FixedHeader(table);
}
I had this problem with a Swift project where I'm creating the buttons dynamically. Problem code:
var trashBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "newButtonClicked")
}
func newButtonClicked(barButtonItem: UIBarButtonItem) {
NSLog("A bar button item on the default toolbar was clicked: \(barButtonItem).")
}
The solution was to add a full colon ':' after the action: e.g.
var trashBarButtonItem: UIBarButtonItem {
return UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "newButtonClicked:")
}
func newButtonClicked(barButtonItem: UIBarButtonItem) {
NSLog("A bar button item on the default toolbar was clicked: \(barButtonItem).")
}
Full example here: https://developer.apple.com/library/content/samplecode/UICatalog/Listings/Swift_UIKitCatalog_DefaultToolbarViewController_swift.html
It seems that you're mainly hesitating whether to use a relational model or not.
As it stands, your example would fit a relational model reasonably well, but the problem may come of course when you need to make this model evolve.
If you only have one (or a few pre-determined) levels of attributes for your main entity (user), you could still use an Entity Attribute Value (EAV) model in a relational database. (This also has its pros and cons.)
If you anticipate that you'll get less structured values that you'll want to search using your application, MySQL might not be the best choice here.
If you were using PostgreSQL, you could potentially get the best of both worlds. (This really depends on the actual structure of the data here... MySQL isn't necessarily the wrong choice either, and the NoSQL options can be of interest, I'm just suggesting alternatives.)
Indeed, PostgreSQL can build index on (immutable) functions (which MySQL can't as far as I know) and in recent versions, you could use PLV8 on the JSON data directly to build indexes on specific JSON elements of interest, which would improve the speed of your queries when searching for that data.
EDIT:
Since there won't be too many columns on which I need to perform search, is it wise to use both the models? Key-per-column for the data I need to search and JSON for others (in the same MySQL database)?
Mixing the two models isn't necessarily wrong (assuming the extra space is negligible), but it may cause problems if you don't make sure the two data sets are kept in sync: your application must never change one without also updating the other.
A good way to achieve this would be to have a trigger perform the automatic update, by running a stored procedure within the database server whenever an update or insert is made. As far as I'm aware, the MySQL stored procedure language probably lack support for any sort of JSON processing. Again PostgreSQL with PLV8 support (and possibly other RDBMS with more flexible stored procedure languages) should be more useful (updating your relational column automatically using a trigger is quite similar to updating an index in the same way).
typedef
defines a new data type. So you can have:
typedef char* my_string;
typedef struct{
int member1;
int member2;
} my_struct;
So now you can declare variables with these new data types
my_string s;
my_struct x;
s = "welcome";
x.member1 = 10;
For enum
, things are a bit different - consider the following examples:
enum Ranks {FIRST, SECOND};
int main()
{
int data = 20;
if (data == FIRST)
{
//do something
}
}
using typedef enum
creates an alias for a type:
typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
Order data = (Order)20; // Must cast to defined type to prevent error
if (data == FIRST)
{
//do something
}
}
The solutions like cmd /c pause
cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.
The solutions using Read-Host
force the user to press Enter and are not really "any key".
This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause
command.
Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)
Well, you can do it also through an S3 client if you prefer a human friendly UI.
I use CrossFTP, which is free and cross-platform, and there you can right-click on the folder directory -> select "Properties..." -> click on "Calculate" button next to Size and voila.
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf
and postgres.conf
files I finally found out that my firewall was overriding everything and therefore blocking connections
try my solution. I use 'required' attribute to get know whether input is filled and if not I show the text from attribute 'placeholder'
//HTML
<input required placeholder="Date" class="textbox-n" type="date" id="date">
//CSS
input[type="date"]:not(:valid):before {
content: attr(placeholder);
// style it like it real placeholder
}
CSS Cursor:Pointer;
is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer;
on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.
I could help you out with the html:
<option value="">abc</option>
instead of
<option value="4">abc</option>
to set abc as the default value.
...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...
For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:
When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.
More info:
For two or multiple arrays, this simple and clean utility method can be used:
/**
* Append the given byte arrays to one big array
*
* @param arrays The arrays to append
* @return The complete array containing the appended data
*/
public static final byte[] append(final byte[]... arrays) {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
if (arrays != null) {
for (final byte[] array : arrays) {
if (array != null) {
out.write(array, 0, array.length);
}
}
}
return out.toByteArray();
}
Here you can find a good example of how to format Y-Axis value.
Also, you can use scaleLabel : "<%=value%>"
that you mentioned, It basically means that everything between <%=
and %>
tags will be treated as javascript code (i.e you can use if
statments...)
IF "%1"=="" GOTO :Continue
.....
.....
:Continue
IF "%1"=="" echo No Parameter given
Use the following code. I have added reference to React and React DOM. Use ES6/Babel to transform you JS code into vanilla JavaScript. Note that Render method comes from ReactDOM and make sure that render method has a target specified in the DOM. Sometimes you might face an issue that the render() method can't find the target element. This happens because the react code is executed before the DOM renders. To counter this use jQuery ready() to call the render() method of React. This way you will be sure about DOM being rendered first. You can also use defer attribute on your app script.
HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div id='main-content'></div>
<script src="CDN link to/react-15.1.0.js"></script>
<script src="CDN link to/react-dom-15.1.0.js"></script>
</body>
</html>
JS code:
var LikeOrNot = React.createClass({
render: function () {
return (
<li>Like</li>
);
}
});
ReactDOM.render(<LikeOrNot />,
document.getElementById('main-content'));
Hope this solves your issue. :-)
This is one way to do it using a list comprehension, though it's increasingly wasteful as the length of the rpt
string increases.
def repeat(rpt, length):
return ''.join([rpt for x in range(0, (len(rpt) % length))])[:length]
Unfortunately, there is not a direct way to do this with a single formula. However, there is a fairly simple workaround that exists.
On the Excel Ribbon, go to "Formulas" and click on "Name Manager". Select "New" and then enter "CellColor" as the "Name". Jump down to the "Refers to" part and enter the following:
=GET.CELL(63,OFFSET(INDIRECT("RC",FALSE),1,1))
Hit OK then close the "Name Manager" window.
Now, in cell A1 enter the following:
=IF(CellColor=3,"FQS",IF(CellColor=6,"SM",""))
This will return FQS for red and SM for yellow. For any other color the cell will remain blank.
***If the value in A1 doesn't update, hit 'F9' on your keyboard to force Excel to update the calculations at any point (or if the color in B2 ever changes).
Below is a reference for a list of cell fill colors (there are 56 available) if you ever want to expand things: http://www.smixe.com/excel-color-pallette.html
Cheers.
::Edit::
The formula used in Name Manager can be further simplified if it helps your understanding of how it works (the version that I included above is a lot more flexible and is easier to use in checking multiple cell references when copied around as it uses its own cell address as a reference point instead of specifically targeting cell B2).
Either way, if you'd like to simplify things, you can use this formula in Name Manager instead:
=GET.CELL(63,Sheet1!B2)
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
I used a two step process to change rows with "blank" values to "Null" values as place holders.
UPDATE [TableName] SET [TableName].[ColumnName] = "0"
WHERE ((([TableName].[ColumnName])=""));
UPDATE [TableName] SET [TableName].[ColumnName] = "Null"
WHERE ((([TableName].[ColumnName])="0"));
Not my web page, but this command from http://www.ixbrian.com/blog/?p=64&cm_mc_uid=89402252817914508279022&cm_mc_sid_50200000=1450827902 works nicely for me on centos. It will show actual cpus even when hyperthreading is enabled.
cat /proc/cpuinfo | egrep "core id|physical id" | tr -d "\n" | sed s/physical/\\nphysical/g | grep -v ^$ | sort | uniq | wc -l
\rm -f file
will never report not found.
For raw speed, use C. For power, use C++. For .NET compatibility, use C#.
They're all pretty complex as languages go; C through decades of gradual accretion, C++ through years of more rapid enhancement, and C# through the power of Microsoft.
Using a dict wouldn't like double your memory usage unless the objects you're storing are really tiny, since the values are only pointers to the actual objects:
>>> a = 'foo'
>>> b = [a]
>>> c = [a]
>>> b[0] is c[0]
True
In that example, 'foo' is only stored once. Does that make a difference for you? And exactly how many items are we talking about anyway?
Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which will raise KeyError
if dictionary[old_key]
is undefined. Note that this will delete dictionary[old_key]
.
>>> dictionary = { 1: 'one', 2:'two', 3:'three' }
>>> dictionary['ONE'] = dictionary.pop(1)
>>> dictionary
{2: 'two', 3: 'three', 'ONE': 'one'}
>>> dictionary['ONE'] = dictionary.pop(1)
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: 1
storing peoples like this
{"Anna" : {
"age": 18,
"profession": "student"},
"Ben" : {
"age" : "nineteen",
"profession": "mechanic"}
}
will cause problems, particularly if differents peoples have same name..
rather use array storing objects like this
{
"peoples":[
{
"name":"Anna",
"age": 18,
"profession": "student"
},
{
"name":"Ben",
"age" : "nineteen",
"profession": "mechanic"
}
]
}
like this, you can enumerates objects, or acces objects by numerical index. remember that json is storage structure, not dynamically sorter or indexer. use data stored in json to build indexes as you need and acces data.
Applying the recursive function on numpy arrays will be faster than the current answer.
df = pd.DataFrame(np.repeat(np.arange(2, 6),3).reshape(4,3), columns=['A', 'B', 'D'])
new = [df.D.values[0]]
for i in range(1, len(df.index)):
new.append(new[i-1]*df.A.values[i]+df.B.values[i])
df['C'] = new
Output
A B D C
0 1 1 1 1
1 2 2 2 4
2 3 3 3 15
3 4 4 4 64
4 5 5 5 325
There is another (somewhat easier) solution, without the size problems. I used this approach today (on a 2003 XLS file, using Excel 2007) and was successful.
DPB=...
partDPB=...
string to DPx=...
*NOTE: Be sure that you have changed the password to a new value, otherwise the next time you open the spreadsheet Excel will report errors (Unexpected Error), then when you access the list of VBA modules you will now see the names of the source modules but receive another error when trying to open forms/code/etc. To remedy this, go back to the VBA Project Properties and set the password to a new value. Save and re-open the Excel document and you should be good to go!
Instead of using a collector try using findFirst
or findAny
.
Optional<Person> matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findFirst();
This returns an Optional
since the list might not contain that object.
If you're sure that the list always contains that person you can call:
Person person = matchingObject.get();
Be careful though! get
throws NoSuchElementException
if no value is present. Therefore it is strongly advised that you first ensure that the value is present (either with isPresent
or better, use ifPresent
, map
, orElse
or any of the other alternatives found in the Optional
class).
If you're okay with a null
reference if there is no such person, then:
Person person = matchingObject.orElse(null);
If possible, I would try to avoid going with the null
reference route though. Other alternatives methods in the Optional class (ifPresent
, map
etc) can solve many use cases. Where I have found myself using orElse(null)
is only when I have existing code that was designed to accept null
references in some cases.
Optionals have other useful methods as well. Take a look at Optional javadoc.
As of Xcode 3.2.5 and Snow Leopard (Mac OS X 10.6), you can run your code through the Zombies instrument: Run > Run with Performance Tool > Zombies
. That allows you to see particular objects and their retain counts on a timeline.