Check out my highly simplified Echo example: It is designed to use basic HTTP communication, but it can easily be modified to use named pipes by editing the app.config files for the client and server. Make the following changes:
Edit the server's app.config file, removing or commenting out the http baseAddress entry and adding a new baseAddress entry for the named pipe (called net.pipe). Also, if you don't intend on using HTTP for a communication protocol, make sure the serviceMetadata and serviceDebug is either commented out or deleted:
<configuration>
<system.serviceModel>
<services>
<service name="com.aschneider.examples.wcf.services.EchoService">
<host>
<baseAddresses>
<add baseAddress="net.pipe://localhost/EchoService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors></serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Edit the client's app.config file so that the basicHttpBinding is either commented out or deleted and a netNamedPipeBinding entry is added. You will also need to change the endpoint entry to use the pipe:
<configuration>
<system.serviceModel>
<bindings>
<netNamedPipeBinding>
<binding name="NetNamedPipeBinding_IEchoService"/>
</netNamedPipeBinding>
</bindings>
<client>
<endpoint address = "net.pipe://localhost/EchoService"
binding = "netNamedPipeBinding"
bindingConfiguration = "NetNamedPipeBinding_IEchoService"
contract = "EchoServiceReference.IEchoService"
name = "NetNamedPipeBinding_IEchoService"/>
</client>
</system.serviceModel>
</configuration>
The above example will only run with named pipes, but nothing is stopping you from using multiple protocols to run your service. AFAIK, you should be able to have a server run a service using both named pipes and HTTP (as well as other protocols).
Also, the binding in the client's app.config file is highly simplified. There are many different parameters you can adjust, aside from just specifying the baseAddress...
I came across System.Runtime.InteropServices.COMException
while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM
Methods. I ran Visual Studio as Administrator and the exception was gone.
Just recently experienced this:
System.ServiceModel.CommunicationException:
An error occurred while making the HTTP request to http://example.com/WebServices/SomeService.svc. This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case. This could also be caused by a mismatch of the security binding between the client and the server.
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.
---> System.IO.IOException: Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.
I found out from an administrator that the IIS application pool that was hosting the web service recycled automatically after running out of memory. The error on the client occurred when the application pool recycled.
Increasing the memory available to the application pool resolved the immediate issue.
I have written a simple base class that handles this. It's available as a NuGet package and it's quite easy to use.
//MemberServiceClient is the class generated by SvcUtil
public class MemberServiceManager : ServiceClientBase<MemberServiceClient>
{
public User GetUser(int userId)
{
return PerformServiceOperation(client => client.GetUser(userId));
}
//you can also check if any error occured if you can't throw exceptions
public bool TryGetUser(int userId, out User user)
{
return TryPerformServiceOperation(c => c.GetUser(userId), out user);
}
}
I've found that the best way to debug is to use the microsoft tool called DTCPing
I've had my fare deal of problems in our old company network, and I've got a few tips:
In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.
Download the map file and the uncompressed version of jQuery.
Put them with the minified version:
Include minified version into your HTML:
Check in Google Chrome:
Get familiar with Debugging JavaScript
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
Try perl -MCPAN -e "upgrade /(.\*)/"
. It works fine for me.
OP: "I would love if there were a way to do it where I didn't have to know the host address..."
response.writeHead(301, {
Location: "http" + (request.socket.encrypted ? "s" : "") + "://" +
request.headers.host + newRoom
});
response.end();
You have to set the height
for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):
.child {
width: 30px;
background-color: red;
display: table-cell;
vertical-align: top;
position:relative;
}
.content {
position:absolute;
top:0;
bottom:0;
width:100%;
background-color: blue;
}
Quick solution, relies on the -webkit-mask-image
property. -webkit-mask-image
sets a mask image for an element.
There are a few gotchas with this method:
:after
psuedo-element (IMG
tags can't have :before
/:after
pseudo elements, grr)attr(…)
CSS function to get the IMG
tag URL, so it's hard-coded into the CSS separately.If you can look past those issues, this might be a possible solution. SVG filters will be even more flexible, and Canvas solutions will be even more flexible and have a wider range of support (SVG doesn't have Android 2.x support).
I wouldn't bother with jQuery or LESS. A javascript framework is overkill in my opinion.
window.addEventListener('scroll', function (evt) {
// This value is your scroll distance from the top
var distance_from_top = document.body.scrollTop;
// The user has scrolled to the tippy top of the page. Set appropriate style.
if (distance_from_top === 0) {
}
// The user has scrolled down the page.
if(distance_from_top > 0) {
}
});
Try this:
string callbackurl = Request.Url.Host != "localhost"
? Request.Url.Host : Request.Url.Authority;
This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.
Just use the ToString()
method
public enum any{Tomato=0,Melon,Watermelon}
To reference the string Tomato
, just use
any.Tomato.ToString();
In my case (IntelliJ 2020-02, Kotlin dev) JUnit library was already included by Create project wizard. I needed to enable JUnit plugin:
to get green Run test icons next to each test class and method:
and CTRL+Shift+R will run test under caret, and CTRL+shift+D to debug.
The (m)
indicates the column display width; applications such as the MySQL client make use of this when showing the query results.
For example:
| v | a | b | c |
+-----+-----+-----+-----+
| 1 | 1 | 1 | 1 |
| 10 | 10 | 10 | 10 |
| 100 | 100 | 100 | 100 |
Here a
, b
and c
are using TINYINT(1)
, TINYINT(2)
and TINYINT(3)
respectively. As you can see, it pads the values on the left side using the display width.
It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1)
still accepts [-128 .. 127]
.
If the id
column has no default value, but has NOT NULL
constraint, then you have to provide a value yourself
INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())
Final(?) edit
Answer, wrapped up in a function, with annotated interactive session:
>>> import re
>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):
... return not bool(search(strg))
...
>>> special_match("")
True
>>> special_match("az09.")
True
>>> special_match("az09.\n")
False
# The above test case is to catch out any attempt to use re.match()
# with a `$` instead of `\Z` -- see point (6) below.
>>> special_match("az09.#")
False
>>> special_match("az09.X")
False
>>>
Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.
==== Earlier text ====
The [previously] accepted answer could use a few improvements:
(1) Presentation gives the appearance of being the result of an interactive Python session:
reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True
but match() doesn't return True
(2) For use with match(), the ^
at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the ^
(3) Should foster the use of raw string automatically unthinkingly for any re pattern
(4) The backslash in front of the dot/period is redundant
(5) Slower than the OP's code!
prompt>rem OP's version -- NOTE: OP used raw string!
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.43 usec per loop
prompt>rem OP's version w/o backslash
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.44 usec per loop
prompt>rem cleaned-up version of accepted answer
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))"
100000 loops, best of 3: 2.07 usec per loop
prompt>rem accepted answer
prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))"
100000 loops, best of 3: 2.08 usec per loop
(6) Can produce the wrong answer!!
>>> import re
>>> bool(re.compile('^[a-z0-9\.]+$').match('1234\n'))
True # uh-oh
>>> bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n'))
False
for cakephp3+:
$url = $this->request->scheme().'://'.$this->request->domain().$this->request->here(false);
will get eg: http://bgq.dev/home/index?t44=333
from nltk.corpus import stopwords
# ...
filtered_words = [word for word in word_list if word not in stopwords.words('english')]
When you only need to check for equality, you can also simply use the in
operator to do a membership test in a sequence of accepted elements:
if message.value[0] in ('/', '\\'):
do_stuff()
Here is my implementation using the Affix Bootstrap plugin http://getbootstrap.com/javascript/#affix
It includes some extra affix problems solved (see below).
HTML:
<nav class="navbar navbar-inverse navbar-fixed-top" id="top_navbar">
<div class="container-fluid">
... (typical Bootstrap top navbar)
</div>
</div>
...
...
...
<div id="parent-navbar-main" >
<div id="navbar-main">
... (here is your nav panel to get sticky on scroll)
</div>
</div>
Javascript:
function set_sticky_panel() {
var affixElement = $('#navbar-main');
var navbarElementHeight = $('#top_navbar').height();
// http://stackoverflow.com/questions/18683303/bootstrap-3-0-affix-with-list-changes-width
var width = affixElement.parent().width();
affixElement.width(width);
// http://stackoverflow.com/questions/3410765/get-full-height-of-element
var affixElementHeight = $('#navbar-main').outerHeight(true);
// https://finiteheap.com/webdev/2014/12/26/bootstrap-affix-flickering.html
affixElement.parent().height(affixElementHeight);
// http://stackoverflow.com/questions/23797241/resetting-changing-the-offset-of-bootstrap-affix
$(window).off('.affix')
affixElement.removeData('bs.affix').removeClass('affix affix-top affix-bottom')
affixElement.affix({
offset: {
// Distance of between element and top page
top: function () {
// how much scrolling is done until sticking the panel
return (this.top = affixElement.offset().top - parseInt(navbarElementHeight,10))
}
}
});
// The replacement for the css-file.
affixElement.on('affix.bs.affix', function (){
// the absolute position where the sticked panel is to be placed when the fixing event fires (e.g. the panel reached the top of the page).
affixElement.css('top', navbarElementHeight + 'px');
affixElement.css('z-index', 10);
});
}
$(document).on('ready', set_sticky_panel);
$(window).resize(set_sticky_panel);
CSS:
No css is required.
If to compare with the standart implementation my code additionaly solves these problems:
@object.as_json
as_json has very flexible way to configure complex object according to model relations
EXAMPLE
Model campaign belongs to shop and has one list
Model list has many list_tasks and each of list_tasks has many comments
We can get one json which combines all those data easily.
@campaign.as_json(
{
except: [:created_at, :updated_at],
include: {
shop: {
except: [:created_at, :updated_at, :customer_id],
include: {customer: {except: [:created_at, :updated_at]}}},
list: {
except: [:created_at, :updated_at, :observation_id],
include: {
list_tasks: {
except: [:created_at, :updated_at],
include: {comments: {except: [:created_at, :updated_at]}}
}
}
},
},
methods: :tags
})
Notice methods: :tags can help you attach any additional object which doesn't have relations with others. You just need to define a method with name tags in model campaign. This method should return whatever you need (e.g. Tags.all)
Official documentation for as_json
Another way is to use the subplots
function and pass the width ratio with gridspec_kw
:
import numpy as np
import matplotlib.pyplot as plt
# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)
# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)
f.tight_layout()
f.savefig('grid_figure.pdf')
If you use vim-plug (Plug), " A minimalist Vim plugin manager.":
:PlugStatus
That will not only list your plugins but check their status.
There is no need to create a key and so forth if you just want to play around with it on your device.
With Eclipse:
To export an unsigned .apk from Eclipse, right-click the project in the Package Explorer and select Android Tools -> Export Unsigned Application Package. Then specify the file location for the unsigned .apk.
CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?
I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).
However the refused message is likely a server side problem, (usually port closed).
in your sample code you must remove the brackets, because it's not a functional assignment; also for documentary reasons I would suggest you use the :=
notation (see code sample below)
Application.Thisworkbook
refers to the book containing the VBA code, not necessarily the book containing the data, so be cautious.Express the sheet you're working on as a sheet object and pass it, together with a logical variable to the following sub:
Sub SetProtectionMode(MySheet As Worksheet, ProtectionMode As Boolean)
If ProtectionMode Then
MySheet.Protect DrawingObjects:=True, Contents:=True, _
AllowSorting:=True, AllowFiltering:=True
Else
MySheet.Unprotect
End If
End Sub
Within the .Protect
method you can define what you want to allow/disallow. This code block will switch protection on/off - without password in this example, you can add it as a parameter or hardcoded within the Sub. Anyway somewhere the PW will be hardcoded. If you don't want this, just call the Protection Dialog window and let the user decide what to do:
Application.Dialogs(xlDialogProtectDocument).Show
Hope that helps
Good luck - MikeD
try
var x = parseFloat(num1) + parseFloat(num2) ;
or, depending on your needs:
var x = parseInt(num1) + parseInt(num2) ;
http://www.javascripter.net/faq/convert2.htm
You might want to pick up the book Javascript: The Good Parts, by Douglas Crockford. Javascript has a rather sizeable colleciton of gotchas! This book goes a long way towards clarifying them. See also
and Mr. Crockford's excellent essay, Javascript: The World's Most Misunderstood Programming Language.
DO $$
DECLARE tableId integer;
BEGIN
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id INTO tableId;
INSERT INTO Table2 (val) VALUES (tableId);
END $$;
Tested with psql (10.3, server 9.6.8)
I think you are a little messed up with what you doing. Athlete is an object, athlete has a name, i has a city where he lives. Athlete can dive.
public class Athlete {
private String name;
private String city;
public Athlete (String name, String city){
this.name = name;
this.city = city;
}
--create method dive, (i am not sure what exactly i has to do)
public void dive (){}
}
public class Main{
public static void main (String [] args){
String name = in.next(); //enter name from keyboad
String city = in.next(); //enter city form keybord
--create a new object athlete and pass paramenters name and city into the object
Athlete a = new Athlete (name, city);
}
}
"Once upon a time there were three little pigs".Split(" ") | ForEach {
"$_ is a token"
}
The key is $_
, which stands for the current variable in the pipeline.
About the code you found online:
%
is an alias for ForEach-Object
. Anything enclosed inside the brackets is run once for each object it receives. In this case, it's only running once, because you're sending it a single string.
$_.Split(" ")
is taking the current variable and splitting it on spaces. The current variable will be whatever is currently being looped over by ForEach
.
You should use the key() function.
key($array)
should return the current key.
If you need the position of the current key:
array_search($key, array_keys($array));
There's the TryParse method, which returns a bool indicating if the conversion was successful.
Always nice to have:
Dim myPath As String
Dim folderPath As String
folderPath = Application.ActiveWorkbook.Path
myPath = Application.ActiveWorkbook.FullName
npm-install-peers worked for me.
npm install -g npm-install-peers
Just set an onload function on the body:
<body onload="init()">
Then do something like this in javascript:
function init() {
var someimage = 'changableBackgroudImage';
document.body.style.background = 'url(img/'+someimage+'.png) no-repeat center center'
}
You can change the 'someimage' variable to whatever you want depending on some conditions, such as the time of day or something, and that image will be set as the background image.
To generate a shared library you need first to compile your C code with the -fPIC
(position independent code) flag.
gcc -c -fPIC hello.c -o hello.o
This will generate an object file (.o), now you take it and create the .so file:
gcc hello.o -shared -o libhello.so
EDIT: Suggestions from the comments:
You can use
gcc -shared -o libhello.so -fPIC hello.c
to do it in one step. – Jonathan Leffler
I also suggest to add -Wall
to get all warnings, and -g
to get debugging information, to your gcc
commands. – Basile Starynkevitch
To print the current working Directory i.e. pwd just type command like:
echo "the PWD is : ${pwd}"
Try df['quantity'] = df['quantity'] * -1
.
Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/
Here I have created handle-destroy directive.
ctrl.directive('handleDestroy', function() {
return function(scope, tElement, attributes) {
scope.$on('$destroy', function() {
alert("In destroy of:" + scope.todo.text);
});
};
});
I came across the same problem. I properly installed the MYSQL Workbench 6.x, but faced the connection as below:
I did a bit R&D on this and found that MySQL service in service.msc is not present. To achieve this I created a new connection in MySQL Workbench then manually configured the MySQL Database Server in "System Profile" (see the below picture).
You also need to install MySQL Database Server and set a configuration file path for my.ini
. Now at last test the connection (make sure MySQL service is running in services.msc).
An alternative to 'LOAD DATA' is available in which the data will not be moved from your existing source location to hive data warehouse location.
You can use ALTER TABLE command with 'LOCATION' option. Here is below required command
ALTER TABLE table_name ADD PARTITION (date_col='2017-02-07') LOCATION 'hdfs/path/to/location/'
The only condition here is, the location should be a directory instead of file.
Hope this will solve the problem.
You actually don't need an ABI at all if--
An oversimplified summary:
API: "Here are all the functions you may call."
ABI: "This is how to call a function."
The ABI is set of rules that compilers and linkers adhere to in order to compile your program so that will work properly. ABIs cover multiple topics:
Taking a deeper look at calling convention, which I consider to be the core of an ABI:
The machine itself has no concept of "functions". When you write a function in a high-level language like c, the compiler generates a line of assembly code like _MyFunction1:
. This is a label, which will eventually get resolved into an address by the assembler. This label marks the "start" of your "function" in the assembly code. In high-level code, when you "call" that function, what you're really doing is causing the CPU to jump to the address of that label and continue executing there.
In preparation for the jump, the compiler must do a bunch of important stuff. The calling convention is like a checklist that the compiler follows to do all this stuff:
_MyFunction1:
). At this point, you can consider the CPU to be "in" your "function".There are many different ABIs / calling conventions. Some main ones are:
Here is a great page that actually shows the differences in the assembly generated when compiling for different ABIs.
Another thing to mention is that an ABI isn't only relevant inside your program's executable module. It's also used by the linker to make sure your program calls library functions correctly. You have multiple shared libraries running on your computer, and as long as your compiler knows what ABI they each use, it can call functions from them properly without blowing up the stack.
Your compiler understanding how to call library functions is extremely important. On a hosted platform (that is, one where an OS loads programs), your program can't even blink without making a kernel call.
Given the following web.config:
<appSettings>
<add key="ClientId" value="127605460617602"/>
<add key="RedirectUrl" value="http://localhost:49548/Redirect.aspx"/>
</appSettings>
Example usage:
using System.Configuration;
string clientId = ConfigurationManager.AppSettings["ClientId"];
string redirectUrl = ConfigurationManager.AppSettings["RedirectUrl"];
ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);
is the right answer
the insert part
INSERT IGNORE INTO mytable ....
Symfony 2.1 has a JsonResponse class.
return new JsonResponse(array('name' => $name));
The passed in array will be JSON encoded the status code will default to 200 and the content type will be set to application/json.
There is also a handy setCallback
function for JSONP.
I don't know if you can do it on-demand, but you can enable the option "Track Active Item in Solution Explorer" (Tools->Options->Projects and Solutions->General) which will always select the active tab item in the solution explorer.
Here's a performance test for the solutions posted here. https://github.com/tedgonzalez/MaxElementInCollectionPerformance
This is the fastest for Swift 5
array.max()
Using MFC it is possible with the following
CFileStatus FileStatus;
BOOL bFileExists = CFile::GetStatus(FileName,FileStatus);
Where FileName
is a string representing the file you are checking for existance
To phyzome's answer (most highly voted one), it seems to me that if you put "identified by" at the end of the grant statement, the user will be created automatically. But if you don't, the user is not created. The following code works for me,
GRANT USAGE ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
DROP USER 'username'@'localhost';
Hope this helps.
An NSInteger
has the method stringValue
that can be used even with a literal
NSString *integerAsString1 = [@12 stringValue];
NSInteger number = 13;
NSString *integerAsString2 = [@(number) stringValue];
Very simple. Isn't it?
var integerAsString = String(integer)
OpenSuse
"sudo zypper install libxml2-devel"
It will install any other dependencies or required packages/libraries
declare @date datetime;
set @date = getdate(); -- or some date
select dateadd(month,1+datediff(month,0,@date),-1);
It is also possible, but you have to mention the same field names in select.
SELECT t1.name, t2.name FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT t1.name, t2.name FROM t2
LEFT JOIN t1 ON t1.id = t2.id
None of the above answers fixed my issue.
The above answers are probably more likely the cause of your problem but my issue was that I was using the wrong bucket name. It was a valid bucket name, it just wasn't my bucket.
The bucket I was pointing to was in a different region that my lambda function so check your bucket name!
First off, EC2 and Elastic Compute Cloud are the same thing.
Next, AWS encompasses the range of Web Services that includes EC2 and Elastic Beanstalk. It also includes many others such as S3, RDS, DynamoDB, and all the others.
EC2 is Amazon's service that allows you to create a server (AWS calls these instances) in the AWS cloud. You pay by the hour and only what you use. You can do whatever you want with this instance as well as launch n
number of instances.
Elastic Beanstalk is one layer of abstraction away from the EC2 layer. Elastic Beanstalk will setup an "environment" for you that can contain a number of EC2 instances, an optional database, as well as a few other AWS components such as a Elastic Load Balancer, Auto-Scaling Group, Security Group. Then Elastic Beanstalk will manage these items for you whenever you want to update your software running in AWS. Elastic Beanstalk doesn't add any cost on top of these resources that it creates for you. If you have 10 hours of EC2 usage, then all you pay is 10 compute hours.
For running Wordpress, it is whatever you are most comfortable with. You could run it straight on a single EC2 instance, you could use a solution from the AWS Marketplace, or you could use Elastic Beanstalk.
In the case that you want to reduce system operations and just focus on the website, then Elastic Beanstalk would be the best choice for that. Elastic Beanstalk supports a PHP stack (as well as others). You can keep your site in version control and easily deploy to your environment whenever you make changes. It will also setup an Autoscaling group which can spawn up more EC2 instances if traffic is growing.
Here's the first result off of Google when searching for "elastic beanstalk wordpress": https://www.otreva.com/blog/deploying-wordpress-amazon-web-services-aws-ec2-rds-via-elasticbeanstalk/
You are correct. You did exactly the right thing, checking the query plan rather than trying to second-guess the optimiser. :-)
Alternative way (but it's not python style. It's JS style)
{{ files and 'Update' or 'Continue' }}
There's no need to remove an account: I switched Google Play to a second Google account, installed an update, and switched back to my original account.
Though apparently, it's sufficient to just switch to a second Google Account, and switch back to the original account, no need to install an update.
I question the value of using a Boolean in TSQL. Every time I've started wishing for Booleans & For loops I realised I was approaching the problem like a C programmer & not a SQL programmer. The problem became trivial when I switched gears.
In SQL you are manipulating SETs of data. "WHERE BOOLEAN" is ineffective, as does not change the set you are working with. You need to compare each row with something for the filter clause to be effective. The Table/Resultset is an iEnumerable, the SELECT statement is a FOREACH loop.
Yes, "WHERE IsAdmin = True" is nicer to read than "WHERE IsAdmin = 1"
Yes, "WHERE True" would be nicer than "WHERE 1=1, ..." when dynamically generating TSQL.
and maybe, passing a Boolean to a stored proc may make an if statement more readable.
But mostly, the more IF's, WHILE's & Temp Tables you have in your TSQL, the more likely you should refactor it.
You can code like below..
<html>
<head>
<style>
p.boldstats{
font-weight: bold
}
</style>
</head>
<body>
<p class="boldstats"> The bold finder </p>
</body>
</html>
You need to use ScriptManager.RegisterStartupScript for Ajax.
protected void ButtonPP_Click(object sender, EventArgs e) { if (radioBtnACO.SelectedIndex < 0) { string csname1 = "PopupScript"; var cstext1 = new StringBuilder(); cstext1.Append("alert('Please Select Criteria!')"); ScriptManager.RegisterStartupScript(this, GetType(), csname1, cstext1.ToString(), true); } }
When a new user is created in ORACLE, an empty work area for tables and views is also automatically created. That work area is called a 'Schema'. Because of the tightly coupled relationship between users and schemas, the terms are often used synonymously. SQL Developer will, by default, show the empty schema that belongs to the user you connected with if it is indeed empty.
However, if you click to expand the part of the tree titled 'Other Users', you'll see other users/schemas that your user has access to. In there, you may find the tables and views you are seeking if you select the correct user/schema. An object only lives in the schema that owns it.
Still, it would be nice if the application allowed us to pick our desired schema closer to the root of the tree instead of forcing us to go searching for it. Other answers have offered workarounds such as:
In the end, I searched and found another free tool that seems to solve this particular usability issue called DBeaver.
It's all a bit confusing because the word schema is overloaded. Schema could also be used to describe the database of your application. To get more clarity, read more about the term schema as it is used in the ORACLE context.
yes, it may work in KITKAT.
above KITKAT+ it will go to internal storage:paths like(storage/emulated/0).
please think, how "Xender app" give permission to write in to external sd card.
So, Fortunately in Android 5.0 and later there is a new official way for apps to write to the external SD card. Apps must ask the user to grant write access to a folder on the SD card. They open a system folder chooser dialog. The user need to navigate into that specific folder and select it.
for more details, please refer https://metactrl.com/docs/sdcard-on-lollipop/
=SUBSTITUTE(text, old_text, new_text)
if: a=!, b=@, c=#,... x=>, y=?, z=~, " "=" "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~ ... ;}? ;*(| ]:;
(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")
---so if a=z,b=y,...y=b,z=a, then the result is
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)
The formula is:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," "," ")
To avoid memory leaks you may use smart pointers whenever you can. There are basically 2 different types of smart pointers in C++
The main difference is that reference counted smart pointers can be copied (and used in std:: containers) while scoped_ptr cannot. Non reference counted pointers have almost no overhead or no overhead at all. Reference counting always introduces some kind of overhead.
(I suggest to avoid auto_ptr, it has some serious flaws if used incorrectly)
may something like this:
testList = [1, 2, 3, 4, 2, 2, 1, 4, 4]
print(max(set(testList), key = testList.count))
This works on firefox 3.6.x and IE:
function copyToClipboardCrossbrowser(s) {
s = document.getElementById(s).value;
if( window.clipboardData && clipboardData.setData )
{
clipboardData.setData("Text", s);
}
else
{
// You have to sign the code to enable this or allow the action in about:config by changing
//user_pref("signed.applets.codebase_principal_support", true);
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes["@mozilla.org/widget/clipboard;1"].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
// create a transferable
var trans = Components.classes["@mozilla.org/widget/transferable;1"].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
// specify the data we wish to handle. Plaintext in this case.
trans.addDataFlavor('text/unicode');
// To get the data from the transferable we need two new objects
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
str.data= s;
trans.setTransferData("text/unicode",str, str.data.length * 2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
}
}
Try this JQuery code to dynamically include form, field, and delete/remove behavior:
$(document).ready(function() {_x000D_
var max_fields = 10;_x000D_
var wrapper = $(".container1");_x000D_
var add_button = $(".add_form_field");_x000D_
_x000D_
var x = 1;_x000D_
$(add_button).click(function(e) {_x000D_
e.preventDefault();_x000D_
if (x < max_fields) {_x000D_
x++;_x000D_
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box_x000D_
} else {_x000D_
alert('You Reached the limits')_x000D_
}_x000D_
});_x000D_
_x000D_
$(wrapper).on("click", ".delete", function(e) {_x000D_
e.preventDefault();_x000D_
$(this).parent('div').remove();_x000D_
x--;_x000D_
})_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="container1">_x000D_
<button class="add_form_field">Add New Field _x000D_
<span style="font-size:16px; font-weight:bold;">+ </span>_x000D_
</button>_x000D_
<div><input type="text" name="mytext[]"></div>_x000D_
</div>
_x000D_
Refer Demo Here
Worked for me by running the command prompt as an administrator
System like Ubuntu prefers to use auth_socket plugin. It will try to authenticate by comparing your username in DB and process which makes mysql request; it is described in here
The socket plugin checks whether the socket user name (the operating system user name) matches the MySQL user name specified by the client program to the server, and permits the connection only if the names match.
Instead you may want to back with the mysql_native_password, which will require user/password to authenticate.
About the method to achieve that, I recommend this instead.
player['score']
is your problem. player is apparently a list
which means that there is no 'score' element. Instead you would do something like:
name, score = player[0], player[1]
return name + ' ' + str(score)
Of course, you would have to know the list indices (those are the 0 and 1 in my example).
Something like player['score']
is allowed in python, but player
would have to be a dict
.
You can read more about both lists and dicts in the python documentation.
Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)
RoflcoptrException's answer should do the trick,but for some reason it did not work for me, So I am posting the solution which worked for me, hope it helps someone
<ListView
android:listSelector="@android:color/transparent"
android:cacheColorHint="@android:color/transparent"
/>
If you are looking for psql command-line mode
like me, here is the syntax --pset expanded=auto
Quoted it here
psql command-line options:
-P expanded=auto
--pset expanded=auto
-x
--expanded
Another 2nd way is -q
option ref
So you can utilize short-circuiting:
bool containsBoth = compareString.Contains(firstString) &&
compareString.Contains(secondString);
With deferred
(another promise/deferred implementation) you can do:
// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
deferred.promisify(mongoose.Collection.prototype.drop);
// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
return conn.collection(name).pdrop()(function () {
console.log("dropped");
});
}).end(function () {
console.log("all dropped");
}, null);
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
Building on @Mike Gledhill's code, I've taken it a step further and added more parameters. If you have a SVG RECT and want text to wrap inside it, this may be handy:
function wraptorect(textnode, boxObject, padding, linePadding) {
var x_pos = parseInt(boxObject.getAttribute('x')),
y_pos = parseInt(boxObject.getAttribute('y')),
boxwidth = parseInt(boxObject.getAttribute('width')),
fz = parseInt(window.getComputedStyle(textnode)['font-size']); // We use this to calculate dy for each TSPAN.
var line_height = fz + linePadding;
// Clone the original text node to store and display the final wrapping text.
var wrapping = textnode.cloneNode(false); // False means any TSPANs in the textnode will be discarded
wrapping.setAttributeNS(null, 'x', x_pos + padding);
wrapping.setAttributeNS(null, 'y', y_pos + padding);
// Make a copy of this node and hide it to progressively draw, measure and calculate line breaks.
var testing = wrapping.cloneNode(false);
testing.setAttributeNS(null, 'visibility', 'hidden'); // Comment this out to debug
var testingTSPAN = document.createElementNS(null, 'tspan');
var testingTEXTNODE = document.createTextNode(textnode.textContent);
testingTSPAN.appendChild(testingTEXTNODE);
testing.appendChild(testingTSPAN);
var tester = document.getElementsByTagName('svg')[0].appendChild(testing);
var words = textnode.textContent.split(" ");
var line = line2 = "";
var linecounter = 0;
var testwidth;
for (var n = 0; n < words.length; n++) {
line2 = line + words[n] + " ";
testing.textContent = line2;
testwidth = testing.getBBox().width;
if ((testwidth + 2*padding) > boxwidth) {
testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
testingTSPAN.setAttributeNS(null, 'dy', line_height);
testingTEXTNODE = document.createTextNode(line);
testingTSPAN.appendChild(testingTEXTNODE);
wrapping.appendChild(testingTSPAN);
line = words[n] + " ";
linecounter++;
}
else {
line = line2;
}
}
var testingTSPAN = document.createElementNS('http://www.w3.org/2000/svg', 'tspan');
testingTSPAN.setAttributeNS(null, 'x', x_pos + padding);
testingTSPAN.setAttributeNS(null, 'dy', line_height);
var testingTEXTNODE = document.createTextNode(line);
testingTSPAN.appendChild(testingTEXTNODE);
wrapping.appendChild(testingTSPAN);
testing.parentNode.removeChild(testing);
textnode.parentNode.replaceChild(wrapping,textnode);
return linecounter;
}
document.getElementById('original').onmouseover = function () {
var container = document.getElementById('destination');
var numberoflines = wraptorect(this,container,20,1);
console.log(numberoflines); // In case you need it
};
I got confused by the answer to this question, so I created a test case in MySQL, hope this helps
-- Schema
CREATE TABLE T1 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE T2 (
`ID` int not null auto_increment,
`Label` varchar(50),
primary key (`ID`)
);
CREATE TABLE TT (
`IDT1` int not null,
`IDT2` int not null,
primary key (`IDT1`,`IDT2`)
);
ALTER TABLE `TT`
ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;
-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);
-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1
You can define a function type in interface in various ways,
export interface IParam {
title: string;
callback(arg1: number, arg2: number): number;
}
export interface IParam {
title: string;
callback: (arg1: number, arg2: number) => number;
}
type MyFnType = (arg1: number, arg2: number) => number;
export interface IParam {
title: string;
callback: MyFnType;
}
Using is very straight forward,
function callingFn(paramInfo: IParam):number {
let needToCall = true;
let result = 0;
if(needToCall){
result = paramInfo.callback(1,2);
}
return result;
}
export interface IParam{
title: string;
callback(lateCallFn?:
(arg1:number,arg2:number)=>number):number;
}
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
for the penultimate day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
As @mrroot5 points out dateutil's rrule
functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.
from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)
#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)
#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)
#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)
Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00
2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
For Registry Key you can check if it is null after getting it. It will be, if it doesn't exist.
For Registry Value you can get names of Values for the current key and check if this array contains the needed Value name.
Example:
public static bool checkMachineType()
{
RegistryKey winLogonKey = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\services\pcmcia", true);
return (winLogonKey.GetValueNames().Contains("Start"));
}
How about just a simple reset button?
<form>
<input type="text" id="textfield1" size="5">
<input type="text" id="textfield2" size="5">
<input type="reset" value="Reset">
</form>
I have discovered that NotePad++ now also creates a subfolder at the file location, called nppBackup. So if your file lived in a folder called c:/thisfolder have a look to see if there's a folder called c:/thisfolder/nppBackup.
Occasionally I couldn't find the backup in AppData\Roaming\Notepad++\backup, but I found it in nppBackup.
Here is how to do a quick check to see if n.fn.init[0]
is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout
function like this:
function timeout(){
...your selector function that returns n.fn.init[0] goes here...
}
setTimeout(timeout, 5000)
This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.
This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.
The preferred ways to check if the DOM is loaded before executing your function are as follows:
1) Wrap your selector function in
$(document).ready(function(){ ... your selector function... };
2) If that doesn't work, use DOMContentLoaded
3) Try window.onload, which waits for all the images to load first, so its least preferred
window.onload = function () { ... your selector function... }
4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.
5) Finally, you can stick with hard-coded setTimeout
function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.
This list of fixes is probably far from perfect so everyone is welcome to edit it.
I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).
The weights from the class_weight
parameter are used to train the classifier.
They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.
Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.
Once you have a classifier, you want to know how well it is performing.
Here you can use the metrics you mentioned: accuracy
, recall_score
, f1_score
...
Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.
I will not detail all these metrics but note that, with the exception of accuracy
, they are naturally applied at the class level: as you can see in this print
of a classification report they are defined for each class. They rely on concepts such as true positives
or false negative
that require defining which class is the positive one.
precision recall f1-score support
0 0.65 1.00 0.79 17
1 0.57 0.75 0.65 16
2 0.33 0.06 0.10 17
avg / total 0.52 0.60 0.51 50
F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The
default `weighted` averaging is deprecated, and from version 0.18,
use of precision, recall or F-score with multiclass or multilabel data
or pos_label=None will result in an exception. Please set an explicit
value for `average`, one of (None, 'micro', 'macro', 'weighted',
'samples'). In cross validation use, for instance,
scoring="f1_weighted" instead of scoring="f1".
You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:
avg / total
result above. It's also called macro averaging.'weighted'
in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average
argument for the score method.
Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.
The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.
Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.
Here's a way to do it using StratifiedShuffleSplit
, which gives you a random splits of your data (after shuffling) that preserve the label distribution.
from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix
# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
svc.fit(X_train, y_train)
y_pred = svc.predict(X_test)
print(f1_score(y_test, y_pred, average="macro"))
print(precision_score(y_test, y_pred, average="macro"))
print(recall_score(y_test, y_pred, average="macro"))
Hope this helps.
This works in Python 2.x.
For Python 3 look in the docs:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
If you just want to check if that item exists:
IEnumerable<DataGridViewRow> rows = grdPdfs.Rows
.Cast<DataGridViewRow>()
.Where(r => r.Cells["SystemId"].Value.ToString().Equals(searchValue));
if (rows.Count() == 0)
{
// Not Found
}
else
{
// Found
}
Enclose the field in quotes, e.g.
field1_value,field2_value,"field 3,value",field4, etc...
See wikipedia.
Updated:
To encode a quote, use "
, one double quote symbol in a field will be encoded as ""
, and the whole field will become """"
. So if you see the following in e.g. Excel:
---------------------------------------
| regular_value |,,,"| ,"", |""" |"|
---------------------------------------
the CSV file will contain:
regular_value,",,,""",","""",","""""""",""""
A comma is simply encapsulated using quotes, so ,
becomes ","
.
A comma and quote needs to be encapsulated and quoted, so ","
becomes ""","""
.
Use 'event.currentTarget.performance.navigation.type' to determine the type of navigation. This is working in IE, FF and Chrome.
function CallbackFunction(event) {
if(window.event) {
if (window.event.clientX < 40 && window.event.clientY < 0) {
alert("back button is clicked");
}else{
alert("refresh button is clicked");
}
}else{
if (event.currentTarget.performance.navigation.type == 2) {
alert("back button is clicked");
}
if (event.currentTarget.performance.navigation.type == 1) {
alert("refresh button is clicked");
}
}
}
Prevent saving changes that require table re-creation
Five swift clicks
- Tools
- Options
- Designers
- Prevent saving changes that require table re-creation
- OK.
After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.
Further explanation
By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*
When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.
*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.
The $?
syntax is pretty neat:
if [ $?BLAH == 1 ]; then
echo "Exists";
else
echo "Does not exist";
fi
If you want to get and set the property both, you can use this in C#7:
GetString(
inputString,
(() => client.WorkPhone, x => client.WorkPhone = x))
void GetString(string inValue, (Func<string> get, Action<string> set) outValue)
{
if (!string.IsNullOrEmpty(outValue))
{
outValue.set(inValue);
}
}
You can't have optional path variables, but you can have two controller methods which call the same service code:
@RequestMapping(value = "/json/{type}", method = RequestMethod.GET)
public @ResponseBody TestBean typedTestBean(
HttpServletRequest req,
@PathVariable String type,
@RequestParam("track") String track) {
return getTestBean(type);
}
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody TestBean testBean(
HttpServletRequest req,
@RequestParam("track") String track) {
return getTestBean();
}
You can execute a function defined in a DLL file by using the rundll command. You can explore the functions available by using Dependency Walker.
You will need something more that a http request to interact with a WCF service UNLESS your WCF service has a REST interface. Either look for a SOAP web service API that runs on android or make your service RESTful. You will need .NET 3.5 SP1 to do WCF REST services:
I would define $Version as a string to start with
[string]$Version
and if it's a param you can use the code posted by Samselvaprabu or if you would rather not present your users with an error you can do something like
while (-not($version)){
$version = Read-Host "Enter the version ya fool!"
}
$request += "/" + $version
<head>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
worked for me, to force IE to "snap out of compatibility mode" (so to speak), BUT that meta statement must appear IMMEDIATELY after the <head>
, or it won't work!
Just add quotes around the size in your code. Using this you can use percentage in width, height
input: {
width: '80%'
}
There are mostly all browser support RGBa code in CSS but only IE8 and below level does not support RGBa css code. For This here is solution. For The solution you must follow this code and it’s better to go with it’s sequence otherwise you will not get perfect output as you wish. This code is used by me and it’s mostly perfect. make comment if it’s perfect.
.class
{
/* Web browsers that does not support RGBa */
background: rgb(0, 0, 0);
/* IE9/FF/chrome/safari supported */
background: rgba(0, 0, 0, 0.6);
/* IE 8 suppoerted */
/* Here some time problem for Hover than you can use background color/image */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#88000000, endColorstr=#88000000)";
/* Below IE7 supported */
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#88000000, endColorstr=#88000000);
}
I too wanted to do something similar, this is what I found: (SDK 3.1.3)
I have a view controller A (itself owned by a Nav controller) which loads VC B on a button press:
In AViewController.m
BViewController *bController = [[BViewController alloc] initWithNibName:@"Bnib" bundle:nil];
[self.navigationController pushViewController:bController animated:YES];
[bController release];
Now VC B has its interface from Bnib, but when a button is pressed, I want to go to an 'edit mode' which has a separate UI from a different nib, but I don't want a new VC for the edit mode, I want the new nib to be associated with my existing B VC.
So, in BViewController.m (in button press method)
NSArray *nibObjects = [[NSBundle mainBundle] loadNibNamed:@"EditMode" owner:self options:nil];
UIView *theEditView = [nibObjects objectAtIndex:0];
self.editView = theEditView;
[self.view addSubview:theEditView];
Then on another button press (to exit edit mode):
[editView removeFromSuperview];
and I'm back to my original Bnib.
This works fine, but note my EditMode.nib has only 1 top level obj in it, a UIView obj. It doesn't matter whether the File's Owner in this nib is set as BViewController or the default NSObject, BUT make sure the View Outlet in the File's Owner is NOT set to anything. If it is, then I get a exc_bad_access crash and xcode proceeds to load 6677 stack frames showing an internal UIView method repeatedly called... so looks like an infinite loop. (The View Outlet IS set in my original Bnib however)
Hope this helps.
Hardware -> Erase all content and settings did the job for me (other things didn't).
As an alternative to the other (very good) answers, you could cast to uintptr_t
or intptr_t
(from stdint.h
/inttypes.h
) and use the corresponding integer conversion specifiers. This would allow more flexibility in how the pointer is formatted, but strictly speaking an implementation is not required to provide these typedefs.
My solution to your problem would be to either:
1 - use int instead of enums: Declare your ints in an anonymous namespace in your CPP file (not in the header):
namespace
{
const int FUNCTIONALITY_NORMAL = 0 ;
const int FUNCTIONALITY_RESTRICTED = 1 ;
const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
}
As your methods are private, no one will mess with the data. You could even go further to test if someone sends you an invalid data:
namespace
{
const int FUNCTIONALITY_begin = 0 ;
const int FUNCTIONALITY_NORMAL = 0 ;
const int FUNCTIONALITY_RESTRICTED = 1 ;
const int FUNCTIONALITY_FOR_PROJECT_X = 2 ;
const int FUNCTIONALITY_end = 3 ;
bool isFunctionalityCorrect(int i)
{
return (i >= FUNCTIONALITY_begin) && (i < FUNCTIONALITY_end) ;
}
}
2 : create a full class with limited const instantiations, like done in Java. Forward declare the class, and then define it in the CPP file, and instanciate only the enum-like values. I did something like that in C++, and the result was not as satisfying as desired, as it needed some code to simulate an enum (copy construction, operator =, etc.).
3 : As proposed before, use the privately declared enum. Despite the fact an user will see its full definition, it won't be able to use it, nor use the private methods. So you'll usually be able to modify the enum and the content of the existing methods without needing recompiling of code using your class.
My guess would be either the solution 3 or 1.
There are two type of convert method in SQL.
CAST and CONVERT have similar functionality. CONVERT is specific to SQL Server, and allows for a greater breadth of flexibility when converting between date and time values, fractional numbers, and monetary signifiers. CAST is the more ANSI-standard of the two functions.
Using Convert
Select convert(int,[Column1])
Using Cast
Select cast([Column1] as int)
mongodb.com -> new project -> new cluster -> new collection -> connect -> IP address: 0.0.0.0/0 & db cred -> connect your application -> copy connection string and paste in .env file of your node app and make sure to replace "" with the actual password for the user and also replace "/test" with your db name
create new file .env
CONNECTIONSTRING=x --> const client = new MongoClient(CONNECTIONSTRING)
PORT=8080
JWTSECRET=mysuper456secret123phrase
Executing git remote update
works for me.
In my case it should be:
from multiprocessing import JoinableQueue
Since in python2, Queue has methods like .task_done()
, but in python3 multiprocessing.Queue
doesn't have this method, and multiprocessing.JoinableQueue
does.
Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:
Using '@reboot' you can Run a command once, at startup.
Wrapping up:
run $ sudo crontab -e -u root
And add a line at the end of the file with your command as follows:
@reboot sudo searchd
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
I had this problem just last week. I had to serialize a PDF file and send it, inside an XML file, to a server.
If you're using .NET, you can convert a binary file directly to a base64 string and stick it inside an XML element.
string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));
Or, there is a method built right into the XmlWriter object. In my particular case, I had to include Microsoft's datatype namespace:
StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();
The string abc looks something that looks like this:
<?xml version="1.0" encoding="utf-16"?>
<doc>
<serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes">
JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)
</serialized_binary>
</doc>
You need to use the change directory command 'cd' to change directory
cd C:\Users\MyName\Desktop
you can use cd \d
to change the drive as well.
link for additional resources http://ss64.com/nt/cd.html
I am facing a similar problem here. Our users are migrating their jobs from freestyle to pipeline. They do not want Jenkinsfile stored in their repos(historical reason) and still want to use "Git Parameter" plugin
So we have to use use "Pipeline script" and develop a different plugin which works like "Git Parameter".
This new plugin does not integrate with SCM setting in the project. The plugin is at https://plugins.jenkins.io/list-git-branches-parameter
Hope it helps you as well
A possible solution might be to use the JSON dumps() method, so you can convert the dictionary to a string ---
import json
a={"a":10, "b":20}
b={"b":20, "a":10}
c = [json.dumps(a), json.dumps(b)]
set(c)
json.dumps(a) in c
Output -
set(['{"a": 10, "b": 20}'])
True
You'll need to order by the same field you're ordering by now, but descending.
As an example, if you have a time stamp when the upload was done called upload_time
, you'd do something like this;
For Pre-Laravel 4
return DB::table('files')->order_by('upload_time', 'desc')->first();
For Laravel 4 and onwards
return DB::table('files')->orderBy('upload_time', 'desc')->first();
For Laravel 5.7 and onwards
return DB::table('files')->latest('upload_time')->first();
This will order the rows in the files table by upload time, descending order, and take the first one. This will be the latest uploaded file.
To expand upon Christian's answer, the only reliable way to do this would be to combine mkdir
and cp
:
mkdir -p /foo/bar && cp myfile "$_"
As an aside, when you only need to create a single directory in an existing hierarchy, rsync
can do it in one operation. I'm quite a fan of rsync
as a much more versatile cp
replacement, in fact:
rsync -a myfile /foo/bar/ # works if /foo exists but /foo/bar doesn't. bar is created.
My recommendation is Virtuous Ten Studio. The tool is free but they suggest a donation. It combines all the necessary steps (unpacking APK, baksmaliing, decompiling, etc.) into one easy-to-use UI-based import process. Within five minutes you should have Java source code, less than it takes to figure out the command line options of one of the above mentioned tools.
Decompiling smali to Java is an inexact process, especially if the smali artifacts went through an obfuscator. You can find several decompilers on the web but only some of them are still maintained. Some will give you better decompiled code than others. Read "better" as in "more understandable" than others. Don't expect that the reverse-engineered Java code will compile out of the box. Virtuous Ten Studio comes with multiple free Java decompilers built-in so you can easily try out different decompilers (the "Generate Java source" step) to see which one gives you the best results, saving you the time to find those decompilers yourself and figure out how to use them. Amongst them is CFR, which is one of the few free and still maintained decompilers.
As output you receive, amongst other things, a folder structure that contains all the decompiled Java source code. You can then import this into IntelliJ IDEA or Eclipse for further editing, analysis (e.g. Go to definition, Find usages), etc.
These errors are usually generated from an ad blocking plugin, such as Adblock Plus. To test this use either a different browser or uninstall the ad blocking plugin (right clicking the extension by the URL bar and clicking "Remove from Chrome...").
There is an easier way to temporarily disable an extension. In Chrome, opening an Incognito tab will usually stop extensions running (unless you have specifically told Chrome which ones to run in Incognito).
The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.
Specifying a non-static position, e.g., position: absolute/relative
on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/
See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts
We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.
#outer {_x000D_
min-width: 2000px; _x000D_
min-height: 1000px; _x000D_
background: #3e3e3e; _x000D_
position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
left: 1%; _x000D_
top: 45px; _x000D_
width: 50%; _x000D_
height: auto; _x000D_
position: absolute; _x000D_
z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
background: #efffef;_x000D_
position: absolute; _x000D_
height: 400px; _x000D_
right: 0px; _x000D_
left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
<div id="inner">_x000D_
<div id="inner-inner"></div>_x000D_
</div>_x000D_
</div>
_x000D_
No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.
Check this link: https://developers.google.com/gsuite/products for updates.
However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi
IIS 6.0 and previous versions :
ASP.NET integrated with IIS via an ISAPI extension, a C API ( C Programming language based API ) and exposed its own application and request processing model.
This effectively exposed two separate server( request / response ) pipelines, one for native ISAPI filters and extension components, and another for managed application components. ASP.NET components would execute entirely inside the ASP.NET ISAPI extension bubble AND ONLY for requests mapped to ASP.NET in the IIS script map configuration.
Requests to non ASP.NET content types:- images, text files, HTML pages, and script-less ASP pages, were processed by IIS or other ISAPI extensions and were NOT visible to ASP.NET.
The major limitation of this model was that services provided by ASP.NET modules and custom ASP.NET application code were NOT available to non ASP.NET requests
What's a SCRIPT MAP ?
Script maps are used to associate file extensions with the ISAPI handler that executes when that file type is requested. The script map also has an optional setting that verifies that the physical file associated with the request exists before allowing the request to be processed
A good example can be seen here
IIS 7 and above
IIS 7.0 and above have been re-engineered from the ground up to provide a brand new C++ API based ISAPI.
IIS 7.0 and above integrates the ASP.NET runtime with the core functionality of the Web Server, providing a unified(single) request processing pipeline that is exposed to both native and managed components known as modules ( IHttpModules )
What this means is that IIS 7 processes requests that arrive for any content type, with both NON ASP.NET Modules / native IIS modules
and ASP.NET modules
providing request processing in all stages This is the reason why NON ASP.NET content types (.html, static files ) can be handled by .NET modules.
IHttpModule
) that have the ability to execute for all application content, and provided an enhanced set of request processing services to your application.IHttpHandler
)When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe
You can do it using:
driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();
In case if your frameId is dynamic, and you only have one iframe, you can use something like:
driver.switchTo().frame(driver.findElement(By.tagName("iframe")));
One possible solution what I can suggest you is to add android:launchMode="singleTop"
in the manifest for my ProfileActivity. and when log out is clicked u can logoff starting again you LoginActivity.
on logout u can call this.
Intent in = new Intent(Profile.this,Login.class);
in.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(in);
finish();
You may as well use for x in values
rather than for x in values[:]
; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...
The code only prints one item per value of x
- and x
is iterating over the elements of values
, which are the sublists. So it will only print each sublist once.
There’s also SenTestingKitAsync that lets you write code like this:
- (void)testAdditionAsync {
[Calculator add:2 to:2 block^(int result) {
STAssertEquals(result, 4, nil);
STSuccess();
}];
STFailAfter(2.0, @"Timeout");
}
(See objc.io article for details.) And since Xcode 6 there’s an AsynchronousTesting
category on XCTest
that lets you write code like this:
XCTestExpectation *somethingHappened = [self expectationWithDescription:@"something happened"];
[testedObject doSomethigAsyncWithCompletion:^(BOOL succeeded, NSError *error) {
[somethingHappened fulfill];
}];
[self waitForExpectationsWithTimeout:1 handler:NULL];
This will do the trick. Note the use of display()
instead of print.
with pd.option_context('display.max_rows', 5, 'display.max_columns', None):
display(my_df)
EDIT:
The use of display
is required because pd.option_context
settings only apply to display
and not to print
.
You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.
Install PM2
$ npm install pm2 -g
Start an application
$ pm2 start app.js
If you using express then you can start your app like
pm2 start ./bin/www --name="app"
Listing all running processes:
$ pm2 list
It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.
$ pm2 stop all
$ pm2 stop 0
$ pm2 restart all
To display logs
$ pm2 logs ['all'|app_name|app_id]
One addition: It should be noted that, in case "/tmp" is the directory where the session data is stored (which seems to be the default value), the sessions will not persist after reboot of that web server, as "/tmp" is often purged during reboot. The concept of a client-wise persistence stands and falls with the persistence of the storage on the server - which might fail if the "/tmp" directory is used for session data.
Do you mean full calendar days, or groups of 24 hours?
For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:
days = (a - b).days
For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:
roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days
I have found following best ways to resize google recaptchas
Option 1: You can resize google ReCaptcha by using inline style.
A very first way for resizing google recapture by using inline style. Inline styles are CSS styles that are applied to one element, directly in the page's HTML, using the style attribute. Here is the example that shows you how you to style Google reCAPTCHA by using inline style.
<div class="g-recaptcha" style="transform: scale(0.77); -webkit-transform: scale(0.77); transform-origin: 0 0; -webkit-transform-origin: 0 0;" data-theme="light" data-sitekey="XXXXXXXXXXXXX"></div>
Option 2: By putting the following style in your page (Internal Style Sheet).
Secondly, you can put style for ReCaptcha into the page between and . An internal style sheet is a section on an HTML page that contains style definitions. Internal style sheets are defined by using the tag within the area of the document. Here is the example that shows you how you to style Google reCAPTCHA by using an external style sheet.
<style type="text/css">
.g-recaptcha{
transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
}
</style>
Option 3: Resize google ReCaptcha by using an external stylesheet.
Create a separate file and give a name like style.css and add this file link in between your an element in your page. For ex. .
<style type="text/css">
.g-recaptcha{
transform:scale(0.77);
-webkit-transform:scale(0.77);
transform-origin:0 0;
-webkit-transform-origin:0 0;
}
</style>
Reference from the blog: https://www.scratchcode.io/how-to-resize-the-google-recaptcha/
I could fix it by installing the following directly.
pip install google.cloud.bigquery
pip install google.cloud.storage
This works well:
{{ app('request')->input('a') }}
Where a
is the url parameter.
See more here: http://blog.netgloo.com/2015/07/17/lumen-getting-current-url-parameter-within-a-blade-view/
You are conflating Optional
with having a default. An Optional
accepts either a value or nil. Having a default permits the argument to be omitted in calling the function. An argument can have a default value with or without being of Optional
type.
func someFunc(param1: String?,
param2: String = "default value",
param3: String? = "also has default value") {
print("param1 = \(param1)")
print("param2 = \(param2)")
print("param3 = \(param3)")
}
Example calls with output:
someFunc(param1: nil, param2: "specific value", param3: "also specific value")
param1 = nil
param2 = specific value
param3 = Optional("also specific value")
someFunc(param1: "has a value")
param1 = Optional("has a value")
param2 = default value
param3 = Optional("also has default value")
someFunc(param1: nil, param3: nil)
param1 = nil
param2 = default value
param3 = nil
To summarize:
Optional
may be nil or may contain an instance of
TypeOptional
and has default, then it may be omitted from function call OR may be included and can be provided with a nil value (e.g. param1: nil)div.abc.xyz {
/* rules go here */
}
... or simply:
.abc.xyz {
/* rules go here */
}
Just append a div
with that class to body
, then remove it when you're done:
// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);
// Remove it (later)
$(".modal-backdrop").remove();
Live Example:
$("input").click(function() {_x000D_
var bd = $('<div class="modal-backdrop"></div>');_x000D_
bd.appendTo(document.body);_x000D_
setTimeout(function() {_x000D_
bd.remove();_x000D_
}, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
Also look into the PEAR mail package Pear Mail Page
It seems to be a little more robust than the standard mail() function that is built in (if the standard function isn't adequate).
Here is an excerpt from this page showing how it is used. PEAR Mail send() usage
<?php
include('Mail.php');
$recipients = '[email protected]';
$headers['From'] = '[email protected]';
$headers['To'] = '[email protected]';
$headers['Subject'] = 'Test message';
$body = 'Test message';
$smtpinfo["host"] = "smtp.server.com";
$smtpinfo["port"] = "25";
$smtpinfo["auth"] = true;
$smtpinfo["username"] = "smtp_user";
$smtpinfo["password"] = "smtp_password";
// Create the mail object using the Mail::factory method
$mail_object =& Mail::factory("smtp", $smtpinfo);
$mail_object->send($recipients, $headers, $body);
?>
Problem is that you are doing something wrong in XML layout file
android:text=" <- Go Back" // this creates error
android:text="Go Back" // correct way
I need a query with constant time response
By default, the indexes in MongoDB are B-Trees. Searching a B-Tree is a O(logN) operation, so even find({_id:...})
will not provide constant time, O(1) responses.
That stated, you can also sort by the _id
if you are using ObjectId
for you IDs. See here for details. Of course, even that is only good to the last second.
You may to resort to "writing twice". Write once to the main collection and write again to a "last updated" collection. Without transactions this will not be perfect, but with only one item in the "last updated" collection it will always be fast.
I solved this exact problem today and stumbled onto this unanswered question by chance during the process.
First, ensure you've properly setup Firebase for Android as documented here: https://firebase.google.com/docs/android/setup. Then, make sure you are compiling the latest version of the Firebase APIs (9.2.0) and the Google Play Services APIs (9.2.0) that you are using. My gradle dependencies look something like this:
dependencies {
...
compile 'com.google.android.gms:play-services-location:9.2.0'
compile 'com.google.firebase:firebase-core:9.2.0'
compile 'com.google.firebase:firebase-auth:9.2.0'
compile 'com.google.firebase:firebase-messaging:9.2.0'
}
Hope this helps!
You can use IPython's Module: display
to load the image. You can read more from the Doc.
from IPython.display import Image
pil_img = Image(filename='data/empire.jpg')
display(pil_img)
As OP's requirement is to use PIL
, if you want to show inline image, you can use matplotlib.pyplot.imshow
with numpy.asarray
like this too:
from matplotlib.pyplot import imshow
import numpy as np
from PIL import Image
%matplotlib inline
pil_im = Image.open('data/empire.jpg', 'r')
imshow(np.asarray(pil_im))
If you only require a preview rather than an inline, you may just use show
like this:
pil_im = Image.open('data/empire.jpg', 'r')
pil_im.show()
I recently had the same issue. It's more likely that your application can not connect to database server due to the network issues.
In my case I was connected to wrong WiFi.
They really should add a wrapper. Like this:
namespace std
{
template<class _container,
class _Ty> inline
bool contains(_container _C, const _Ty& _Val)
{return std::find(_C.begin(), _C.end(), _Val) != _C.end(); }
};
...
if( std::contains(my_container, what_to_find) )
{
}
Please use flexbox for this. You have a container that is going to flex its children into a row. The first child takes its space as needed. The second one flexes to take all the remaining space:
<div style="display:flex;flex-direction:row">_x000D_
<label for="MyInput">label text</label>_x000D_
<input type="text" id="MyInput" style="flex:1" />_x000D_
</div>
_x000D_
Instead of using this:
$(document).ready(function() { /* your code */ });
Use this:
jQuery(function($) { /* your code */ })(jQuery);
It is more concise and does the same thing, it also doesn't depend on the $
variable to be the jQuery object.
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
Here's a quick example:
termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))
result = [x[1] for x in termList if x[0] == 'term3']
print(result)
AJAX is the best way to do asynchronous tasks. Making asynchronous calls is something common in use in any website building. We will take a short example to learn how we can implement AJAX in Django. We need to use jQuery so as to write less javascript.
This is Contact example, which is the simplest example, I am using to explain the basics of AJAX and its implementation in Django. We will be making POST request in this example. I am following one of the example of this post: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django
models.py
Let's first create the model of Contact, having basic details.
from django.db import models
class Contact(models.Model):
name = models.CharField(max_length = 100)
email = models.EmailField()
message = models.TextField()
timestamp = models.DateTimeField(auto_now_add = True)
def __str__(self):
return self.name
forms.py
Create the form for the above model.
from django import forms
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
exclude = ["timestamp", ]
views.py
The views look similar to the basic function-based create view, but instead of returning with render, we are using JsonResponse response.
from django.http import JsonResponse
from .forms import ContactForm
def postContact(request):
if request.method == "POST" and request.is_ajax():
form = ContactForm(request.POST)
form.save()
return JsonResponse({"success":True}, status=200)
return JsonResponse({"success":False}, status=400)
urls.py
Let's create the route of the above view.
from django.contrib import admin
from django.urls import path
from app_1 import views as app1
urlpatterns = [
path('ajax/contact', app1.postContact, name ='contact_submit'),
]
template
Moving to frontend section, render the form which was created above enclosing form tag along with csrf_token and submit button. Note that we have included the jquery library.
<form id = "contactForm" method= "POST">{% csrf_token %}
{{ contactForm.as_p }}
<input type="submit" name="contact-submit" class="btn btn-primary" />
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Javascript
Let's now talk about javascript part, on the form submit we are making ajax request of type POST, taking the form data and sending to the server side.
$("#contactForm").submit(function(e){
// prevent from normal form behaviour
e.preventDefault();
// serialize the form data
var serializedData = $(this).serialize();
$.ajax({
type : 'POST',
url : "{% url 'contact_submit' %}",
data : serializedData,
success : function(response){
//reset the form after successful submit
$("#contactForm")[0].reset();
},
error : function(response){
console.log(response)
}
});
});
This is just a basic example to get started with AJAX with django, if you want to get dive with several more examples, you can go through this article: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django
It means you compiled with e.g. gcc -O3
and the gcc optimiser found that some of your variables were redundant in some way that allowed them to be optimised away. In this particular case you appear to have three variables a, b, c with the same value and presumably they can all be aliassed to a single variable. Compile with optimisation disabled, e.g. gcc -O0
, if you want to see such variables (this is generally a good idea for debug builds in any case).
Also check out the directory where you put .gitignore
.
It should be in the root of your project:
./myproject/.gitignore
Not in
./myproject/.git/.gitignore
If you don't want to use random.choice() you can try this way:
>>> list(myDictionary)[i]
'VENEZUELA'
>>> myDictionary = {'VENEZUELA':'CARACAS', 'IRAN' : 'TEHRAN'}
>>> import random
>>> i = random.randint(0, len(myDictionary) - 1)
>>> myDictionary[list(myDictionary)[i]]
'TEHRAN'
>>> list(myDictionary)[i]
'IRAN'
For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
You may try the following if your database does not have any data OR you have another away to restore that data. You will need to know the Ubuntu server root password but not the mysql root password.
It is highly probably that many of us have installed "mysql_secure_installation" as this is a best practice. Navigate to bin directory where mysql_secure_installation exist. It can be found in the /bin directory on Ubuntu systems. By rerunning the installer, you will be prompted about whether to change root database password.
How host name verification should be done is defined in RFC 6125, which is quite recent and generalises the practice to all protocols, and replaces RFC 2818, which was specific to HTTPS. (I'm not even sure Java 7 uses RFC 6125, which might be too recent for this.)
From RFC 2818 (Section 3.1):
If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.
[...]
In some cases, the URI is specified as an IP address rather than a hostname. In this case, the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI.
Essentially, the specific problem you have comes from the fact that you're using IP addresses in your CN and not a host name. Some browsers might work because not all tools follow this specification strictly, in particular because "most specific" in RFC 2818 isn't clearly defined (see discussions in RFC 6215).
If you're using keytool
, as of Java 7, keytool
has an option to include a Subject Alternative Name (see the table in the documentation for -ext
): you could use -ext san=dns:www.example.com
or -ext san=ip:10.0.0.1
.
EDIT:
You can request a SAN in OpenSSL by changing openssl.cnf
(it will pick the copy in the current directory if you don't want to edit the global configuration, as far as I remember, or you can choose an explicit location using the OPENSSL_CONF
environment variable).
Set the following options (find the appropriate sections within brackets first):
[req]
req_extensions = v3_req
[ v3_req ]
subjectAltName=IP:10.0.0.1
# or subjectAltName=DNS:www.example.com
There's also a nice trick to use an environment variable for this (rather in than fixing it in a configuration file) here: http://www.crsr.net/Notes/SSL.html
There is an option “unlimited scrollback buffer” which you can find under Preferences > Profiles > Terminal
or you can just pump up number of lines that you want to have in history in the same place.
Like this:
<?php
if (isset($_SERVER["HTTP_REFERER"])) {
header("Location: " . $_SERVER["HTTP_REFERER"]);
}
?>
I don't know if this solves your problem but instead of:
$("#tbIntervalos").find("td").attr("id", horaInicial);
you can just do:
$("#tbIntervalos td#" + horaInicial);
If you encounter this error in SourceTree, go to Actions>Resolve Conflicts>Restart Merge.
SourceTree version used is 1.6.14.0
Here's how to get the filepath of the file in Excel 2010.
1) Right click on the Ribbon.
2) Click on "Customize the Ribbon"
3) On the right hand side, click "New Group." This will add a new tab to the Ribbon.
If you want to, click on the "Rename" button the right side and name your tab. For example, I named the tab "Doc Path." This step is optional
4) Under "Choose Commands From" on the left hand side, choose "Commands Not in the Ribbon."
5) Select "Document Location" and "Add" it to your newly created group.
6) The filepath should now appear under the newly created tab on the ribbon.
I've had the same problem, was missing a slash in servlet url in web.xml
replace
<servlet-mapping>
<servlet-name>jsonservice</servlet-name>
<url-pattern>jsonservice</url-pattern>
</servlet-mapping>
with
<servlet-mapping>
<servlet-name>jsonservice</servlet-name>
<url-pattern>/jsonservice</url-pattern>
</servlet-mapping>
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
This does not solve the string in the question since its format is not conforming with RFC 4180; the acceptable encoding is escaping double quote with double quote. The solution below works correctly with CSV files d/l from google spreadsheets.
Parsing single line would be wrong. According to RFC 4180 fields may contain CRLF which will cause any line reader to break the CSV file. Here is an updated version that parses CSV string:
'use strict';_x000D_
_x000D_
function csvToArray(text) {_x000D_
let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;_x000D_
for (l of text) {_x000D_
if ('"' === l) {_x000D_
if (s && l === p) row[i] += l;_x000D_
s = !s;_x000D_
} else if (',' === l && s) l = row[++i] = '';_x000D_
else if ('\n' === l && s) {_x000D_
if ('\r' === p) row[i] = row[i].slice(0, -1);_x000D_
row = ret[++r] = [l = '']; i = 0;_x000D_
} else row[i] += l;_x000D_
p = l;_x000D_
}_x000D_
return ret;_x000D_
};_x000D_
_x000D_
let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"\r\n"2nd line one","two with escaped """" double quotes""","three, with, commas",four with no quotes,"five with CRLF\r\n"';_x000D_
console.log(csvToArray(test));
_x000D_
(Single line solution)
function CSVtoArray(text) {_x000D_
let ret = [''], i = 0, p = '', s = true;_x000D_
for (let l in text) {_x000D_
l = text[l];_x000D_
if ('"' === l) {_x000D_
s = !s;_x000D_
if ('"' === p) {_x000D_
ret[i] += '"';_x000D_
l = '-';_x000D_
} else if ('' === p)_x000D_
l = '-';_x000D_
} else if (s && ',' === l)_x000D_
l = ret[++i] = '';_x000D_
else_x000D_
ret[i] += l;_x000D_
p = l;_x000D_
}_x000D_
return ret;_x000D_
}_x000D_
let test = '"one","two with escaped """" double quotes""","three, with, commas",four with no quotes,five for fun';_x000D_
console.log(CSVtoArray(test));
_x000D_
And for the fun, here is how you create CSV from the array:
function arrayToCSV(row) {_x000D_
for (let i in row) {_x000D_
row[i] = row[i].replace(/"/g, '""');_x000D_
}_x000D_
return '"' + row.join('","') + '"';_x000D_
}_x000D_
_x000D_
let row = [_x000D_
"one",_x000D_
"two with escaped \" double quote",_x000D_
"three, with, commas",_x000D_
"four with no quotes (now has)",_x000D_
"five for fun"_x000D_
];_x000D_
let text = arrayToCSV(row);_x000D_
console.log(text);
_x000D_
With C#6.0 you also have a new way of formatting date when using string interpolation e.g.
$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"
Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.
You can just use Scanner to read word by word, Scanner.next() reads the next word
try {
Scanner s = new Scanner(new File(filename));
while (s.hasNext()) {
System.out.println("word:" + s.next());
}
} catch (IOException e) {
System.out.println("Error accessing input file!");
}
Hibernate is ignorant of time zone stuff in Dates (because there isn't any), but it's actually the JDBC layer that's causing problems. ResultSet.getTimestamp
and PreparedStatement.setTimestamp
both say in their docs that they transform dates to/from the current JVM timezone by default when reading and writing from/to the database.
I came up with a solution to this in Hibernate 3.5 by subclassing org.hibernate.type.TimestampType
that forces these JDBC methods to use UTC instead of the local time zone:
public class UtcTimestampType extends TimestampType {
private static final long serialVersionUID = 8088663383676984635L;
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
@Override
public Object get(ResultSet rs, String name) throws SQLException {
return rs.getTimestamp(name, Calendar.getInstance(UTC));
}
@Override
public void set(PreparedStatement st, Object value, int index) throws SQLException {
Timestamp ts;
if(value instanceof Timestamp) {
ts = (Timestamp) value;
} else {
ts = new Timestamp(((java.util.Date) value).getTime());
}
st.setTimestamp(index, ts, Calendar.getInstance(UTC));
}
}
The same thing should be done to fix TimeType and DateType if you use those types. The downside is you'll have to manually specify that these types are to be used instead of the defaults on every Date field in your POJOs (and also breaks pure JPA compatibility), unless someone knows of a more general override method.
UPDATE: Hibernate 3.6 has changed the types API. In 3.6, I wrote a class UtcTimestampTypeDescriptor to implement this.
public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();
private static final TimeZone UTC = TimeZone.getTimeZone("UTC");
public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicBinder<X>( javaTypeDescriptor, this ) {
@Override
protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
}
};
}
public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
return new BasicExtractor<X>( javaTypeDescriptor, this ) {
@Override
protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
}
};
}
}
Now when the app starts, if you set TimestampTypeDescriptor.INSTANCE to an instance of UtcTimestampTypeDescriptor, all timestamps will be stored and treated as being in UTC without having to change the annotations on POJOs. [I haven't tested this yet]
INSERT INTO def (field_1, field_2, field3)
VALUES
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')
For getting the list of filenames in a specified folder, you can use:
fs.readdir(directory_path, callback_function)
This will return a list which you can parse by simple list indexing like file[0],file[1]
, etc.
If you are using an app which is running on node. you can use webpack as a build tool and use their built in devserver
You can use webpackdevserver to start your application from a localhost server and then pass in your localhost address and port of your choice.
webpack-dev-server --host 192.168.0.89 --port 3000
then from your iPhone you can access it using
Note :: Your laptop and iPhone should be on the same network, and you should use your localhost ip address.
For Mac how to find ip address you can refer Get local IP address in node.js
I am sure that you have found a solution somewhere over the past 2 years but the following is a solution that works for your requested site
package javasandbox;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*
* @author Ryan.Oglesby
*/
public class JavaSandbox {
private static String sURL;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws MalformedURLException, IOException {
sURL = "http://www.cumhuriyet.com.tr/?hn=298710";
System.out.println(sURL);
URL url = new URL(sURL);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
//set http request headers
httpCon.addRequestProperty("Host", "www.cumhuriyet.com.tr");
httpCon.addRequestProperty("Connection", "keep-alive");
httpCon.addRequestProperty("Cache-Control", "max-age=0");
httpCon.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpCon.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
httpCon.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
httpCon.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
//httpCon.addRequestProperty("Cookie", "JSESSIONID=EC0F373FCC023CD3B8B9C1E2E2F7606C; lang=tr; __utma=169322547.1217782332.1386173665.1386173665.1386173665.1; __utmb=169322547.1.10.1386173665; __utmc=169322547; __utmz=169322547.1386173665.1.1.utmcsr=stackoverflow.com|utmccn=(referral)|utmcmd=referral|utmcct=/questions/8616781/how-to-get-a-web-pages-source-code-from-java; __gads=ID=3ab4e50d8713e391:T=1386173664:S=ALNI_Mb8N_wW0xS_wRa68vhR0gTRl8MwFA; scrElm=body");
HttpURLConnection.setFollowRedirects(false);
httpCon.setInstanceFollowRedirects(false);
httpCon.setDoOutput(true);
httpCon.setUseCaches(true);
httpCon.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(httpCon.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
System.out.println(a.toString());
httpCon.disconnect();
}
}
As already mentioned, Chrome Extensions don't allow to have inline JavaScript due to security reasons so you can try this workaround as well.
HTML file
<!doctype html>
<html>
<head>
<title>
Getting Started Extension's Popup
</title>
<script src="popup.js"></script>
</head>
<body>
<div id="text-holder">ha</div><br />
<a class="clickableBtn">
hyhy
</a>
</body>
</html>
<!doctype html>
popup.js
window.onclick = function(event) {
var target = event.target ;
if(target.matches('.clickableBtn')) {
var clickedEle = document.activeElement.id ;
var ele = document.getElementById(clickedEle);
alert(ele.text);
}
}
Or if you are having a Jquery file included then
window.onclick = function(event) {
var target = event.target ;
if(target.matches('.clickableBtn')) {
alert($(target).text());
}
}
You can use LINQ Union method:
dir.GetFiles("*.txt").Union(dir.GetFiles("*.jpg")).ToArray();
I used this code where you subtract 0.5 from the number and when you round it, it is the original number rounded down.
round(a-0.5)
A portion of code originally from Example Depot for listing all of the aliases in a key store:
// Load input stream into keystore
keystore.load(is, password.toCharArray());
// List the aliases
Enumeration aliases = keystore.aliases();
for (; aliases.hasMoreElements(); ) {
String alias = (String)aliases.nextElement();
// Does alias refer to a private key?
boolean b = keystore.isKeyEntry(alias);
// Does alias refer to a trusted certificate?
b = keystore.isCertificateEntry(alias);
}
The exporting of private keys came up on the Sun forums a couple of months ago, and u:turingcompleter came up with a DumpPrivateKey class to stitch into your app.
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
import sun.misc.BASE64Encoder;
public class DumpPrivateKey {
/**
* Provides the missing functionality of keytool
* that Apache needs for SSLCertificateKeyFile.
*
* @param args <ul>
* <li> [0] Keystore filename.
* <li> [1] Keystore password.
* <li> [2] alias
* </ul>
*/
static public void main(String[] args)
throws Exception {
if(args.length < 3) {
throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
}
final String keystoreName = args[0];
final String keystorePassword = args[1];
final String alias = args[2];
final String keyPassword = getKeyPassword(args,keystorePassword);
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
Key key = ks.getKey(alias, keyPassword.toCharArray());
String b64 = new BASE64Encoder().encode(key.getEncoded());
System.out.println("-----BEGIN PRIVATE KEY-----");
System.out.println(b64);
System.out.println("-----END PRIVATE KEY-----");
}
private static String getKeyPassword(final String[] args, final String keystorePassword)
{
String keyPassword = keystorePassword; // default case
if(args.length == 4) {
keyPassword = args[3];
}
return keyPassword;
}
}
Note: this use Sun package, which is a "bad thing".
If you can download apache commons code, here is a version which will compile without warning:
javac -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey.java
and will give the same result:
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyStore;
//import sun.misc.BASE64Encoder;
import org.apache.commons.codec.binary.Base64;
public class DumpPrivateKey {
/**
* Provides the missing functionality of keytool
* that Apache needs for SSLCertificateKeyFile.
*
* @param args <ul>
* <li> [0] Keystore filename.
* <li> [1] Keystore password.
* <li> [2] alias
* </ul>
*/
static public void main(String[] args)
throws Exception {
if(args.length < 3) {
throw new IllegalArgumentException("expected args: Keystore filename, Keystore password, alias, <key password: default same tha
n keystore");
}
final String keystoreName = args[0];
final String keystorePassword = args[1];
final String alias = args[2];
final String keyPassword = getKeyPassword(args,keystorePassword);
KeyStore ks = KeyStore.getInstance("jks");
ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
Key key = ks.getKey(alias, keyPassword.toCharArray());
//String b64 = new BASE64Encoder().encode(key.getEncoded());
String b64 = new String(Base64.encodeBase64(key.getEncoded(),true));
System.out.println("-----BEGIN PRIVATE KEY-----");
System.out.println(b64);
System.out.println("-----END PRIVATE KEY-----");
}
private static String getKeyPassword(final String[] args, final String keystorePassword)
{
String keyPassword = keystorePassword; // default case
if(args.length == 4) {
keyPassword = args[3];
}
return keyPassword;
}
}
You can use it like so:
java -classpath .:commons-codec-1.4/commons-codec-1.4.jar DumpPrivateKey $HOME/.keystore changeit tomcat
List<T>.Remove() and List<T>.RemoveAt() do not return the item that is being removed.
Therefore you have to use this:
var item = list[oldIndex];
list.RemoveAt(oldIndex);
list.Insert(newIndex, item);
I wrote more universal solution based on @Fer answer.
It also should work with flavor and build type based configuration of applicationId
, versionName
, versionCode
.
In the build.gradle:
android {
...
applicationVariants.all { variant ->
variant.outputs.each { output ->
def appId = variant.applicationId
def versionName = variant.versionName
def versionCode = variant.versionCode
def flavorName = variant.flavorName // e. g. free
def buildType = variant.buildType // e. g. debug
def variantName = variant.name // e. g. freeDebug
def apkName = appId + '_' + variantName + '_' + versionName + '_' + versionCode + '.apk';
output.outputFile = new File(output.outputFile.parentFile, apkName)
}
}
}
Example apk name: com.example.app_freeDebug_1.0_1.apk
For more information about variant
variable see ApkVariant and BaseVariant interfaces definition.
$(selector).filter(function(){return this.value==yourval}).remove();
inspect.stack()
returns the current stack rather than the exception traceback:
import inspect
print inspect.stack()
See https://gist.github.com/FredLoney/5454553 for a log_stack utility function.
You need to use *
0 */6 * * * /path/to/mycommand
Also you can refer to https://crontab.guru/ which will help you in scheduling better...
The best on I have found is http://www.auditmypc.com/xml-sitemap.asp which uses Java, and has no limit on pages, and even lets you export results as a raw URL list.
It also uses sessions, so if you are using a CMS, make sure you are logged out before you run the crawl.
awk
awk '{gsub(/two.*/,"")}1' file
Ruby
ruby -ne 'print $_.gsub(/two.*/,"")' file
I also did not know how to do this until I thought of using PHP array
's. And I am pretty sure this is the simplest way of generating a random string or number with array's. The code:
function randstr ($len=10, $abc="aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789") {
$letters = str_split($abc);
$str = "";
for ($i=0; $i<=$len; $i++) {
$str .= $letters[rand(0, count($letters)-1)];
};
return $str;
};
You can use this function like this
randstr(20) // returns a random 20 letter string
// Or like this
randstr(5, abc) // returns a random 5 letter string using the letters "abc"
I use sqlyog to migrate from mssql to mysql. I tried Migration toolkit and workbench but liked sqlyog for its SJA. I could schedule the import process and could do incremental import using WHERE clause.
Without any plugins:
You just need to enable highlight: (Idea v.2016, 2017 and 2018, previous versions may have same or similar settings)
File -> Settings -> Editor -> Inspections -> Java -> Serialization issues -> Serializable class without 'serialVersionUID' - set flag and click 'OK'. (For Macs, Settings is under IntelliJ IDEA -> Preferences...)
Now, if your class implements Serializable
, you will see highlight and alt+Enter on class name will ask you to generate private static final long serialVersionUID
.
UPD: a faster way to find this setting - you might use hotkey Ctrl+Shift+A
(find action), type Serializable class without 'serialVersionUID'
- the first is the one.
There are a lot of different ways to do this in bash.
However, it's important to first note that bash
has many special features (so-called bashisms) that won't work in any other shell.
In particular, arrays, associative arrays, and pattern substitution, which are used in the solutions in this post as well as others in the thread, are bashisms and may not work under other shells that many people use.
For instance: on my Debian GNU/Linux, there is a standard shell called dash; I know many people who like to use another shell called ksh; and there is also a special tool called busybox with his own shell interpreter (ash).
The string to be split in the above question is:
IN="[email protected];[email protected]"
I will use a modified version of this string to ensure that my solution is robust to strings containing whitespace, which could break other solutions:
IN="[email protected];[email protected];Full Name <[email protected]>"
In pure bash
, we can create an array with elements split by a temporary value for IFS (the input field separator). The IFS, among other things, tells bash
which character(s) it should treat as a delimiter between elements when defining an array:
IN="[email protected];[email protected];Full Name <[email protected]>"
# save original IFS value so we can restore it later
oIFS="$IFS"
IFS=";"
declare -a fields=($IN)
IFS="$oIFS"
unset oIFS
In newer versions of bash
, prefixing a command with an IFS definition changes the IFS for that command only and resets it to the previous value immediately afterwards. This means we can do the above in just one line:
IFS=\; read -a fields <<<"$IN"
# after this command, the IFS resets back to its previous value (here, the default):
set | grep ^IFS=
# IFS=$' \t\n'
We can see that the string IN
has been stored into an array named fields
, split on the semicolons:
set | grep ^fields=\\\|^IN=
# fields=([0]="[email protected]" [1]="[email protected]" [2]="Full Name <[email protected]>")
# IN='[email protected];[email protected];Full Name <[email protected]>'
(We can also display the contents of these variables using declare -p
:)
declare -p IN fields
# declare -- IN="[email protected];[email protected];Full Name <[email protected]>"
# declare -a fields=([0]="[email protected]" [1]="[email protected]" [2]="Full Name <[email protected]>")
Note that read
is the quickest way to do the split because there are no forks or external resources called.
Once the array is defined, you can use a simple loop to process each field (or, rather, each element in the array you've now defined):
# `"${fields[@]}"` expands to return every element of `fields` array as a separate argument
for x in "${fields[@]}" ;do
echo "> [$x]"
done
# > [[email protected]]
# > [[email protected]]
# > [Full Name <[email protected]>]
Or you could drop each field from the array after processing using a shifting approach, which I like:
while [ "$fields" ] ;do
echo "> [$fields]"
# slice the array
fields=("${fields[@]:1}")
done
# > [[email protected]]
# > [[email protected]]
# > [Full Name <[email protected]>]
And if you just want a simple printout of the array, you don't even need to loop over it:
printf "> [%s]\n" "${fields[@]}"
# > [[email protected]]
# > [[email protected]]
# > [Full Name <[email protected]>]
In newer versions of bash
, you can also play with the command mapfile
:
mapfile -td \; fields < <(printf "%s\0" "$IN")
This syntax preserve special chars, newlines and empty fields!
If you don't want to include empty fields, you could do the following:
mapfile -td \; fields <<<"$IN"
fields=("${fields[@]%$'\n'}") # drop '\n' added by '<<<'
With mapfile
, you can also skip declaring an array and implicitly "loop" over the delimited elements, calling a function on each:
myPubliMail() {
printf "Seq: %6d: Sending mail to '%s'..." $1 "$2"
# mail -s "This is not a spam..." "$2" </path/to/body
printf "\e[3D, done.\n"
}
mapfile < <(printf "%s\0" "$IN") -td \; -c 1 -C myPubliMail
(Note: the \0
at end of the format string is useless if you don't care about empty fields at end of the string or they're not present.)
mapfile < <(echo -n "$IN") -td \; -c 1 -C myPubliMail
# Seq: 0: Sending mail to '[email protected]', done.
# Seq: 1: Sending mail to '[email protected]', done.
# Seq: 2: Sending mail to 'Full Name <[email protected]>', done.
Or you could use <<<
, and in the function body include some processing to drop the newline it adds:
myPubliMail() {
local seq=$1 dest="${2%$'\n'}"
printf "Seq: %6d: Sending mail to '%s'..." $seq "$dest"
# mail -s "This is not a spam..." "$dest" </path/to/body
printf "\e[3D, done.\n"
}
mapfile <<<"$IN" -td \; -c 1 -C myPubliMail
# Renders the same output:
# Seq: 0: Sending mail to '[email protected]', done.
# Seq: 1: Sending mail to '[email protected]', done.
# Seq: 2: Sending mail to 'Full Name <[email protected]>', done.
If you can't use bash
, or if you want to write something that can be used in many different shells, you often can't use bashisms -- and this includes the arrays we've been using in the solutions above.
However, we don't need to use arrays to loop over "elements" of a string. There is a syntax used in many shells for deleting substrings of a string from the first or last occurrence of a pattern. Note that *
is a wildcard that stands for zero or more characters:
(The lack of this approach in any solution posted so far is the main reason I'm writing this answer ;)
${var#*SubStr} # drops substring from start of string up to first occurrence of `SubStr`
${var##*SubStr} # drops substring from start of string up to last occurrence of `SubStr`
${var%SubStr*} # drops substring from last occurrence of `SubStr` to end of string
${var%%SubStr*} # drops substring from first occurrence of `SubStr` to end of string
As explained by Score_Under:
#
and%
delete the shortest possible matching substring from the start and end of the string respectively, and
##
and%%
delete the longest possible matching substring.
Using the above syntax, we can create an approach where we extract substring "elements" from the string by deleting the substrings up to or after the delimiter.
The codeblock below works well in bash (including Mac OS's bash
), dash, ksh, and busybox's ash:
IN="[email protected];[email protected];Full Name <[email protected]>"
while [ "$IN" ] ;do
# extract the substring from start of string up to delimiter.
# this is the first "element" of the string.
iter=${IN%%;*}
echo "> [$iter]"
# if there's only one element left, set `IN` to an empty string.
# this causes us to exit this `while` loop.
# else, we delete the first "element" of the string from IN, and move onto the next.
[ "$IN" = "$iter" ] && \
IN='' || \
IN="${IN#*;}"
done
# > [[email protected]]
# > [[email protected]]
# > [Full Name <[email protected]>]
Have fun!
WHERE `column` LIKE '%$needle%'
The answer already posted will work. If you want to use the jQuery :not you can do this:
if ($(this).is(':not(:checked)'))
or
if ($(this).attr('checked') == false)
You can also use pyautogui as:
import pyautogui
pyautogui._autoPause(0.05, False)
If the first argument is not None, then it will pause for first argument's seconds, in this example: 0.05 seconds
If the first argument is None, and the second argument is True, then it will sleep for the global pause setting which is set with:
pyautogui.PAUSE = int
If you are wondering about the reason, see the source code:
def _autoPause(pause, _pause):
"""If `pause` is not `None`, then sleep for `pause` seconds.
If `_pause` is `True`, then sleep for `PAUSE` seconds (the global pause setting).
This function is called at the end of all of PyAutoGUI's mouse and keyboard functions. Normally, `_pause`
is set to `True` to add a short sleep so that the user can engage the failsafe. By default, this sleep
is as long as `PAUSE` settings. However, this can be override by setting `pause`, in which case the sleep
is as long as `pause` seconds.
"""
if pause is not None:
time.sleep(pause)
elif _pause:
assert isinstance(PAUSE, int) or isinstance(PAUSE, float)
time.sleep(PAUSE)
Please NOTICE (at least in centos 8) the user who you are assigning listen.owner
and other stuff to it MUST
be in the same POOL with the user for example given I am the foo user
[www] # WRONG | IN MY CASE I WAS UNDER www POOL SO IT WASNT WORKING FOR ME.
[foo] # CORRECT | THE POOL AND THE USER MATCHES.
listen.owner = foo
listen.group = foo
listen.mode = 0660
user = foo
group = foo
I dont know if there's a global pool but after hours of searching I finlly did it.
protected void gvTurnos_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.EmptyDataRow)
{
LinkButton btn = (LinkButton)e.Row.FindControl("btnAgregarVacio");
if (btn != null)
{
btn.Visible = rbFiltroEstatusCampus.SelectedValue == "1" ? true : false;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
Using "Store as a Global Variable" works, but it only gets the final instance of the object, and not the moment the object is being logged (since you're likely wanting to compare changes to the object as they happen). To get the object at its exact point in time of being modified, I use this...
function logObject(object) {
console.info(JSON.stringify(object).replace(/,/g, ",\n"));
}
Call it like so...
logObject(puzzle);
You may want to remove the .replace(/./g, ",\n") regex if your data happens to have comma's in it.
.myDiv {
background-color: red;
width: 100%;
min-height: 100vh;
max-height: 100%;
position: absolute;
top: 0;
left: 0;
margin: 0 auto;
}
Basically, we're fixing the div's position regardless of it's parent, and then position it using margin: 0 auto; and settings its position at the top left corner.
Callback functions are part of the C standard, an therefore also part of C++. But if you are working with C++, I would suggest you use the observer pattern instead: http://en.wikipedia.org/wiki/Observer_pattern
Install request module, using npm install request
In code:
var request = require('request');
var data = '{ "request" : "msg", "data:" {"key1":' + Var1 + ', "key2":' + Var2 + '}}';
var json_obj = JSON.parse(data);
request.post({
headers: {'content-type': 'application/json'},
url: 'http://localhost/PhpPage.php',
form: json_obj
}, function(error, response, body){
console.log(body)
});
Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a /
with a :
just like the windows jvm replaces it with a \
).
However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.
Make sure that your package is installed in your $GOPATH
directory or already inside your workspace/package.
For example: if your $GOPATH = "c:\go"
, make sure that the package inside C:\Go\src\pkgName
text-overflow: ellipsis;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
line-height: 36px;
max-height: 18px;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
I've found a combo of both line-clamp and line-height works :D