Thanks to jimhark's answer and other answers here, I found a way to do it in PowerShell:
$ProcessID = 1234
$MemberDefinition = '
[DllImport("kernel32.dll")]public static extern bool FreeConsole();
[DllImport("kernel32.dll")]public static extern bool AttachConsole(uint p);
[DllImport("kernel32.dll")]public static extern bool GenerateConsoleCtrlEvent(uint e, uint p);
public static void SendCtrlC(uint p) {
FreeConsole();
if (AttachConsole(p)) {
GenerateConsoleCtrlEvent(0, p);
FreeConsole();
}
AttachConsole(uint.MaxValue);
}'
Add-Type -Name 'dummyName' -Namespace 'dummyNamespace' -MemberDefinition $MemberDefinition
[dummyNamespace.dummyName]::SendCtrlC($ProcessID) }
What made things work was sending the GenerateConsoleCtrlEvent to the desired process group instead of all processes that share the console of the calling process
and AttachConsole back to the console of the parent of the current process
.
I also had this issue with my Android app depending on some of my own Android libraries (using Android Studio 3.0 and 3.1.1).
Whenever I updated a lib and go back to the app, triggering a Gradle Sync, Android Studio was not able to detect the code changes I made to the lib. Compilation worked fine, but Android Studio showed red error lines on some code using the lib.
After investigating, I found that it's because gradle keeps pointing to an old compiled version of my libs. If you go to yourProject/.idea/libraries/ you'll see a list of xml files that contains the link to the compiled version of your libs. These files starts with Gradle__artifacts_*.xml (where * is the name of your libs).
So in order for Android Studio to take the latest version of your libs, you need to delete these Gradle__artifacts_*.xml files, and Android Studio will regenerate them, pointing to the latest compiled version of your libs.
If you don't want to do that manually every time you click on "Gradle sync" (who would want to do that...), you can add this small gradle task in the build.gradle file of your app.
task deleteArtifacts {
doFirst {
File librariesFolderPath = file(getProjectDir().absolutePath + "/../.idea/libraries/")
File[] files = librariesFolderPath.listFiles({ File file -> file.name.startsWith("Gradle__artifacts_") } as FileFilter)
for (int i = 0; i < files.length; i++) {
files[i].delete()
}
}
}
And in order for your app to always execute this task before doing a gradle sync, you just need to go to the Gradle window, then find the "deleteArtifacts" task under yourApp/Tasks/other/, right click on it and select "Execute Before Sync" (see below).
Now, every time you do a Gradle sync, Android Studio will be forced to use the latest version of your libs.
Since this is the top-rated Stack Overflow Google search result for C++ split string
or similar, I'll post a complete, copy/paste runnable example that shows both methods.
splitString
uses stringstream
(probably the better and easier option in most cases)
splitString2
uses find
and substr
(a more manual approach)
// SplitString.cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
// function prototypes
std::vector<std::string> splitString(const std::string& str, char delim);
std::vector<std::string> splitString2(const std::string& str, char delim);
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx);
int main(void)
{
// Test cases - all will pass
std::string str = "ab,cd,ef";
//std::string str = "abcdef";
//std::string str = "";
//std::string str = ",cd,ef";
//std::string str = "ab,cd,"; // behavior of splitString and splitString2 is different for this final case only, if this case matters to you choose which one you need as applicable
std::vector<std::string> tokens = splitString(str, ',');
std::cout << "tokens: " << "\n";
if (tokens.empty())
{
std::cout << "(tokens is empty)" << "\n";
}
else
{
for (auto& token : tokens)
{
if (token == "") std::cout << "(empty string)" << "\n";
else std::cout << token << "\n";
}
}
return 0;
}
std::vector<std::string> splitString(const std::string& str, char delim)
{
std::vector<std::string> tokens;
if (str == "") return tokens;
std::string currentToken;
std::stringstream ss(str);
while (std::getline(ss, currentToken, delim))
{
tokens.push_back(currentToken);
}
return tokens;
}
std::vector<std::string> splitString2(const std::string& str, char delim)
{
std::vector<std::string> tokens;
if (str == "") return tokens;
int leftIdx = 0;
int delimIdx = str.find(delim);
int rightIdx;
while (delimIdx != std::string::npos)
{
rightIdx = delimIdx - 1;
std::string token = getSubstring(str, leftIdx, rightIdx);
tokens.push_back(token);
// prep for next time around
leftIdx = delimIdx + 1;
delimIdx = str.find(delim, delimIdx + 1);
}
rightIdx = str.size() - 1;
std::string token = getSubstring(str, leftIdx, rightIdx);
tokens.push_back(token);
return tokens;
}
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx)
{
return str.substr(leftIdx, rightIdx - leftIdx + 1);
}
There's an important facet to instanceof that does not seem to be covered in any of the comments thus far: inheritance. A variable being evaluated by use of instanceof could return true for multiple "types" due to prototypal inheritance.
For example, let's define a type and a subtype:
function Foo(){ //a Foo constructor
//assign some props
return this;
}
function SubFoo(){ //a SubFoo constructor
Foo.call( this ); //inherit static props
//assign some new props
return this;
}
SubFoo.prototype = Object.create(Foo.prototype); // Inherit prototype
SubFoo.prototype.constructor = SubFoo;
Now that we have a couple of "classes" lets make some instances, and find out what they're instances of:
var
foo = new Foo()
, subfoo = new SubFoo()
;
alert(
"Q: Is foo an instance of Foo? "
+ "A: " + ( foo instanceof Foo )
); // -> true
alert(
"Q: Is foo an instance of SubFoo? "
+ "A: " + ( foo instanceof SubFoo )
); // -> false
alert(
"Q: Is subfoo an instance of Foo? "
+ "A: " + ( subfoo instanceof Foo )
); // -> true
alert(
"Q: Is subfoo an instance of SubFoo? "
+ "A: " + ( subfoo instanceof SubFoo )
); // -> true
alert(
"Q: Is subfoo an instance of Object? "
+ "A: " + ( subfoo instanceof Object )
); // -> true
See that last line? All "new" calls to a function return an object that inherits from Object. This holds true even when using object creation shorthand:
alert(
"Q: Is {} an instance of Object? "
+ "A: " + ( {} instanceof Object )
); // -> true
And what about the "class" definitions themselves? What are they instances of?
alert(
"Q: Is Foo an instance of Object? "
+ "A:" + ( Foo instanceof Object)
); // -> true
alert(
"Q: Is Foo an instance of Function? "
+ "A:" + ( Foo instanceof Function)
); // -> true
I feel that understanding that any object can be an instance of MULTIPLE types is important, since you my (incorrectly) assume that you could differentiate between, say and object and a function by use of instanceof
. As this last example clearly shows a function is an object.
This is also important if you are using any inheritance patterns and want to confirm the progeny of an object by methods other than duck-typing.
Hope that helps anyone exploring instanceof
.
I'd like to add that there is name for those inverted if's - Guard Clause. I use it whenever I can.
I hate reading code where there is if at the beginning, two screens of code and no else. Just invert if and return. That way nobody will waste time scrolling.
The cause for me receiving this error was trying the new pre-release VSCode JS debugger.
If you opted in, change via User settings:
"debug.javascript.usePreview": true|false
Everything in my normal configuration and integrated terminal was correct and finding executables. I wasted a lot of time trying other things!
A better alternative to using pointers to pointers is to use std::vector
. That takes care of the details of memory allocation and deallocation.
std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}
Add two bindings to your website, one for local access and another for LAN access like so:
Open IIS and select your local website (that you want to access from your local network) from the left panel:
Connections > server (user-pc) > sites > local site
Open Bindings on the right panel under Actions tab add these bindings:
Local:
Type: http Ip Address: All Unassigned Port: 80 Host name: samplesite.local
LAN:
Type: http Ip Address: <Network address of the hosting machine ex. 192.168.0.10> Port: 80 Host name: <Leave it blank>
Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.
NOTE:
if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):
192.168.0.10 samplesite.local
To answer a more generic case, this error is noticed when you pick a function name which is already used in some built in library. For e.g., select.
A simple method to know about it is while compiling the file, the compiler will indicate the previous declaration.
This solution is for Vue-2 users:
vue-2
if you don't like to keep your files in static
folder (relevant info), orvue-2
& vue-cli-3
if you don't like to keep your files in public
folder (static
folder is renamed to public
):The simple solution is :)
<img src="@/assets/img/clear.gif" /> // just do this:
<img :src="require(`@/assets/img/clear.gif`)" // or do this:
<img :src="require(`@/assets/img/${imgURL}`)" // if pulling from: data() {return {imgURL: 'clear.gif'}}
If you like to keep your static images in static/assets/img
or public/assets/img
folder, then just do:
<img src="./assets/img/clear.gif" />
<img src="/assets/img/clear.gif" /> // in some case without dot ./
Since the OP was asking for using a custom compare function (and this is what led me to this question as well), I want to give a solid answer here:
Generally, you want to use the built-in sorted()
function which takes a custom comparator as its parameter. We need to pay attention to the fact that in Python 3 the parameter name and semantics have changed.
When providing a custom comparator, it should generally return an integer/float value that follows the following pattern (as with most other programming languages and frameworks):
< 0
) when the left item should be sorted before the right item> 0
) when the left item should be sorted after the right item0
when both the left and the right item have the same weight and should be ordered "equally" without precedenceIn the particular case of the OP's question, the following custom compare function can be used:
def compare(item1, item2):
return fitness(item1) - fitness(item2)
Using the minus operation is a nifty trick because it yields to positive values when the weight of left item1
is bigger than the weight of the right item2
. Hence item1
will be sorted after item2
.
If you want to reverse the sort order, simply reverse the subtraction: return fitness(item2) - fitness(item1)
sorted(mylist, cmp=compare)
or:
sorted(mylist, cmp=lambda item1, item2: fitness(item1) - fitness(item2))
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(compare))
or:
from functools import cmp_to_key
sorted(mylist, key=cmp_to_key(lambda item1, item2: fitness(item1) - fitness(item2)))
Using simple html,
<div>
<object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
</object>
</div>
Or jquery,
<script>
$("#mydiv")
.html('<object data="http://your-website-domain"/>');
</script>
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
JSDB, available for Linux, Windows, and Mac should fit the bill pretty well. It uses Mozilla's Spidermonkey Javascript engine and seems to be less of a hassle to install compared to node.js (at least last time I tried node.js a couple of years ago).
I found JSDB from this interesting list of Javascript shells: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Shells
The Random
class of Java located in the java.util
package will serve your purpose better. It has some nextInt()
methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.
It is not a valid answer as it gives following error
Cannot find table 0.
Use the following statement instead
if (ds.Tables.Count == 0)
{
//DataSet is empty
}
Or, if you are doing a split - join:
GROUP_CONCAT(split(thing, " "), '----') AS thing_name,
You may want to inclue WITHIN RECORD
, like this:
GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,
from BigQuery API page
The response is a bit late - but in case anyone has the issue in the future...
From the screenshot above - it seems that you are adding the url data (username, password, grant_type) to the header and not to the body element.
Clicking on the body tab, and then select "x-www-form-urlencoded" radio button, there should be a key-value list below that where you can enter the request data
Use StringIO
to turn the read string into a file-like object:
from StringIO import StringIO
import urllib
Image.open(StringIO(urllib.requests.urlopen(url).read()))
My implementation
import $ from 'jquery';
$(document).ready(() => {
$('#whatDescribesYouSelectInput').on('change', (e) => {
if (e.target.value === 'Other') {
$('#whatDescribesYouOtherInput').attr('type', 'text');
$('#specifyLabel').show();
} else {
$('#whatDescribesYouOtherInput').attr('type', 'hidden');
$('#specifyLabel').hide();
}
});
});
The solution from Xavier Ho of doubling the width of the stroke and changing the paint-order is brilliant, although only works if the fill is a solid color, with no transparency.
I have developed other approach, more complicated but works for any fill. It also works in ellipses or paths (with the later there are some corner cases with strange behaviour, for example open paths that crosses theirselves, but not much).
The trick is to display the shape in two layers. One without stroke (only fill), and another one only with stroke at double width (transparent fill) and passed through a mask that shows the whole shape, but hides the original shape without stroke.
<svg width="240" height="240" viewBox="0 0 1024 1024">
<defs>
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
<mask id="mask">
<use xlink:href="#ld" stroke="#FFFFFF" stroke-width="160" fill="#FFFFFF"/>
<use xlink:href="#ld" fill="#000000"/>
</mask>
</defs>
<g>
<use xlink:href="#ld" fill="#00D2B8"/>
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="red" mask="url(#mask)"/>
</g>
</svg>
I ran in this problem with OpenVPN working as well and I've found a solution where you should NOT stop/start OpenVPN server.
Idea that You should specify what exactly subnet you want to use. In docker-compose.yml
write:
networks:
default:
driver: bridge
ipam:
config:
- subnet: 172.16.57.0/24
That's it. Now, default
network will be used and if your VPN did not assign you something from 172.16.57.*
subnet, you're fine.
Based on @givanse's answer, this is how you could do it with classes
:
class Swipe {
constructor(element) {
this.xDown = null;
this.yDown = null;
this.element = typeof(element) === 'string' ? document.querySelector(element) : element;
this.element.addEventListener('touchstart', function(evt) {
this.xDown = evt.touches[0].clientX;
this.yDown = evt.touches[0].clientY;
}.bind(this), false);
}
onLeft(callback) {
this.onLeft = callback;
return this;
}
onRight(callback) {
this.onRight = callback;
return this;
}
onUp(callback) {
this.onUp = callback;
return this;
}
onDown(callback) {
this.onDown = callback;
return this;
}
handleTouchMove(evt) {
if ( ! this.xDown || ! this.yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
this.xDiff = this.xDown - xUp;
this.yDiff = this.yDown - yUp;
if ( Math.abs( this.xDiff ) > Math.abs( this.yDiff ) ) { // Most significant.
if ( this.xDiff > 0 ) {
this.onLeft();
} else {
this.onRight();
}
} else {
if ( this.yDiff > 0 ) {
this.onUp();
} else {
this.onDown();
}
}
// Reset values.
this.xDown = null;
this.yDown = null;
}
run() {
this.element.addEventListener('touchmove', function(evt) {
this.handleTouchMove(evt).bind(this);
}.bind(this), false);
}
}
You can than use it like this:
// Use class to get element by string.
var swiper = new Swipe('#my-element');
swiper.onLeft(function() { alert('You swiped left.') });
swiper.run();
// Get the element yourself.
var swiper = new Swipe(document.getElementById('#my-element'));
swiper.onLeft(function() { alert('You swiped left.') });
swiper.run();
// One-liner.
(new Swipe('#my-element')).onLeft(function() { alert('You swiped left.') }).run();
Your activity must have
public void insertIntoDb(View v) {
...
}
not Fragment .
If you don't want the above in activity. initialize button in fragment and set listener to the same.
<Button
android:id="@+id/btn_conferma" // + missing
Then
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rssitem_detail,
container, false);
Button button = (Button) view.findViewById(R.id.btn_conferma);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// do something
}
});
return view;
}
Use:
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
// Create a couple of columns
model.addColumn("Col1");
model.addColumn("Col2");
// Append a row
model.addRow(new Object[]{"v1", "v2"});
Mine was Web Module 3.0
in web.xml
, but in properties>Dynamic Web Module
It was on 3.1
I changed the web.xml
to this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
after this change, do: right click on project>Maven>Update Project...
You can safely delete the table manually or using query. It will be recreated automatically.
DROP TABLE DATABASECHANGELOGLOCK;
Try looking at decode string encoded in utf-8 format in android but it doesn't look like your string is encoded with anything particular. What do you think the output should be?
Tim Bray presented a concise step-by-step, stating that openConnection() does not establish an actual connection. Rather, an actual HTTP connection is not established until you call methods such as getInputStream() or getOutputStream().
http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection
just to add a detail to what Tamlyn wrote,
instead of
$('form').get(0).setAttribute('action', 'baz'); //this works
$('form')[0].setAttribute('action', 'baz');
works equally well
[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'
foreach ($bename in $xmlfile.xml.Section.BEName) {
if($bename.Status -eq 1){
#Do something
}
}
If you don't give an aspect
argument to imshow
, it will use the value for image.aspect
in your matplotlibrc
. The default for this value in a new matplotlibrc
is equal
.
So imshow
will plot your array with equal aspect ratio.
If you don't need an equal aspect you can set aspect
to auto
imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')
which gives the following figure
If you want an equal aspect ratio you have to adapt your figsize
according to the aspect
fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()
which gives you:
Deleting Android Shared Preferences in one line :-)
context.getSharedPreferences("YOUR_PREFS", 0).edit().clear().commit();
Or apply
for non-blocking asynchronous operation:
this.getSharedPreferences("YOUR_PREFS", 0).edit().clear().apply();
As others have suggested, AirPlay mirroring is the way to go. To mirror directly to your computer use an AirPlay server like http://www.airserverapp.com/. Then, since it's showing up directly on your computer you can capture it using the built-in Quicktime app (File > New Screen Recording). Works great!
Another way to do this, if you have pgAdmin and are comfortable using the GUI is to go the table in the schema and right click on the table you wish to import the file to and select "Import" browse your computer for the file, select the type your file is, the columns you want the data to be imputed into, and then select import.
That was done using pgAdmin III and the 9.4 version of PostgreSQL
Note : a nice easy alternative to using the inbuilt "Visual Studio Development Server" or IIS Express (e.g. because you are developing against IIS and have particular settings you need for proper functioning of your app) is to simply stay running run in IIS (I use the Custom Web Server + hosts file entry + IIS binding to same domain)
Your breakpoint should be hit nicely, and you can continue to debug in your natural IIS habitat. Great !
Yes, they both form the primary key. Especially in tables where you don't have a surrogate key, it may be necessary to specify multiple attributes as the unique identifier for each record (bad example: a table with both a first name and last name might require the combination of them to be unique).
I got one good solution. Here I have attached it as the image below. So try it. It may be helpful to you...!
List<string> L = new List<string> ( new string[10] );
Have you tried the arrange > auto arrange function in MySQL Workbench. It may save you from manually moving the tables around.
Basically, the third parameter in loggedIn
should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber
or something.
If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.
HTML:
<body>
<div id="content">...</div>
</body>
CSS:
#content {
max-width: 1000px;
margin: auto;
left: 1%;
right: 1%;
position: absolute;
}
JavaScript (using jQuery):
$(function() {
$(window).on('resize', function resize() {
$(window).off('resize', resize);
setTimeout(function () {
var content = $('#content');
var top = (window.innerHeight - content.height()) / 2;
content.css('top', Math.max(0, top) + 'px');
$(window).on('resize', resize);
}, 50);
}).resize();
});
You can add a multi-line label with the following:
JLabel label = new JLabel("My label");
label.setText("<html>This is a<br>multline label!<br> Try it yourself!</html>");
From here, simply add the label to the frame using the add() method, and you're all set!
Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is
var setActive = 'true';
setActive = setActive == "true";
if(setActive)
// statements
else
// statements.
The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)
You can send an OPTIONS request with curl like this:
curl -i -X OPTIONS http://example.org/path
You may also use -v
instead of -i
to see more output.
To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:
curl -i --request-target "*" -X OPTIONS http://example.org
It's much simpler to run the task on the thread pool, rather than trying to trick the scheduler to run it synchronously. That way you can be sure that it won't deadlock. Performance is affected because of the context switch.
Task<MyResult> DoSomethingAsync() { ... }
// Starts the asynchronous task on a thread-pool thread.
// Returns a proxy to the original task.
Task<MyResult> task = Task.Run(() => DoSomethingAsync());
// Will block until the task is completed...
MyResult result = task.Result;
Even if modern browsers support WebSockets now, I think there is no need to throw SocketIO away and it still has its place in any nowadays project. It's easy to understand, and personally, I learned how WebSockets work thanks to SocketIO.
As said in this topic, there's a plenty of integration libraries for Angular, React, etc. and definition types for TypeScript and other programming languages.
The other point I would add to the differences between Socket.io and WebSockets is that clustering with Socket.io is not a big deal. Socket.io offers Adapters that can be used to link it with Redis to enhance scalability. You have ioredis and socket.io-redis for example.
Yes I know, SocketCluster exists, but that's off-topic.
I'll throw mine in the mix:
https://gist.github.com/btm1/6802312
this evaluates the if statement once and adds no watch listener BUT you can add an additional attribute to the element that has the set-if called wait-for="somedata.prop" and it will wait for that data or property to be set before evaluating the if statement once. that additional attribute can be very handy if you're waiting for data from an XHR request.
angular.module('setIf',[]).directive('setIf',function () {
return {
transclude: 'element',
priority: 1000,
terminal: true,
restrict: 'A',
compile: function (element, attr, linker) {
return function (scope, iterStartElement, attr) {
if(attr.waitFor) {
var wait = scope.$watch(attr.waitFor,function(nv,ov){
if(nv) {
build();
wait();
}
});
} else {
build();
}
function build() {
iterStartElement[0].doNotMove = true;
var expression = attr.setIf;
var value = scope.$eval(expression);
if (value) {
linker(scope, function (clone) {
iterStartElement.after(clone);
clone.removeAttr('set-if');
clone.removeAttr('wait-for');
});
}
}
};
}
};
});
If you're looking for a Kafka error, this might because the upgrade of Kafka's version from 1.x to 2.x.
javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... javax.net.ssl.SSLHandshakeException: General SSLEngine problem ... java.security.cert.CertificateException: No name matching *** found
or
[Producer clientId=producer-1] Connection to node -2 failed authentication due to: SSL handshake failed
The default value for ssl.endpoint.identification.algorithm was changed to https, which performs hostname verification (man-in-the-middle attacks are possible otherwise). Set ssl.endpoint.identification.algorithm to an empty string to restore the previous behaviour. Apache Kafka Notable changes in 2.0.0
Solution: SslConfigs.SSL_ENDPOINT_IDENTIFICATION_ALGORITHM_CONFIG, ""
I had to merge some of those good answers here! This works for me:
git remote set-url origin 'https://bitbucket.org/teamName/repo.git'
In the end, it will always prompt anyone who wants to pull from it
dmidecode -t 17 | grep Size:
Adding all above values displayed after "Size: " will give exact total physical size of all RAM sticks in server.
I presume you are wanting to check if the array contains a certain value, yes? If so, use the contains
method.
if(Arrays.asList(codes).contains(userCode))
These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.
jQuery.scrollTableBody (GitHub)
As long as you have a table with proper <thead>
, <tbody>
, and (optional) <tfoot>
, all you need to do is this:
$('table').scrollTableBody();
Anything that matches something ending with a --- .*a$
So when you match the regex, negate the condition
or alternatively you can also do .*[^a]$
where [^a]
means anything which is not a
When you populate your fields, you can check for the value:
<input type="radio" name="sex" value="Male" <?php echo ($sex=='Male')?'checked':'' ?>size="17">Male
<input type="radio" name="sex" value="Female" <?php echo ($sex=='Female')?'checked':'' ?> size="17">Female
Assuming that the value you return from your database is in the variable $sex
The checked property will preselect the value that match
In fact technically you can store C++ arrays in a vector, and it makes a lot of sense. Not directly, but by a simple workaround, wrapping in a class, will meet exactly all the requirements of a multidimensional array. As the question is already answered by anon. Some explanations steel needed. STL already provides std::array for these purposes.
Is an unpleasant surprise to fall in the trap of not understanding clearly the difference between arrays and pointers, between multidimensional arrays and arrays of arrays, and so on and so on. Vectors of vectors contains vectors as elements. Each element containing a copy of size, capacity and maybe other things, meanwhile the vector datas for elements will be placed in different random places in memory. But a vector of arrays will contain a contiguous segment of memory with all data, which is identical to multidimensional array. Also there is no good reason to keep the size of each array element while it is known to be the same for all elements.
So, making a vector of array, you can't do it directly. But you can workaround it easily by wrapping the array in a class, and in this sample the memory will be identical to the memory of a bidimensional array. This approach is already widely used by many libraries. At low level it will be easily interoperable with APIs that are not C++ vector aware. So without using std::array it will look like this:
int main()
{
struct ss
{
int a[5];
int& operator[] (const int& i) { return a[i]; }
} a{ 1,2,3,4,5 }, b{ 9,8,7,6,5 };
vector<ss> v;
v.resize(10);
v[0] = a;
v[1] = b;
v.push_back(a); // will push to index 10, with reallocation
v.push_back(b); // will push to index 11, with reallocation
auto d = v.data();
// cin >> v[1][3]; //input any element from stdin
cout << "show two element: "<< v[1][2] <<":"<< v[1][3] << endl;
return 0;
}
Since C++11 STL contains std::array for these purposes, so no need to reinvent it:
....
#include<array>
....
int main()
{
vector<array<int, 5>> v;
v.reserve(10);
v.resize(2);
v[0] = array<int, 5> {1, 2, 3, 4, 5};
v[1] = array<int, 5> {9, 8, 7, 6, 5};
v.emplace_back(array<int, 5>{ 7, 2, 53, 4, 5 });
///cin >> v[1][1];
auto d = v.data();
Now look how looks in memory
Now, this is why vectors of vectors is not the answer. Supposing following code
int main()
{
vector<vector<int>> vv = { { 1,2,3,4,5 }, { 9,8,7,6,5 } };
auto dd = vv.data();
return 0;
}
Guess what it looks like in the memory now
You're correct that the .swp
file is used by vim for locking and as a recovery file.
Try putting set nobackup
in your vimrc if you don't want these files. See the Vim docs for various backup related options if you want the whole scoop, or want to have .bak files instead...
Just check tsnnames.ora and listener.ora files. It should not have localhost as a server. change it to hostname.
Like in tnsnames.ora
LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
Replace localhost by hostname.
Look at the r.status_code
attribute:
if r.status_code == 404:
# A 404 was issued.
Demo:
>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404
If you want requests
to raise an exception for error codes (4xx or 5xx), call r.raise_for_status()
:
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "requests/models.py", line 664, in raise_for_status
raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.
You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:
if r:
# successful response
If you want to be more explicit, use if r.ok:
.
You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html()
call will not serialize the event.
You can also upload using HTML5. You can use this AJAX uploader.
The JS code is basically:
$scope.doPhotoUpload = function () {
// ..
var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
myUploader.send();
// ..
}
Which reads from an HTML input element
<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">
i find it work, :)
As Quoted by mattjames
The use of a Statement in JDBC should be 100% localized to being used for DDL (ALTER, CREATE, GRANT, etc) as these are the only statement types that cannot accept BIND VARIABLES. PreparedStatements or CallableStatements should be used for EVERY OTHER type of statement (DML, Queries). As these are the statement types that accept bind variables.
This is a fact, a rule, a law -- use prepared statements EVERYWHERE. Use STATEMENTS almost no where.
Clearing application data helped me in this. It may help you..
https://dev.mysql.com/doc/refman/8.0/en/lock-tables.html
The correct way to use LOCK TABLES and UNLOCK TABLES with transactional tables, such as InnoDB tables, is to begin a transaction with SET autocommit = 0 (not START TRANSACTION) followed by LOCK TABLES, and to not call UNLOCK TABLES until you commit the transaction explicitly. For example, if you need to write to table t1 and read from table t2, you can do this:
SET autocommit=0;
LOCK TABLES t1 WRITE, t2 READ, ...;... do something with tables t1 and t2 here ...
COMMIT;
UNLOCK TABLES;
The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.
d = Date.now();_x000D_
d = new Date(d);_x000D_
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");_x000D_
_x000D_
console.log(d);
_x000D_
as answer of @thomasrutter
If you previously issued a 301 redirect but want to un-do that
If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:
The simplest and best solution is to issue another 301 redirect back again.
The browser will realise it is being directed back to what it previously thought was a decommissioned URL, and this should cause it re-fetch that URL again to confirm that the old redirect isn't still there.
If you don't have control over the site where the previous redirect target went to, then you are outta luck. Try and beg the site owner to redirect back to you.
In fact, this means:
a.com 301 to b.com
delete a.com 's 301
add b.com 301 to a.com
Then it works.
I think you set the marquee width related to 5 images total width. It works fine
ex: <marquee style="width:700px"></marquee>
There is no need to use AS
, just use:
SELECT table1.price Table1 Price, table2.price Table2 Price, .....
It's as easy as the following:
info_1 = "one piece of info"
info_2 = "another piece"
vars = (info_1, info_2)
# 'vars' is now a tuple with the values ("info_1", "info_2")
However, tuples in Python are immutable, so you cannot append variables to a tuple once it is created.
Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Also, consider to use a repository manager such as Nexus and configure all your repositories there.
For python 3.7:
Change directory, if you didn't add the following as your PATH: cd C:\Users{user_name}\AppData\Local\Programs\Python\Python37-32\Scripts To know where your package/application has been installed/located, type: "where program_name" like> where jupyter If you didn't find a location, you need to add the location in PATH.
Type: pip-autoremove jupyter It will ask to type y/n to confirm the action.
It can be done, I found it elsewhere on the web...this is no way my work ! :)
Option Explicit
' Import
Private Declare Function GetCurrentThreadId Lib "kernel32" () As Long
Private Declare Function SetDlgItemText Lib "user32" _
Alias "SetDlgItemTextA" _
(ByVal hDlg As Long, _
ByVal nIDDlgItem As Long, _
ByVal lpString As String) As Long
Private Declare Function SetWindowsHookEx Lib "user32" _
Alias "SetWindowsHookExA" _
(ByVal idHook As Long, _
ByVal lpfn As Long, _
ByVal hmod As Long, _
ByVal dwThreadId As Long) As Long
Private Declare Function UnhookWindowsHookEx Lib "user32" _
(ByVal hHook As Long) As Long
' Handle to the Hook procedure
Private hHook As Long
' Hook type
Private Const WH_CBT = 5
Private Const HCBT_ACTIVATE = 5
' Constants
Public Const IDOK = 1
Public Const IDCANCEL = 2
Public Const IDABORT = 3
Public Const IDRETRY = 4
Public Const IDIGNORE = 5
Public Const IDYES = 6
Public Const IDNO = 7
Public Sub MsgBoxSmile()
' Set Hook
hHook = SetWindowsHookEx(WH_CBT, _
AddressOf MsgBoxHookProc, _
0, _
GetCurrentThreadId)
' Run MessageBox
MsgBox "Smiling Message Box", vbYesNo, "Message Box Hooking"
End Sub
Private Function MsgBoxHookProc(ByVal lMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
If lMsg = HCBT_ACTIVATE Then
SetDlgItemText wParam, IDYES, "Yes :-)"
SetDlgItemText wParam, IDNO, "No :-("
' Release the Hook
UnhookWindowsHookEx hHook
End If
MsgBoxHookProc = False
End Function
I need more information really but it will be along the lines of..
SELECT table1.*, table2.col1, table2.col3 FROM table1 JOIN table2 USING(id)
Cast bare integer to decimal:
select cast(9 as decimal(4,2)); //prints 9.00
Cast Integers 8/5 to decimal:
select cast(8/5 as decimal(11,4)); //prints 1.6000
Cast string to decimal:
select cast(".885" as decimal(11,3)); //prints 0.885
Cast two int variables into a decimal
mysql> select 5 into @myvar1;
Query OK, 1 row affected (0.00 sec)
mysql> select 8 into @myvar2;
Query OK, 1 row affected (0.00 sec)
mysql> select @myvar1/@myvar2; //prints 0.6250
Cast decimal back to string:
select cast(1.552 as char(10)); //shows "1.552"
important: in this kind of error you should look for simple mistakes in most cases
besides syntax error, I should say once I had same problem and it was because of bad name I have chosen for function. I have never searched for the reason but I remember that I copied another function and change it to use. I add "1" after the name to changed the function name and I got this error.
Once you have your PropertyInfo
(from GetProperty
), you need to call GetValue
and pass in the instance that you want to get the value from. In your case:
d.GetType().GetProperty("value2").GetValue(d, null);
Assuming the parent has a fixed width, e.g #page { width: 1000px; }
and is centered #page { margin: auto; }
, you want the child to fit the width of browser viewport you could simply do:
#page {
margin: auto;
width: 1000px;
}
.fullwidth {
margin-left: calc(500px - 50vw); /* 500px is half of the parent's 1000px */
width: 100vw;
}
It seems a lot of people get confused by the way objects are passed to functions and what passing by reference means. Object are still passed by value, it's just the value that is passed in PHP5 is a reference handle. As proof:
<?php
class Holder {
private $value;
public function __construct($value) {
$this->value = $value;
}
public function getValue() {
return $this->value;
}
}
function swap($x, $y) {
$tmp = $x;
$x = $y;
$y = $tmp;
}
$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);
echo $a->getValue() . ", " . $b->getValue() . "\n";
Outputs:
a, b
To pass by reference means we can modify the variables that are seen by the caller, which clearly the code above does not do. We need to change the swap function to:
<?php
function swap(&$x, &$y) {
$tmp = $x;
$x = $y;
$y = $tmp;
}
$a = new Holder('a');
$b = new Holder('b');
swap($a, $b);
echo $a->getValue() . ", " . $b->getValue() . "\n";
Outputs:
b, a
in order to pass by reference.
You can use a HTML table:
<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>
This works for me:
function refresh() {
setTimeout(function () {
location.reload()
}, 100);
}
There are many way to do the string aggregation, but the easiest is a user defined function. Try this for a way that does not require a function. As a note, there is no simple way without the function.
This is the shortest route without a custom function: (it uses the ROW_NUMBER() and SYS_CONNECT_BY_PATH functions )
SELECT questionid,
LTRIM(MAX(SYS_CONNECT_BY_PATH(elementid,','))
KEEP (DENSE_RANK LAST ORDER BY curr),',') AS elements
FROM (SELECT questionid,
elementid,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) AS curr,
ROW_NUMBER() OVER (PARTITION BY questionid ORDER BY elementid) -1 AS prev
FROM emp)
GROUP BY questionid
CONNECT BY prev = PRIOR curr AND questionid = PRIOR questionid
START WITH curr = 1;
The first element of the sites
array is an array, as you can see indenting the JSON:
{"units":[{"id":42,
...
"sites":
[
[
{
"id":316,
"article":42,
"clip":133904
}
],
{"length":5}
]
...
}
Therefore you need to treat its value accordingly; probably you could do something like:
JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
require 'csv'
csv_text = File.read('...')
csv = CSV.parse(csv_text, :headers => true)
csv.each do |row|
Moulding.create!(row.to_hash)
end
Simply, you could use or refer to guava lib provided by google, which offers utiliy methods for conversion between long and byte array. My client code:
long content = 212000607777l;
byte[] numberByte = Longs.toByteArray(content);
logger.info(Longs.fromByteArray(numberByte));
s = "BINGO"
print(s.replace("", " ")[1: -1])
Timings below
$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]'
1000000 loops, best of 3: 0.584 usec per loop
$ python -m timeit -s's = "BINGO"' '" ".join(s)'
100000 loops, best of 3: 1.54 usec per loop
static void Main(string[] args)
{ int i,j;
Console.WriteLine("prime no between 1 to 100");
for (i = 2; i <= 100; i++)
{
int count = 0;
for (j = 1; j <= i; j++)
{
if (i % j == 0)
{ count=count+1; }
}
if ( count <= 2)
{ Console.WriteLine(i); }
}
Console.ReadKey();
}
It's simple as:
$('#action').val("1");
#action
is hidden input field id.
As per latest Ansible Version 2.5, to check if a variable is defined and depending upon this if you want to run any task, use undefined
keyword.
tasks:
- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
when: foo is defined
- fail: msg="Bailing out. this play requires 'bar'"
when: bar is undefined
Take a look at archive.org
You can find almost everything about the past of a website there.
For just reading the last element of a slice:
sl[len(sl)-1]
For removing it:
sl = sl[:len(sl)-1]
See this page about slice tricks
In C++/CLI, a handle is a pointer to an object located on the GC heap. Creating an object on the (unmanaged) C++ heap is achieved using new
and the result of a new
expression is a "normal" pointer. A managed object is allocated on the GC (managed) heap with a gcnew
expression. The result will be a handle. You can't do pointer arithmetic on handles. You don't free handles. The GC will take care of them. Also, the GC is free to relocate objects on the managed heap and update the handles to point to the new locations while the program is running.
In JQuery:
$("#id option:selected").prop("selected", false);
$("#id").multiselect('refresh');
Try this :
<script type="text/javascript">
function clearThis(target){
if(target.value == "[email protected]")
{
target.value= "";
}
}
</script>
As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.
( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -
Replace backup.ab with the path to your file.
As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.
This function is only available at Python start-up time, when Python scans the environment. It has to be called in a system-wide module, sitecustomize.py
, After this module has been evaluated, the setdefaultencoding()
function is removed from the sys
module.
The only way to actually use it is with a reload hack that brings the attribute back.
Also, the use of sys.setdefaultencoding()
has always been discouraged, and it has become a no-op in py3k. The encoding of py3k is hard-wired to "utf-8" and changing it raises an error.
I suggest some pointers for reading:
Try This:
<img class="img-responsive" src="assets/img/google-body-ads.png">
Assuming you're passing in strings rather than integers, try casting the arguments to integers:
def example(arg1, arg2, arg3):
if int(arg1) == 1 and int(arg2) == 2 and int(arg3) == 3:
print("Example Text")
(Edited to emphasize I'm not asking for clarification; I was trying to be diplomatic in my answer. )
Don't know who looks at your file, but if you open it in wordpad instead of notepad, the linebreaks will show correct. In case you're using a special file extension, associate it with wordpad and you're done with it. Or use any other more advanced text editor.
public List<Student> findStudentByReports(Date startDate, Date endDate) {
System.out.println("call findStudentMethd******************with this pattern"
+ startDate
+ endDate
+ "*********************************************");
return em
.createQuery(
"' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
+ "'")
.setParameter("startDate", startDate, TemporalType.DATE)
.setParameter("endDate", endDate, TemporalType.DATE)
.getResultList();
}
group by default order by pk id,so the result
username point avg_time
demo123 100 90 ---> id = 4
demo123456 100 100 ---> id = 7
demo 90 120 ---> id = 1
Another alternative is dotnetprojects SVGImage
This allows native use of .svg files directly in xaml.
The nice part is, it is only one assembly which is about 100k. In comparision to sharpvectors which is much bigger any many files.
Usage:
...
xmlns:svg1="clr-namespace:SVGImage.SVG;assembly=DotNetProjects.SVGImage"
...
<svg1:SVGImage Name="mySVGImage" Source="/MyDemoApp;component/Resources/MyImage.svg"/>
...
That's all.
See:
@Column
is not the appropriate annotation. You don't want to store a whole User or Question in a column. You want to create an association between the entities. Start by renaming Questions
to Question
, since an instance represents a single question, and not several ones. Then create the association:
@Entity
@Table(name = "UserAnswer")
public class UserAnswer {
// this entity needs an ID:
@Id
@Column(name="useranswer_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "question_id")
private Question question;
@Column(name = "response")
private String response;
//getter and setter
}
The Hibernate documentation explains that. Read it. And also read the javadoc of the annotations.
See demo here you need to introduce an additiona calss for second div
.overlap{
top: -30px;
position: relative;
left: 30px;
}
PHP HAS multithreading, its just not enabled by default, there is an extension called pthreads which does exactly that. You'll need php compiled with ZTS though. (Thread Safe) Links:
Simple example for compareAndSet() function:
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val = new AtomicInteger(0);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// Checks if previous value was 0
// and then updates it
boolean res = val.compareAndSet(0, 6);
// Checks if the value was updated.
if (res)
System.out.println("The value was"
+ " updated and it is "
+ val);
else
System.out.println("The value was "
+ "not updated");
}
}
The printed is: previous value: 0 The value was updated and it is 6 Another simple example:
import java.util.concurrent.atomic.AtomicInteger;
public class GFG {
public static void main(String args[])
{
// Initially value as 0
AtomicInteger val
= new AtomicInteger(0);
// Prints the updated value
System.out.println("Previous value: "
+ val);
// Checks if previous value was 0
// and then updates it
boolean res = val.compareAndSet(10, 6);
// Checks if the value was updated.
if (res)
System.out.println("The value was"
+ " updated and it is "
+ val);
else
System.out.println("The value was "
+ "not updated");
}
}
The printed is: Previous value: 0 The value was not updated
Why not take the approach that GMail uses and show the number of messages in the page title?
Sometimes users don't want to be distracted when a new message arrives.
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
The strpos()
finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.
$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
If you also want to check if the underscore character (_
) exists in your string before trying to get it, you can use the following:
if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
You can use @@trancount
in MSSQL
From the documentation:
Returns the number of BEGIN TRANSACTION statements that have occurred on the current connection.
I was facing the same problem for several days, and finally the issue isn't with the code, the problem commes from maven, you must delete all the files that he downloaded from your hard drive "C:\Users\username.m2\repository", and do another update maven for your project, that will fix your problem.
You should add the resources in a library project as per http://developer.android.com/tools/support-library/setup.html
Section > Adding libraries with resources
You then add the android-support-v7-appcompat
library in your workspace and then add it as a reference to your app project.
Defining all the resources in your app project will also work (but there are a lot of definitions to add and you have missed some of them), and it is not the recommended approach.
run npm install jquery --save
then on your root component, place this
global.jQuery = require('../node_modules/jquery/dist/jquery.js');
var $ = global.jQuery;
Do not forget to export it to enable you to use it with other components
export default {
name: 'App',
components: {$}
}
You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.
More accurately anything that is not 0
is true.
So 1
is true, but so is 2
, 3
... etc.
Add:
using System.Linq;
to the top of your file.
And then:
Car[] carList = ...
var carMake =
from item in carList
where item.Model == "bmw"
select item.Make;
or if you prefer the fluent syntax:
var carMake = carList
.Where(item => item.Model == "bmw")
.Select(item => item.Make);
Things to pay attention to:
item.Make
in the select
clause instead if s.Make
as in your code.item
and .Model
in your where
clausebrew info mysql
mysql: stable 5.6.12 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.12 (9363 files, 353M) *
Poured from bottle
From: https://github.com/mxcl/homebrew/commits/master/Library/Formula/mysql.rb
==> Dependencies
Build: cmake
==> Options
--enable-debug
Build with debug support
--enable-local-infile
Build with local infile loading support
--enable-memcached
Enable innodb-memcached support
--universal
Build a universal binary
--with-archive-storage-engine
Compile with the ARCHIVE storage engine enabled
--with-blackhole-storage-engine
Compile with the BLACKHOLE storage engine enabled
--with-embedded
Build the embedded server
--with-libedit
Compile with editline wrapper instead of readline
--with-tests
Build with unit tests
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
To connect:
mysql -uroot
To reload mysql after an upgrade:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
mysql.service start
. ERROR! The server quit without updating PID file (/var/run/mysqld/mysqld.pid).
or mysql -u root
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
I'm looking for a solution for some time but I can not solve my problem. I tried several solutions in stackoverflow.com but no this helping me.
Place this css in your page:
<style>
#client_logos {
display: inline-block;
width:100%;
}
</style>
Replace
<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>
To
<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>
I was having difficulty maintaining keyboard state when changing orientation of fragments within a viewpager. I'm not sure why, but it just seems to be wonky and acts differently from a standard Activity.
To maintain keyboard state in this case, first you should add android:windowSoftInputMode = "stateUnchanged"
to your AndroidManifest.xml
. You may notice, though, that this doesn't actually solve the entire problem -- the keyboard didn't open for me if it was previously opened before orientation change. In all other cases, the behavior seemed to be correct.
Then, we need to implement one of the solutions mentioned here. The cleanest one I found was George Maisuradze's--use the boolean callback from hideSoftInputFromWindow:
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
return imm.hideSoftInputFromWindow(mViewPager.getWindowToken(), 0);
I stored this value in my Fragment's onSaveInstanceState
method and retrieved it onCreate
. Then, I forcibly showed the keyboard in onCreateView
if it had a value of true
(it returns true if the keyboard is visible before actually hiding it prior to the Fragment destruction).
You can use php built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change filed name as your requirement
then the result is
and if you want to concat same filed using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
ExecuteScalar()
is what you need here
You just have to replace the break
with a return
statement.
Think of the code inside the Foreach-Object
as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue
, break
, ...).
Use class_=
If you want to find element(s) without stating the HTML tag.
For single element:
soup.find(class_='my-class-name')
For multiple elements:
soup.find_all(class_='my-class-name')
Use onChange={this.handleChange.bind(this, "name")
method and value={this.state.fields["name"]}
on input text field and below that create span element to show error, see the below example.
export default class Form extends Component {
constructor(){
super()
this.state ={
fields: {
name:'',
email: '',
message: ''
},
errors: {},
disabled : false
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if(!fields["name"]){
formIsValid = false;
errors["name"] = "Name field cannot be empty";
}
if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
if(!fields["name"].match(/^[a-zA-Z]+$/)){
formIsValid = false;
errors["name"] = "Only letters";
}
}
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Email field cannot be empty";
}
if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
if(!fields["message"]){
formIsValid = false;
errors["message"] = " Message field cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
handleSubmit(e){
e.preventDefault();
if(this.handleValidation()){
console.log('validation successful')
}else{
console.log('validation failed')
}
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="row">
<div className="col-25">
<label htmlFor="name">Name</label>
</div>
<div className="col-75">
<input type="text" placeholder="Enter Name" refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="exampleInputEmail1">Email address</label>
</div>
<div className="col-75">
<input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
<span style={{color: "red"}}>{this.state.errors["email"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="message">Message</label>
</div>
<div className="col-75">
<textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
<span style={{color: "red"}}>{this.state.errors["message"]}</span>
</div>
</div>
<div className="row">
<button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
</div>
</form>
)
}
}
Using ES6, this can be done quite nicely using .reduce()
with a Map
as the accumulator, and then using Array.from()
with its mapping function to map each grouped map-entry to an object:
const arr = [{"group":"one","color":"red"},{"group":"two","color":"blue"},{"group":"one","color":"green"},{"group":"one","color":"black"}];
const res = Array.from(arr.reduce((m, {group, color}) =>
m.set(group, [...(m.get(group) || []), color]), new Map
), ([group, color]) => ({group, color})
);
console.log(res);
_x000D_
If you have additional properties in your objects other than just group
and color
, you can take a more general approach by setting a grouped object as the map's values like so:
const arr = [{"group":"one","color":"red"},{"group":"two","color":"blue"},{"group":"one","color":"green"},{"group":"one","color":"black"}];
const groupAndMerge = (arr, groupBy, mergeInto) =>
Array.from(arr.reduce((m, o) => {
const curr = m.get(o[groupBy]);
return m.set(o[groupBy], {...o, [mergeInto]: [...(curr && curr[mergeInto] || []), o[mergeInto]]});
}, new Map).values());
console.log(groupAndMerge(arr, 'group', 'color'));
_x000D_
If you can support optional chaining and the nullish coalescing operator (??), you can simplify the above method to the following:
const arr = [{"group":"one","color":"red"},{"group":"two","color":"blue"},{"group":"one","color":"green"},{"group":"one","color":"black"}];
const groupAndMerge = (arr, groupBy, mergeWith) =>
Array.from(arr.reduce((m, o) => m.set(o[groupBy], {...o, [mergeWith]: [...(m.get(o[groupBy])?.[mergeWith] ?? []), o[mergeWith]]}), new Map).values());
console.log(groupAndMerge(arr, 'group', 'color'));
_x000D_
In Oracle, you could do this:
create table D (
ID numeric(1),
CODE varchar(2),
constraint PK_D primary key (ID, CODE)
);
The default class constructor is called unless you explicitly call another constructor in the derived class. the language specifies this.
Rectangle(int h,int w):
Shape(h,w)
{...}
Will call the other base class constructor.
There is a way with struct namespace.
The benefit is all enum variables are under a specific namespace to avoid pollution.
The issue is that we could only use var
not const
type OrderStatusType string
var OrderStatus = struct {
APPROVED OrderStatusType
APPROVAL_PENDING OrderStatusType
REJECTED OrderStatusType
REVISION_PENDING OrderStatusType
}{
APPROVED: "approved",
APPROVAL_PENDING: "approval pending",
REJECTED: "rejected",
REVISION_PENDING: "revision pending",
}
Try following these steps:
Building off of Alberto, I added the rollup.
SELECT [Narrative] = CASE
WHEN [Narrative] IS NULL THEN 'count_total' ELSE [Narrative] END
,[Count]=SUM([Count]) FROM (SELECT COUNT(*) [Count], 'count_nulls' AS [Narrative]
FROM [CrmDW].[CRM].[User]
WHERE [EmployeeID] IS NULL
UNION
SELECT COUNT(*), 'count_not_nulls ' AS narrative
FROM [CrmDW].[CRM].[User]
WHERE [EmployeeID] IS NOT NULL) S
GROUP BY [Narrative] WITH CUBE;
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
What I needed: A document number with a fixed number of integers that would also act like an AutoField
.
My searches took me all over incl. this page.
Finally I did something like this:
I created a table with a DocuNumber
field as an IntegerField with foll. attributes:
max_length=6
primary_key=True
unique=True
default=100000
The max_length
value anything as required (and thus the corresponding default=
value).
A warning is issued while creating the said model, which I could ignore.
Afterwards, created a document (dummy) whence as expected, the document had an integer field value of 100000.
Afterwards changed the model key field as:
AutoField
max_length
And default
attributesprimary_key = True
attributeThe next (desired document) created had the value as 100001 with subsequent numbers getting incremented by 1.
So far so good.
How do I check if something is (not) in a list in Python?
The cheapest and most readable solution is using the in
operator (or in your specific case, not in
). As mentioned in the documentation,
The operators
in
andnot in
test for membership.x in s
evaluates toTrue
ifx
is a member ofs
, andFalse
otherwise.x not in s
returns the negation ofx in s
.
Additionally,
The operator
not in
is defined to have the inverse true value ofin
.
y not in x
is logically the same as not y in x
.
Here are a few examples:
'a' in [1, 2, 3]
# False
'c' in ['a', 'b', 'c']
# True
'a' not in [1, 2, 3]
# True
'c' not in ['a', 'b', 'c']
# False
This also works with tuples, since tuples are hashable (as a consequence of the fact that they are also immutable):
(1, 2) in [(3, 4), (1, 2)]
# True
If the object on the RHS defines a __contains__()
method, in
will internally call it, as noted in the last paragraph of the Comparisons section of the docs.
...
in
andnot in
, are supported by types that are iterable or implement the__contains__()
method. For example, you could (but shouldn't) do this:
[3, 2, 1].__contains__(1)
# True
in
short-circuits, so if your element is at the start of the list, in
evaluates faster:
lst = list(range(10001))
%timeit 1 in lst
%timeit 10000 in lst # Expected to take longer time.
68.9 ns ± 0.613 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
178 µs ± 5.01 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
If you want to do more than just check whether an item is in a list, there are options:
list.index
can be used to retrieve the index of an item. If that element does not exist, a ValueError
is raised.list.count
can be used if you want to count the occurrences.set
s?Ask yourself these questions:
hash
on them?If you answered "yes" to these questions, you should be using a set
instead. An in
membership test on list
s is O(n) time complexity. This means that python has to do a linear scan of your list, visiting each element and comparing it against the search item. If you're doing this repeatedly, or if the lists are large, this operation will incur an overhead.
set
objects, on the other hand, hash their values for constant time membership check. The check is also done using in
:
1 in {1, 2, 3}
# True
'a' not in {'a', 'b', 'c'}
# False
(1, 2) in {('a', 'c'), (1, 2)}
# True
If you're unfortunate enough that the element you're searching/not searching for is at the end of your list, python will have scanned the list upto the end. This is evident from the timings below:
l = list(range(100001))
s = set(l)
%timeit 100000 in l
%timeit 100000 in s
2.58 ms ± 58.9 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
101 ns ± 9.53 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As a reminder, this is a suitable option as long as the elements you're storing and looking up are hashable. IOW, they would either have to be immutable types, or objects that implement __hash__
.
The u in u'Some String'
means that your string is a Unicode string.
Q: I'm in a terrible, awful hurry and I landed here from Google Search. I'm trying to write this data to a file, I'm getting an error, and I need the dead simplest, probably flawed, solution this second.
A: You should really read Joel's Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) essay on character sets.
Q: sry no time code pls
A: Fine. try str('Some String')
or 'Some String'.encode('ascii', 'ignore')
. But you should really read some of the answers and discussion on Converting a Unicode string and this excellent, excellent, primer on character encoding.
select sysdate from dual
30-MAR-17
select count(1) from masterdata where to_date(inactive_from_date,'DD-MON-YY'
between '01-JAN-16' to '31-DEC-16'
12998 rows
Providing javac
is set up through /etc/alternatives/javac
, you can add to your .bash_profile:
JAVA_HOME=$(l=$(which javac) ; while : ; do nl=$(readlink ${l}) ; [ "$nl" ] || break ; l=$nl ; done ; echo $(cd $(dirname $l)/.. ; pwd) )
export JAVA_HOME
When you need to copy a variable to the clipboard in the Chrome dev console, you can simply use the copy()
command.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#copyobject
Objective-C code for copy Table from a Database to another Database
-(void) createCopyDatabase{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
NSFileManager *fileManager = [NSFileManager defaultManager];
char *error;
if ([fileManager fileExistsAtPath:newdbPath]) {
[fileManager removeItemAtPath:newdbPath error:nil];
}
sqlite3 *database;
//open database
if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
NSLog(@"Error to open database");
}
NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS aDB",maindbPath];
sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to Attach = %s",error);
}
//Query for copy Table
NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM aDB.Info";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
//Query for copy Table with Where Clause
sqlString = @"CREATE TABLE comments AS SELECT * FROM aDB.comments Where user_name = 'XYZ'";
sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
if (error) {
NSLog(@"Error to copy database = %s",error);
}
}
I have a little hack for this one. JSON.parse('false')
will return false
and JSON.parse('true')
will return true. But this doesn't work with JSON.parse(true || false)
. So, if you use something like JSON.parse(your_value.to_s)
it should achieve your goal in a simple but hacky way.
Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.
git push --all
is the canonical way to push everything to a new bare repository.
Another way to do the same thing is to create your new, non-bare repository and then make a bare clone with
git clone --bare
then use
git remote add origin <new-remote-repo>
in the original (non-bare) repository.
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
[Update]
Matt Johnsons answer is much better than this one was.
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
The time_t
value for midnight GMT is always divisible by 86400
(24 * 3600
). The value for seconds-since-midnight GMT is thus time %% 86400
.
The hour in GMT is (time %% 86400) / 3600
and this can be used as the x-axis of the plot:
plot((as.numeric(times) %% 86400)/3600, val)
To adjust for a time zone, adjust the time before taking the modulus, by adding the number of seconds that your time zone is ahead of GMT. For example, US central daylight saving time (CDT) is 5 hours behind GMT. To plot against the time in CDT, the following expression is used:
plot(((as.numeric(times) - 5*3600) %% 86400)/3600, val)
If you're using the compatibility ActionBar from the recent v7 appcompat support package, you can get the height using
@dimen/abc_action_bar_default_height
If you want to add fields to an object dynamically, simplest way to do it is as follows:
var params= [
{key: "k1", value=1},
{key: "k2", value=2},
{key: "k3", value=3}];
for(i=0; i< params.len; i++) {
data[params[i].key] = params[i].value
}
This will create data object which has following fields:
{k1:1, k2:2, k3:3}
Sometimes when the dev process has both WIN work stations and LINUX systems (hosting) and in the code you do not see any output before the related line, it could be the formatting of the file and the lack of Unix LF (linefeed) line ending.
What we usually do in order to quickly fix this, is rename the file and on the LINUX system create a new file instead of the renamed one, and then copy the content into that. Many times this solve the issue as some of the files that were created in WIN once moved to the hosting cause this issue.
This fix is an easy fix for sites we manage by FTP and sometimes can save our new team members some time.
Underscore-java has static method U.formatJson(json)
.
Five format types are supported: 2, 3, 4, tabs and compact. I am the maintainer of the project. Live example
import com.github.underscore.lodash.U;
import static com.github.underscore.lodash.Json.JsonStringBuilder.Step.TABS;
import static com.github.underscore.lodash.Json.JsonStringBuilder.Step.TWO_SPACES;
public class MyClass {
public static void main(String args[]) {
String json = "{\"Price\": {"
+ " \"LineItems\": {"
+ " \"LineItem\": {"
+ " \"UnitOfMeasure\": \"EACH\", \"Quantity\": 2, \"ItemID\": \"ItemID\""
+ " }"
+ " },"
+ " \"Currency\": \"USD\","
+ " \"EnterpriseCode\": \"EnterpriseCode\""
+ "}}";
System.out.println(U.formatJson(json, TWO_SPACES));
System.out.println(U.formatJson(json, TABS));
}
}
Output:
{
"Price": {
"LineItems": {
"LineItem": {
"UnitOfMeasure": "EACH",
"Quantity": 2,
"ItemID": "ItemID"
}
},
"Currency": "USD",
"EnterpriseCode": "EnterpriseCode"
}
}
{
"Price": {
"LineItems": {
"LineItem": {
"UnitOfMeasure": "EACH",
"Quantity": 2,
"ItemID": "ItemID"
}
},
"Currency": "USD",
"EnterpriseCode": "EnterpriseCode"
}
}
I was not able to find any solution for this type of animation using ViewPropertyAnimator.
Here's an example:
Layout:
<FrameLayout
android:id="@+id/child_view_container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/child_view"
android:gravity="center_horizontal"
android:layout_gravity="center_horizontal"
/>
</FrameLayout>
Animate - Right to left and exit view:
final childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.animate()
.translationXBy(-containerView.getWidth())
.setDuration(TRANSLATION_DURATION)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
childView.setVisibility(View.GONE);
}
});
Animate - Right to left enter view:
final View childView = findViewById(R.id.child_view);
View containerView = findViewById(R.id.child_view_container);
childView.setTranslationX(containerView.getWidth());
childView.animate()
.translationXBy(-containerView.getWidth())
.setDuration(TRANSLATION_DURATION)
.setInterpolator(new AccelerateDecelerateInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
childView.setVisibility(View.VISIBLE);
}
});
I've resorted to
df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index
lately. That gets both null and empty-string cells in one go.
If you want to write a loop in Python which prints some integer no etc, then just copy and paste this code, it'll work a lot
# Display Value from 1 TO 3
for i in range(1,4):
print "",i,"value of loop"
# Loop for dictionary data type
mydata = {"Fahim":"Pakistan", "Vedon":"China", "Bill":"USA" }
for user, country in mydata.iteritems():
print user, "belongs to " ,country
I can't get that constructor to work either. This however seems to work:
# $temp = Get-ResourceFiles
$resourceFiles = New-Object System.Collections.ArrayList($null)
$resourceFiles.AddRange($temp)
You can also pass an integer in the constructor to set an initial capacity.
What do you mean when you say you want to enumerate the files? Why can't you just filter the wanted values into a fresh array?
Edit:
It seems that you can use the array constructor like this:
$resourceFiles = New-Object System.Collections.ArrayList(,$someArray)
Note the comma. I believe what is happening is that when you call a .NET method, you always pass parameters as an array. PowerShell unpacks that array and passes it to the method as separate parameters. In this case, we don't want PowerShell to unpack the array; we want to pass the array as a single unit. Now, the comma operator creates arrays. So PowerShell unpacks the array, then we create the array again with the comma operator. I think that is what is going on.
You can mix git blame
and git log
commands to retrieve the summary of each commit in the git blame command and append them. Something like the following bash + awk script. It appends the commit summary as code comment inline.
git blame FILE_NAME | awk -F" " \
'{
commit = substr($0, 0, 8);
if (!a[commit]) {
query = "git log --oneline -n 1 " commit " --";
(query | getline a[commit]);
}
print $0 " // " substr(a[commit], 9);
}'
In one line:
git blame FILE_NAME | awk -F" " '{ commit = substr($0, 0, 8); if (!a[commit]) { query = "git log --oneline -n 1 " commit " --"; (query | getline a[commit]); } print $0 " // " substr(a[commit], 9); }'
Join the table with itself and give it two different aliases (A
and B
in the following example). This allows to compare different rows of the same table.
SELECT DISTINCT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
A.Address <> B.Address
The "less than" comparison <
ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <>
instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A
alias and the B
alias in turn.
The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.
The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to
SELECT A.Id
FROM
Address A
INNER JOIN Address B
ON A.Id = B.Id
WHERE
A.[Adress Code] = 1 AND
B.[Adress Code] = 2 AND
A.Address <> B.Address
I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .
Here is your string XOR'er, presumably for some mild form of encryption:
>>> src = "Hello, World!"
>>> code = "secret"
>>> xorWord = lambda ss,cc: ''.join(chr(ord(s)^ord(c)) for s,c in zip(ss,cc*100))
>>> encrypt = xorWord(src, code)
>>> encrypt
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'
>>> decrypt = xorWord(encrypt,code)
>>> print decrypt
Hello, World!
Note that this is an extremely weak form of encryption. Watch what happens when given a blank string to encode:
>>> codebreak = xorWord(" ", code)
>>> print codebreak
SECRET
You can use normal CSS selectors to select an element by name using jquery. Like this:
Button Code
<button type="button" name="mybutton">Click Me!</button>
Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});
There are lots of ways. And this should work too in all browsers and you don't have to use document.getElementById anymore since you're passing the element itself to the function.
<input type="button" value="Open Curtain" onclick="return change(this);" />
<script type="text/javascript">
function change( el )
{
if ( el.value === "Open Curtain" )
el.value = "Close Curtain";
else
el.value = "Open Curtain";
}
</script>
In bootstrap you can use .text-center
to align center. also add .row
and .col-md-*
to your code.
align=
is deprecated,
Added .col-xs-*
for demo
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
<div class="container">
<div class="row">
<div class="col-xs-4">
<p>Hello there</p>
</div>
<div class="col-xs-4 text-center">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="col-xs-4 text-right">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
</div>
_x000D_
For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
<div class="d-flex justify-content-between">
<div class="p-1">
<p>Hello there</p>
</div>
<div class="p-1">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="p-1">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
_x000D_
There's a much better answer than using spliteratorUnknownSize
directly, which is both easier and gets a better result. Iterable
has a spliterator()
method, so you should just use that to get your spliterator. In the worst case, it's the same code (the default implementation uses spliteratorUnknownSize
), but in the more common case, where your Iterable
is already a collection, you'll get a better spliterator, and therefore better stream performance (maybe even good parallelism). It's also less code:
StreamSupport.stream(iterable.spliterator(), false)
.filter(...)
.moreStreamOps(...);
As you can see, getting a stream from an Iterable
(see also this question) is not very painful.
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
In Sourcetree: Just ignore a file in specified folder. Sourcetree will ask if you like to ignore all files in that folder. It's perfect!
Use
echo "your sql script;" | mysql -u -p -h db_name
You need to diagnosis the jvm usages like how many process is running and what about heap allocation. there exists a lot of ways to do that for example
if (isset($_POST['Register']))
{
$ErrorArrays = array (); //Empty array for input errors
$Input_Username = $_POST['Username'];
$Input_Password = $_POST['Password'];
$Input_Confirm = $_POST['ConfirmPass'];
$Input_Email = $_POST['Email'];
if (empty($Input_Username))
{
$ErrorArrays[] = "Username Is Empty";
}
if (empty($Input_Password))
{
$ErrorArrays[] = "Password Is Empty";
}
if ($Input_Password !== $Input_Confirm)
{
$ErrorArrays[] = "Passwords Do Not Match!";
}
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
}
?>
<form method="POST">
Username: <input type='text' name='Username'> <br>
Password: <input type='password' name='Password'><br>
Confirm Password: <input type='password' name='ConfirmPass'><br>
Email: <input type='text' name='Email'> <br><br>
<input type='submit' name='Register' value='Register'>
</form>
This is a very basic PHP Form validation. This could be put in a try
block, but for basic reference, I see this fit following our conversation in the comment box.
What this script will do, is process each of the post elements, and act accordingly, for example:
if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
{
$ErrorArrays[] = "Incorrect Email Formatting";
}
This will check:
if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.
Further down the script, you will see:
if (count($ErrorArrays) == 0)
{
// No Errors
}
else
{
foreach ($ErrorArrays AS $Errors)
{
echo "<font color='red'><b>".$Errors."</font></b><br>";
}
}
Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.
Remember, this is a reference based on our conversation in the comment box, and should be used as such.
Sheet sheet = workBook.getSheetAt(0); // Get Your Sheet.
for (Row row : sheet) { // For each Row.
Cell cell = row.getCell(0); // Get the Cell at the Index / Column you want.
}
My solution, a bit simpler code wise.
Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:
// add values
list.add("one");
list.add("two");
// your code
for (String object: list) {
System.out.println(object);
}
var example = "I am too long string";
var result;
// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add
Result variable contains "I am too l..."
Try format
function:
> xx = 100000000000
> xx
[1] 1e+11
> format(xx, scientific=F)
[1] "100000000000"
In an XML file, there is a sequence of declarations, and you may override a previous definition with a newer one. When you use annotations, there is no notion of before or after. All the beans are at the same level. You defined two beans with the same name, and Spring doesn't know which one it should choose.
Give them a different name (staticConverterDAO, inMemoryConverterDAO for example), create an alias in the Spring XML file (theConverterDAO for example), and use this alias when injecting the converter:
@Autowired @Qualifier("theConverterDAO")
@Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
@Web.Mvc.Claims.Resources.PartyResource.MaleLabel
@Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
@Web.Mvc.Claims.Resources.PartyResource.FemaleLabel
Add a property to the form method="post"
.
Like this:
<form name="loginform" method="post">
A lot of good answers already, but let me see if I can give you another viewpoint.
Simplifying things by quite a bit, you can view a framework as an application that is complete except for the actual functionality. You plug in the functionality and PRESTO! you have an application.
Consider, say, a GUI framework. The framework contains everything you need to make an application. Indeed you can often trivially make a minimal application with very few lines of source that does absolutely nothing -- but it does give you window management, sub-window management, menus, button bars, etc. That's the framework side of things. By adding your application functionality and "plugging it in" to the right places in the framework you turn this empty app that does nothing more than window management, etc. into a real, full-blown application.
There are similar types of frameworks for web apps, for server-side apps, etc. In each case the framework provides the bulk of the tedious, repetitive code (hopefully) while you provide the actual problem domain functionality. (This is the ideal. In reality, of course, the success of the framework is highly variable.)
I stress again that this is the simplified view of what a framework is. I'm not using scary terms like "Inversion of Control" and the like although most frameworks have such scary concepts built-in. Since you're a beginner, I thought I'd spare you the jargon and go with an easy simile.
List list1 = new ArrayList();
list1.add("one");
list1.add("three");
list1.add("four");
List list2 = new ArrayList();
list2.add("one");
list2.add("two");
list2.add("three");
list2.add("four");
list2.add("five");
list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));
The output is:
two
five
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
string myFile= File.ReadAllLines(Application.StartupPath.ToString() + @"..\..\..\Data\myTxtFile.txt")
"Hello! world!".TrimEnd('!');
EDIT:
What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.
Trim - Removes all occurrences of white space characters from the beginning and end of this instance.
Under this definition removing only last character from string is bad solution.
So if we want to "Trim last character from string" we should do something like this
Example as extension method:
public static class MyExtensions
{
public static string TrimLastCharacter(this String str)
{
if(String.IsNullOrEmpty(str)){
return str;
} else {
return str.TrimEnd(str[str.Length - 1]);
}
}
}
Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :
else { return str.Remove(str.Length - 1); }
I know this has been answered with a very high-quality answer. But, in short, you cant have spaces.
#!/bin/bash
STR = "Hello World"
echo $STR
Didn't work because of the spaces around the equal sign. If you were to run...
#!/bin/bash
STR="Hello World"
echo $STR
It would work
I just wanted a quick and dirty workaround... I couldn't run the script from Nikita Volkov: syntax error + it requires a strict format for the jar names.
I made this Perl script which works with whatever format for the jar file names, and it generates the dependencies in an xml so it can be copy pasted directly in a pom.
If you want to use it, make sure you understand what the script is doing, you may need to change the lib
folder and the value for the groupId
or artifactId
...
#!/usr/bin/perl
use strict;
use warnings;
open(my $fh, '>', 'dependencies.xml') or die "Could not open file 'dependencies.xml' $!";
foreach my $file (glob("lib/*.jar")) {
print "$file\n";
my $groupId = "my.mess";
my $artifactId = "";
my $version = "0.1-SNAPSHOT";
if ($file =~ /\/([^\/]*?)(-([0-9v\._]*))?\.jar$/) {
$artifactId = $1;
if (defined($3)) {
$version = $3;
}
`mvn install:install-file -Dfile=$file -DgroupId=$groupId -DartifactId=$artifactId -Dversion=$version -Dpackaging=jar`;
print $fh "<dependency>\n\t<groupId>$groupId</groupId>\n\t<artifactId>$artifactId</artifactId>\n\t<version>$version</version>\n</dependency>\n";
print " => $groupId:$artifactId:$version\n";
} else {
print "##### BEUH...\n";
}
}
close $fh;
If you don't mind cloning the entire directory, this small bash/zsh function will have the end result of cloning a single file into your current directory (by cloning the repo into a temp directory and removing it afterwards).
Pro: You only get the file you want
Con: You still have to wait for the whole repo to clone
git-single-file () {
if [ $# -lt 2 ]
then
echo "Usage: $0 <repo url> <file path>"
return
fi
TEMP_DIR=$(mktemp -d)
git clone $1 $TEMP_DIR
cp $TEMP_DIR/$2 .
rm -rf $TEMP_DIR
}
To mock an ES6 dependency module default export using Jest:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');
// If necessary, you can place a mock implementation like this:
dependency.mockImplementation(() => 42);
describe('myModule', () => {
it('calls the dependency once with double the input', () => {
myModule(2);
expect(dependency).toHaveBeenCalledTimes(1);
expect(dependency).toHaveBeenCalledWith(4);
});
});
The other options didn't work for my case.
By default connection timeout is 240 but if you are faceing the problem of connection time out then you can increase upto "300" "Connection Timeout=300"
Check
config > config
codeigniter file structure
replace
$config['base_url'] = "your Website url";
with
$config['base_url'] = "http://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= preg_replace('@/+$@', '', dirname($_SERVER['SCRIPT_NAME'])).'/';
You can use --version
and in that case it's not required to redirect to stdout
java --version | head -1 | cut -f2 -d' '
From java help
-version print product version to the error stream and exit
--version print product version to the output stream and exit
Pass a JS Date object and an integer of how many months you want to add/subtract. monthsToAdd
can be positive or negative. Returns a JS date object.
If your originalDateObject
is March 31, and you pass -1 as monthsToAdd
, then your output date will be February 28.
If you pass a large number of months, say 36, it will handle the year adjustment properly as well.
const addMonthsToDate = (originalDateObject, monthsToAdd) => {
const originalDay = originalDateObject.getUTCDate();
const originalMonth = originalDateObject.getUTCMonth();
const originalYear = originalDateObject.getUTCFullYear();
const monthDayCountMap = {
"0": 31,
"1": 28,
"2": 31,
"3": 30,
"4": 31,
"5": 30,
"6": 31,
"7": 31,
"8": 30,
"9": 31,
"10": 30,
"11": 31
};
let newMonth;
if (newMonth > -1) {
newMonth = (((originalMonth + monthsToAdd) % 12)).toString();
} else {
const delta = (monthsToAdd * -1) % 12;
newMonth = originalMonth - delta < 0 ? (12+originalMonth) - delta : originalMonth - delta;
}
let newDay;
if (originalDay > monthDayCountMap[newMonth]) {
newDay = monthDayCountMap[newMonth].toString();
} else {
newDay = originalDay.toString();
}
newMonth = (+newMonth + 1).toString();
if (newMonth.length === 1) {
newMonth = '0' + newMonth;
}
if (newDay.length === 1) {
newDay = '0' + newDay;
}
if (monthsToAdd <= 0) {
monthsToAdd -= 11;
}
let newYear = (~~((originalMonth + monthsToAdd) / 12)) + originalYear;
let newTime = originalDateObject.toISOString().slice(10, 24);
const newDateISOString = `${newYear}-${newMonth}-${newDay}${newTime}`;
return new Date(newDateISOString);
};
You can achieve this with the background-size property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
Go to view
, then appearence
. Then select move panel bottom.
If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:
jQuery('#mydiv').css("overflow-y", "scroll");
Here are the steps that i took to solve the issue and you can try also
ssh-keygen
and hit enterC:\Users\<username>\.ssh
and open a file named id_rsa.pub
in notepad and copy the keySettings
and select the option SSH and GPS keys
.git push origin master
I hope you wont get any errorIf accessibility reasons is important then use the first variant (when customer want to see image without styles)
<div id="logo">
<a href="">
<img src="logo.png" alt="Stack Overflow" />
</a>
</div>
No need to conform imaginary SEO requirements, because the HTML code above has correct structure and only you should decide does this suitable for you visitors.
Also you can use the variant with less HTML code
<h1 id="logo">
<a href=""><span>Stack Overflow</span></a>
</h1>
/* position code, it may be absolute position or normal - depends on other parts of your site */
#logo {
...
}
#logo a {
display:block;
width: actual_image_width;
height: actual_image_height;
background: url(image.png) no-repeat left top;
}
/* for accessibility reasons - without styles variant*/
#logo a span {display: none}
Please note that I have removed all other CSS styles and hacks because they didn't correspond to the task. They may be usefull in particular cases only.
If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.
Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.
If you want to audit a client application name along with each failed login, you can use an Extended Events session.
To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/
How was your 2D array declared?
If it something like:
int arr[20][30];
You can zero it by doing:
memset(arr, sizeof(int)*20*30);
Came across this looking for something else.
While the post looks fairly old, the easiest solution in bash is illustrated below (at least bash 4) using set -- "${@:#}"
where # is the starting number of the array element we want to preserve forward:
#!/bin/bash
someVar="${1}"
someOtherVar="${2}"
set -- "${@:3}"
input=${@}
[[ "${input[*],,}" == *"someword"* ]] && someNewVar="trigger"
echo -e "${someVar}\n${someOtherVar}\n${someNewVar}\n\n${@}"
Basically, the set -- "${@:3}"
just pops off the first two elements in the array like perl's shift and preserves all remaining elements including the third. I suspect there's a way to pop off the last elements as well.