Open Project properties by selecting project then go to
View>Properties Windows
and make sure Anonymous Authentication is Enabled
If this is an IIS website that is having the problem, check the Identity property of the advanced settings for the application pool that the site or application uses. You may find that it is set to ApplicationPoolIdentity, and in that case then this is the user that will have to have access to the path.
Or you can go old style and simply set the Identity to Network Service, and give the Network Service user access to the path.
And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?
This is the value of User-Agent, the browser identification string.
For this reason, most Web browsers use a User-Agent string value as follows:
Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:
Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:
Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.
This value will be used to identify what browser is being used by end user.
That's a half-open interval.
[a,b]
includes the end points.(a,b)
excludes them.In your case the end-point at the start of the interval is included, but the end is excluded. So it means the interval "first1 <= x < last1".
Half-open intervals are useful in programming because they correspond to the common idiom for looping:
for (int i = 0; i < n; ++i) { ... }
Here i is in the range [0, n).
See What is the maximum length of a URL in different browsers?
The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.
Try this. It works with me. Hope you too!
List<YOUR_OBJECT> testList = new ArrayList<>();_x000D_
testList.add(test1);_x000D_
_x000D_
Gson gson = new Gson();_x000D_
_x000D_
String json = gson.toJson(testList);_x000D_
_x000D_
Type type = new TypeToken<ArrayList<YOUR_OBJECT>>(){}.getType();_x000D_
_x000D_
ArrayList<YOUR_OBJECT> array = gson.fromJson(json, type);
_x000D_
Try RFS (for responsive font size) library by MartijnCuppens that maybe will be implemented in Bootstrap
sum(list_of_lists, [])
would flatten it.
l = [['image00', 'image01'], ['image10'], []]
print sum(l,[]) # prints ['image00', 'image01', 'image10']
Starting from Java 10:
Set<E> oldSet = Set.of();
Set<E> newSet = Set.copyOf(oldSet);
Set.copyOf()
returns an unmodifiable Set
containing the elements of the given Collection
.
The given Collection
must not be null
, and it must not contain any null
elements.
I found a solution that works for me:
$.fn.setCursorPosition = function(position){
if(this.length == 0) return this;
return $(this).setSelection(position, position);
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
if(this.length == 0) return this;
var input = this[0];
if (input.createTextRange) {
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', selectionEnd);
range.moveStart('character', selectionStart);
range.select();
} else if (input.setSelectionRange) {
input.focus();
input.setSelectionRange(selectionStart, selectionEnd);
}
return this;
}
$.fn.focusEnd = function(){
this.setCursorPosition(this.val().length);
return this;
}
Now you can move the focus to the end of any element by calling:
$(element).focusEnd();
Or you specify the position.
$(element).setCursorPosition(3); // This will focus on the third character.
innerText is the current correct answer for this. The other answers are outdated and incorrect.
document.getElementById('ShowButton').innerText = 'Show filter';
innerHTML also works, and can be used to insert HTML.
As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:
import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*
try{
//get Jenkins instance
def jenkins = Jenkins.instance
//get job Item
def item = jenkins.getItemByFullName("The_JOB_NAME")
println item
// get workspacePath for the job Item
def workspacePath = jenkins.getWorkspaceFor (item)
println workspacePath
def file = new File(workspacePath.toString()+"\\pom.xml")
def pomFile = new XmlSlurper().parse(file)
def pomModules = pomFile.modules.children().join(",")
return pomModules
} catch (Exception ex){
println ex.message
}
I got around this by temporarily rewriting my function to something like this:
IF OBJECT_ID ('[dbo].[fx_dosomething]', 'TF') IS NOT NULL
drop function [dbo].[fx_dosomething];
GO
create FUNCTION dbo.fx_dosomething ( @x numeric )
returns @t table (debug varchar(100), x2 numeric)
as
begin
declare @debug varchar(100)
set @debug = 'printme';
declare @x2 numeric
set @x2 = 0.123456;
insert into @t values (@debug, @x2)
return
end
go
select * from fx_dosomething(0.1)
@Jacob already showed you how to use the Gaussian filter in Matlab, so I won't repeat that.
I would choose filter size to be about 3*sigma in each direction (round to odd integer). Thus, the filter decays to nearly zero at the edges, and you won't get discontinuities in the filtered image.
The choice of sigma depends a lot on what you want to do. Gaussian smoothing is low-pass filtering, which means that it suppresses high-frequency detail (noise, but also edges), while preserving the low-frequency parts of the image (i.e. those that don't vary so much). In other words, the filter blurs everything that is smaller than the filter.
If you're looking to suppress noise in an image in order to enhance the detection of small features, for example, I suggest to choose a sigma that makes the Gaussian just slightly smaller than the feature.
Example for SignalR 2.2.1 (May 2017)
Server
Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1
[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
class Program
{
static IDisposable SignalR;
static void Main(string[] args)
{
string url = "http://127.0.0.1:8088";
SignalR = WebApp.Start(url);
Console.ReadKey();
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
/* CAMEL CASE & JSON DATE FORMATTING
use SignalRContractResolver from
https://stackoverflow.com/questions/30005575/signalr-use-camel-case
var settings = new JsonSerializerSettings()
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc
};
settings.ContractResolver = new SignalRContractResolver();
var serializer = JsonSerializer.Create(settings);
GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
*/
app.MapSignalR();
}
}
[HubName("MyHub")]
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.All.addMessage(name, message);
}
}
}
}
Client
(almost the same as Mehrdad Bahrainy reply)
Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1
namespace ConsoleApplication116_SignalRClient
{
class Program
{
private static void Main(string[] args)
{
var connection = new HubConnection("http://127.0.0.1:8088/");
var myHub = connection.CreateHubProxy("MyHub");
Console.WriteLine("Enter your name");
string name = Console.ReadLine();
connection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
myHub.On<string, string>("addMessage", (s1, s2) => {
Console.WriteLine(s1 + ": " + s2);
});
while (true)
{
Console.WriteLine("Please Enter Message");
string message = Console.ReadLine();
if (string.IsNullOrEmpty(message))
{
break;
}
myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
if (task1.IsFaulted)
{
Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
}
else
{
Console.WriteLine(task1.Result);
}
});
}
}
}).Wait();
Console.Read();
connection.Stop();
}
}
}
This works, array of ArrayList. Give it a try to understand how it works.
import java.util.*;
public class ArrayOfArrayList {
public static void main(String[] args) {
// Put the length of the array you need
ArrayList<String>[] group = new ArrayList[15];
for (int x = 0; x < group.length; x++) {
group[x] = new ArrayList<>();
}
//Add some thing to first array
group[0].add("Some");
group[0].add("Code");
//Add some thing to Secondarray
group[1].add("In here");
//Try to output 'em
System.out.println(group[0]);
System.out.println(group[1]);
}
}
Credits to Kelvincer for some of codes.
I think your overflow should be on the outer container. You can also explicitly set a min width for the columns. Like this:
.search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }
Fiddle: http://jsfiddle.net/5WsEt/
This works as well by adding .getWindow().setLayout(width, height)
after show()
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
}).show().getWindow().setLayout(600,500);
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!
You are on the right track.
On your header set
Content-Type: application/x-www-form-urlencoded
The body of the POST request should be =test
and nothing else. For unknown/variable strings you have to URL encode the value so that way you do not accidentally escape with an input character.
See also POST string to ASP.NET Web Api application - returns null
An IP gives you an quite unreliable location, you could Ajax the location upon load with JS if it isn't critical to have the location at first. (Also, the user need's to give you it's permission to access it.)
And by the way for you fellow googlers for selecting multiple folders in the search input you separate your directories with a comma. Works both for exclude and include
Example: ./src/public/,src/components/
I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.
echo "Testing..."
PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"
eval $PING_CMD
if [[ $? -eq 0 ]]; then
echo "Already connected."
else
echo -n "Waiting for connection..."
while true; do
eval $PING_CMD
if [[ $? -eq 0 ]]; then
echo
echo Connected.
break
else
sleep 0.5
echo -n .
fi
done
fi
I also have a Gist of this script which I'll update with fixes and improvements as needed.
All you have to do is add:
#include <string>
using namespace std;
at the top. (BTW I know this was posted in 2013 but I just wanted to answer)
If your datasets are between 1 and 20GB, you should get a workstation with 48GB of RAM. Then Pandas can hold the entire dataset in RAM. I know its not the answer you're looking for here, but doing scientific computing on a notebook with 4GB of RAM isn't reasonable.
You can also use serializeArray function to do the same.
I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.
add_shortcode( 'seriesposts', 'series_posts' );
function series_posts( $atts )
{ ob_start();
$myseriesoption = get_option( '_myseries', null );
$type = $myseriesoption;
$args=array( 'post_type' => $type, 'post_status' => 'publish', 'posts_per_page' => 5, 'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post();
echo '<li><a href="';
echo the_permalink();
echo '">';
echo the_title();
echo '</a></li>';
endwhile;
echo '</ul>';
}
wp_reset_query();
return ob_get_clean(); }
//this will generate a shortcode function to be used on your site [seriesposts]
Basically you just need to add lines to ~/.gitconfig
[alias]
st = status
ci = commit -v
Or you can use the git config alias command:
$ git config --global alias.st status
On unix, use single quotes if the alias has a space:
$ git config --global alias.ci 'commit -v'
On windows, use double quotes if the alias has a space or a command line argument:
c:\dev> git config --global alias.ci "commit -v"
The alias command even accepts functions as parameters. Take a look at aliases.
Active Record gives you _before_type_cast
attributes which contain the raw attribute data before typecasting. This can be useful for returning error messages with pre-typecast values or just doing validations that aren't possible after typecast.
I would shy away from Daniel Von Fange's suggestion of overriding the accessor, because doing validation in an accessor changes the accessor contract slightly. Active Record has a feature explicitly for this situation. Use it.
use getBoundingClientRect
if $el
is the actual DOM object:
var top = $el.getBoundingClientRect().top;
Fiddle will show that this will get the same value that jquery's offset top will give you
Edit: as mentioned in comments this does not account for scrolled content, below is the code that jQuery uses
https://github.com/jquery/jquery/blob/master/src/offset.js (5/13/2015)
offset: function( options ) {
//...
var docElem, win, rect, doc,
elem = this[ 0 ];
if ( !elem ) {
return;
}
rect = elem.getBoundingClientRect();
// Make sure element is not hidden (display: none) or disconnected
if ( rect.width || rect.height || elem.getClientRects().length ) {
doc = elem.ownerDocument;
win = getWindow( doc );
docElem = doc.documentElement;
return {
top: rect.top + win.pageYOffset - docElem.clientTop,
left: rect.left + win.pageXOffset - docElem.clientLeft
};
}
}
To update a subset of fields, you can use update_fields
:
survey.save(update_fields=["active"])
The update_fields
argument was added in Django 1.5. In earlier versions, you could use the update()
method instead:
Survey.objects.filter(pk=survey.pk).update(active=True)
There's a class of question on SO that sometimes make less than perfect sense, this one is perilously close :-)
Perhaps you could explain your aversion to using one of the two methods you ruled out.
If it's just because you don't want to pepper your code with if
statements or exception catching code, one solution is to use a helper function that will take care of it for you, something like:
static String substring_safe (String s, int start, int len) { ... }
which will check lengths beforehand and act accordingly (either return smaller string or pad with spaces).
Then you don't have to worry about it in your code at all, just call:
String s2 = substring_safe (s, 10, 7);
instead of:
String s2 = s.substring (10,7);
This would work in the case that you seem to be worried about (based on your comments to other answers), not breaking the flow of the code when doing lots of string building stuff.
Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?
In your situation (for your example) it would be:
prompt> git add B
prompt> git commit
Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use
prompt> git reset A
or
prompt> git checkout HEAD -- A
to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).
An even more efficient way is streaming by asking the operating system’s kernel to open a file, then read bytes from it bit by bit. When reading a file per line in Ruby, data is taken from the file 512 bytes at a time and split up in “lines” after that.
By buffering the file’s content, the number of I/O calls is reduced while dividing the file in logical chunks.
Example:
Add this class to your app as a service object:
class MyIO
def initialize(filename)
fd = IO.sysopen(filename)
@io = IO.new(fd)
@buffer = ""
end
def each(&block)
@buffer << @io.sysread(512) until @buffer.include?($/)
line, @buffer = @buffer.split($/, 2)
block.call(line)
each(&block)
rescue EOFError
@io.close
end
end
Call it and pass the :each
method a block:
filename = './somewhere/large-file-4gb.txt'
MyIO.new(filename).each{|x| puts x }
Read about it here in this detailed post:
OK, so thanks to all of the contributors above. I am using .NET 4.6 and we also had the same issue. I spent time debugging System.Net.Http
, specifically the HttpClientHandler
, and found the following:
if (ExecutionContext.IsFlowSuppressed())
{
IWebProxy webProxy = (IWebProxy) null;
if (this.useProxy)
webProxy = this.proxy ?? WebRequest.DefaultWebProxy;
if (this.UseDefaultCredentials || this.Credentials != null || webProxy != null && webProxy.Credentials != null)
this.SafeCaptureIdenity(state);
}
So after assessing that the ExecutionContext.IsFlowSuppressed()
might have been the culprit, I wrapped our Impersonation code as follows:
using (((WindowsIdentity)ExecutionContext.Current.Identity).Impersonate())
using (System.Threading.ExecutionContext.SuppressFlow())
{
// HttpClient code goes here!
}
The code inside of SafeCaptureIdenity
(not my spelling mistake), grabs WindowsIdentity.Current()
which is our impersonated identity. This is being picked up because we are now suppressing flow. Because of the using/dispose this is reset after invocation.
It now seems to work for us, phew!
Just declare a variable like k
or m
or any other you want, now just add this piece of code at the end of your program
k=input("press close to exit")
Here I just assumed k
as variable to pause the program, you can use any variable you like.
This may be interesting for ppl using Primefaces (which uses CLEditor):
document.getElementById('form:somecontainer:editor')
.getElementsByTagName('iframe')[0].contentWindow
.document.onclick = function(){//do something}
I basically just took the answer from Travelling Tech Guy and changed the selection a bit .. ;)
You could use setInterval
for this.
<script type="text/javascript">
function myFunction () {
console.log('Executed!');
}
var interval = setInterval(function () { myFunction(); }, 60000);
</script>
Disable the timer by setting clearInterval(interval)
.
See this Fiddle: http://jsfiddle.net/p6NJt/2/
Based on unlimit's post on How to properly split a CSV using C# split() function? :
string[] tokens = System.Text.RegularExpressions.Regex.Split(paramString, ",");
NOTE: this doesn't handle escaped / nested commas, etc., and therefore is only suitable for certain simple CSV lists.
Your code should work, but I'm aware that answer doesn't help you. You can see a working example here (jsfiddle).
Jquery:
$(document).on('click','#test-element',function(){
alert("You clicked the element with and ID of 'test-element'");
});
As someone already pointed out, you are using an ID instead of a class. If you have more that one element on the page with an ID, then jquery will return only the first element with that ID. There won't be any errors because that's how it works. If this is the problem, then you'll notice that the click event works for the first test-element
but not for any that follow.
If this does not accurately describe the symptoms of the problem, then perhaps your selector is wrong. Your update leads me to believe this is the case because of inspecting an element then clicking the page again and triggering the click. What could be causing this is if you put the event listener on the actual document
instead of test-element
. If so, when you click off the document and back on (like from the developer window back to the document) the event will trigger. If this is the case, you'll also notice the click event is triggered if you click between two different tabs (because they are two different document
s and therefore you are clicking the document.
If neither of these are the answer, posting HTML will go a long way toward figuring it out.
Assuming
value: update_composer
was the issue, try
value: Boolean.valueOf(update_composer)
is there a less cumbersome way in which I can just pass ALL the pipeline parameters to the downstream job
Not that I know of, at least not without using Jenkins API calls and disabling the Groovy sandbox.
$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();
Chrome v50:
Way 1:
Way 2:
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
Using styles.xml (value)
Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.
<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">
<!-- Used for the buttons -->
<item name="colorAccent">@android:color/white</item>
<!-- Used for the title and text -->
<item name="android:textColorPrimary">@color/black</item>
<!-- Used for the background -->
<item name="android:background">#ffffff</item>
<item name="android:colorPrimary">@color/white</item>
<item name="android:colorAccent">@color/white</item>
<item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
</style>
Alternative (Using Java)
@SuppressLint("ResourceAsColor")
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
AlertDialog dialog = new AlertDialog.Builder(view.getContext(), R.style.MyAlertDialogStyle)
.setTitle("Royal Frolics")
.setIcon(R.mipmap.ic_launcher)
.setMessage(message)
.setPositiveButton("OK", (dialog1, which) -> {
//do nothing
result.confirm();
}).create();
Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(R.color.white);
return true;
}
If you prefer a one-liner:
matched_lines = [line for line in my_string.split('\n') if "substring" in line]
For those looking on how to do it when you have an array of elements:
const textInputRefs = useRef<(HTMLDivElement | null)[]>([])
...
const onClickFocus = (event: React.BaseSyntheticEvent, index: number) => {
textInputRefs.current[index]?.focus()
};
...
{items.map((item, index) => (
<textInput
inputRef={(ref) => textInputs.current[index] = ref}
/>
<Button
onClick={event => onClickFocus(event, index)}
/>
}
You should be able to call print("yo!") since there is a constructor for std::string which takes a const char*. These single argument constructors define implicit conversions from their aguments to their class type (unless the constructor is declared explicit which is not the case for std::string). Have you actually tried to compile this code?
void print(std::string input)
{
cout << input << endl;
}
int main()
{
print("yo");
}
It compiles fine for me in GCC. However, if you declared print like this void print(std::string& input)
then it would fail to compile since you can't bind a non-const reference to a temporary (the string would be a temporary constructed from "yo")
Add '.ToString' to improve comparing on ASP.NET MVC
<ul class="nav navbar-nav">
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li>
<li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li>
--
Adding and clarifying Stefano's answer, you can use expressions to dynamically set the values for the conditions in switch, e.g.:
var i = 3
switch (i) {
case ((i>=0 && i<=5) ? i : -1):
console.log('0-5');
break;
case 6: console.log('6');
}
So in your problem, you could do something like:
var varName = "afshin"
switch (varName) {
case (["afshin", "saeed", "larry"].indexOf(varName)+1 && varName):
console.log("hey");
break;
default:
console.log('Default case');
}
Although it is so much DRY...
Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.
I'm going to disagree with the majority here. I think you should learn C before learning C++. It's definitely not necessary, but I think it makes learning C++ a lot easier. C is at the heart of C++. Anything you learn about C is applicable to C++, but C is a lot smaller and easier to learn.
Pick up K&R and read through that. It is short and will give you a sufficient sense of the language. Once you have the basics of pointers and function calls down, you can move on to C++ a little easier.
Give this solution a try
you may have to use div instead of li for that
.DivParent {_x000D_
height: 100px;_x000D_
border: 1px solid lime;_x000D_
white-space: nowrap;_x000D_
}_x000D_
.verticallyAlignedDiv {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
white-space: normal;_x000D_
}_x000D_
.DivHelper {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
height:100%;_x000D_
}
_x000D_
<div class="DivParent">_x000D_
<div class="verticallyAlignedDiv">_x000D_
<p>Isnt it good!</p>_x000D_
_x000D_
</div><div class="DivHelper"></div>_x000D_
</div>
_x000D_
The following script should work for you:
#!/bin/bash
hive -e "insert overwrite local directory '/LocalPath/'
row format delimited fields terminated by ','
select * from Mydatabase,Mytable limit 100"
cat /LocalPath/* > /LocalPath/table.csv
I used limit 100
to limit the size of data since I had a huge table, but you can delete it to export the entire table.
I was having the same issue. tried some of the solutions here but rather than doing all this mumbo-jumbo. I found just setting height constraint is enough.
The previous answers are quite complete regarding what ::
method reference does. To sum up, it provides a way to refer to a method(or constructor) without executing it, and when evaluated, it creates an instance of the functional interface that provides the target type context.
Below are two examples to find an object with the max value in an ArrayList
WITH and WITHOUT the use of ::
method reference. Explanations are in the comments below.
WITHOUT the use of ::
import java.util.*;
class MyClass {
private int val;
MyClass (int v) { val = v; }
int getVal() { return val; }
}
class ByVal implements Comparator<MyClass> {
// no need to create this class when using method reference
public int compare(MyClass source, MyClass ref) {
return source.getVal() - ref.getVal();
}
}
public class FindMaxInCol {
public static void main(String args[]) {
ArrayList<MyClass> myClassList = new ArrayList<MyClass>();
myClassList.add(new MyClass(1));
myClassList.add(new MyClass(0));
myClassList.add(new MyClass(3));
myClassList.add(new MyClass(6));
MyClass maxValObj = Collections.max(myClassList, new ByVal());
}
}
WITH the use of ::
import java.util.*;
class MyClass {
private int val;
MyClass (int v) { val = v; }
int getVal() { return val; }
}
public class FindMaxInCol {
static int compareMyClass(MyClass source, MyClass ref) {
// This static method is compatible with the compare() method defined by Comparator.
// So there's no need to explicitly implement and create an instance of Comparator like the first example.
return source.getVal() - ref.getVal();
}
public static void main(String args[]) {
ArrayList<MyClass> myClassList = new ArrayList<MyClass>();
myClassList.add(new MyClass(1));
myClassList.add(new MyClass(0));
myClassList.add(new MyClass(3));
myClassList.add(new MyClass(6));
MyClass maxValObj = Collections.max(myClassList, FindMaxInCol::compareMyClass);
}
}
Criteria query for dynamically we can construct query based on our inputs..In case of Hql query is the static query once we construct we can't change the structure of the query.
If you're using a Storyboard and you're coming from a push segue, you could also just override shouldPerformSegueWithIdentifier:sender:
.
There is a significant different in how jQuery handles the this variable with a "on" method
$("outer DOM element").on('click',"inner DOM element",function(){
$(this) // refers to the "inner DOM element"
})
If you compare this with :-
$("outer DOM element").click(function(){
$(this) // refers to the "outer DOM element"
})
Try something like this. It works for me. Logg (Class name)
String level= "";
Properties prop = new Properties();
InputStream in =
Logg.class.getResourceAsStream("resources\\config");
if (in != null) {
prop.load(in);
} else {
throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
}
level = prop.getProperty("Level");
use regex [\\[\\]]
-
String str = "[Chrissman-@1]";
String[] temp = str.replaceAll("[\\[\\]]", "").split("-@");
System.out.println("Nickname: " + temp[0] + " | Power: " + temp[1]);
output -
Nickname: Chrissman | Power: 1
Spring has org.springframework.core.io.Resource which is designed for such situations. From context.xml you can pass classpath to the bean
<bean class="test.Test1">
<property name="path" value="classpath:/test/test1.xml" />
</bean>
and you get it in your bean as Resource:
public void setPath(Resource path) throws IOException {
File file = path.getFile();
System.out.println(file);
}
output
D:\workspace1\spring\target\test-classes\test\test1.xml
Now you can use it in new FileReader(file)
params
is for GET-style URL parameters, data
is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.
Your raw post contains JSON data though. requests
can handle JSON encoding for you, and it'll set the correct Content-Type
header too; all you need to do is pass in the Python object to be encoded as JSON into the json
keyword argument.
You could split out the URL parameters as well:
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
then post your data with:
import requests
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, json=data)
The json
keyword is new in requests
version 2.4.2; if you still have to use an older version, encode the JSON manually using the json
module and post the encoded result as the data
key; you will have to explicitly set the Content-Type header in that case:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, data=json.dumps(data), headers=headers)
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:
* Issue a CHECKPOINT command to free up log space in the log file.
* Check the available log space with DBCC SQLPERF('logspace'). If only a small
percentage of your log file is actually been used, you can try a DBCC SHRINKFILE
command. This can however possibly introduce corruption in your database.
* If you have another drive with space available you can try to add a file there in
order to get enough space to attempt to resolve the issue.
Hope this will help you in finding your solution.
using @SyntaxError's answer, https://stackoverflow.com/a/13745199/5134043
I've managed to do this in React; the only way I could figure out was to attach the ondragstart and ondrop methods to a ref, like so:
const panelManagerBody = React.createRef<HTMLDivElement>();
useEffect(() => {
if (panelManagerBody.current) {
panelManagerBody.current.ondragstart = () => false;
panelManagerBody.current.ondrop = () => false;
}
}, [panelManagerBody]);
return (
<div ref={panelManagerBody}>
Works perfectly fine if the first option's value is null. Explanation : The HTML5 will read a null value on button submit. If not null (value attribute), the selected value is assumed not to be null hence the validation would have worked i.e by checking if there's been data in the option tag. Therefore it will not produce the validation method. However, i guess the other side becomes clear, if the value attribute is set to null ie (value = "" ), HTML5 will detect an empty value on the first or rather the default selected option thus giving out the validation message. Thanks for asking. Happy to help. Glad to know if i did.
img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"
I have the same issue with Entity Framework 6.1.3
But with different scenario. My model property is of type nullable DateTime
DateTime? CreatedDate { get; set; }
So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext
:
Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);
For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
You could use a javascript snippit
$(function()
{
// Enable drop menu clicks
$(".nav li > a").off();
});
That will unbind the click event preventing url changing.
Use two single-quotes
SQL> SELECT 'D''COSTA' name FROM DUAL;
NAME
-------
D'COSTA
Alternatively, use the new (10g+) quoting method:
SQL> SELECT q'$D'COSTA$' NAME FROM DUAL;
NAME
-------
D'COSTA
import h5py
filename = "file.hdf5"
with h5py.File(filename, "r") as f:
# List all groups
print("Keys: %s" % f.keys())
a_group_key = list(f.keys())[0]
# Get the data
data = list(f[a_group_key])
import h5py
# Create random data
import numpy as np
data_matrix = np.random.uniform(-1, 1, size=(10, 3))
# Write data to HDF5
with h5py.File("file.hdf5", "w") as data_file:
data_file.create_dataset("group_name", data=data_matrix)
See h5py docs for more information.
For your application, the following might be important:
See also: Comparison of data serialization formats
In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python
Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.
Use this markup:
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
with the following CSS:
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:100%;
}
and you should be done!
In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:
.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }
It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.
What fixed it for me: dig down to the specific solution for the project you want i.e NOT the overall solution file for all the projects.
Do try - I tried everything else mentioned here but to no avail.
Try this,
add inplace=True
import numpy as np
df.replace(np.NaN, ' ', inplace=True)
we can use Outputstream to output our Object to internal memory. And convert to string then save in preference. For example:
mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor ed = mPrefs.edit();
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutput;
try {
objectOutput = new ObjectOutputStream(arrayOutputStream);
objectOutput.writeObject(object);
byte[] data = arrayOutputStream.toByteArray();
objectOutput.close();
arrayOutputStream.close();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Base64OutputStream b64 = new Base64OutputStream(out, Base64.DEFAULT);
b64.write(data);
b64.close();
out.close();
ed.putString(key, new String(out.toByteArray()));
ed.commit();
} catch (IOException e) {
e.printStackTrace();
}
when we need to extract Object from Preference. Use the code as below
byte[] bytes = mPrefs.getString(indexName, "{}").getBytes();
if (bytes.length == 0) {
return null;
}
ByteArrayInputStream byteArray = new ByteArrayInputStream(bytes);
Base64InputStream base64InputStream = new Base64InputStream(byteArray, Base64.DEFAULT);
ObjectInputStream in;
in = new ObjectInputStream(base64InputStream);
MyObject myObject = (MyObject) in.readObject();
You can tell EF which properties have to be updated in this way:
public void ChangePassword(int userId, string password)
{
var user = new User { Id = userId, Password = password };
using (var context = new ObjectContext(ConnectionString))
{
var users = context.CreateObjectSet<User>();
users.Attach(user);
context.ObjectStateManager.GetObjectStateEntry(user)
.SetModifiedProperty("Password");
context.SaveChanges();
}
}
Set the foreign key as a primary key, and then set the relationship on both primary key fields. That's it! You should see a key sign on both ends of the relationship line. This represents a one to one.
Check this : SQL Server Database Design with a One To One Relationship
for my example:
Windows XP ---> Synology:DS218+
Step2:
Enable Telnet service (?? Telnet ??)
or Enable SSH Service (?? SSH ??)
Step3: Launch the terminal on Windows (or via executing cmd
to launch the terminal)
Step4: type: telnet your_nas_ip_or_domain_name, like below telnet 192.168.1.104
Fzz login: tsungjung411 Password: # shows the current working directory (?????????) $ pwd /var/services/homes/tsungjung411 # edit a Java file (via vi), then compile and run it # (?? vi ?? Java ??,???????) $ vi Main.java # show the file content (??????) $ cat Main.java public class Main { public static void main(String [] args) { System.out.println("hello, World!"); } } # compiles the Java file (?? Java ??) javac Main.java # executes the Java file (?? Java ??) $ java Main hello, World! # shows the file list (??????) $ ls CloudStation Main.class Main.java www
# shows the JRE version on this Synology Disk Station $ java -version openjdk version "1.8.0_151" OpenJDK Runtime Environment (IcedTea 3.6.0) (linux-gnu build 1.8.0_151-b12) OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)
$ python Python 2.7.12 (default, Nov 10 2017, 20:30:30) [GCC 4.9.3 20150311 (prerelease)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import sys >>> >>> # shows the the python version >>> print(sys.version) 2.7.12 (default, Nov 10 2017, 20:30:30) [GCC 4.9.3 20150311 (prerelease)] >>> >>> import os >>> >>> # shows the current working directory >>> print(os.getcwd()) /volume1/homes/tsungjung411
$ # launch Python 3 $ python3 Python 3.5.1 (default, Dec 9 2016, 00:20:03) [GCC 4.9.3 20150311 (prerelease)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
'a' in vars() or 'a' in globals()
if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)
using str.replace(regex, $1);
:
var str = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
if (str.match(regex)) {
str = str.replace(regex, "$1" + "1" + "$2");
}
Edit: adaptation regarding the comment
//this is the code you have to use in you controller
$config['upload_path'] = './uploads/';
// directory (http://localhost/codeigniter/index.php/your directory)
$config['allowed_types'] = 'gif|jpg|png|jpeg';
//Image type
$config['max_size'] = 0;
// I have chosen max size no limit
$new_name = time() . '-' . $_FILES["txt_file"]['name'];
//Added time function in image name for no duplicate image
$config['file_name'] = $new_name;
//Stored the new name into $config['file_name']
$this->load->library('upload', $config);
if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('production/create_images', $error);
} else {
$upload_data = $this->upload->data();
}
It's possible with const qualifier for State:
virtual const ULONG Write(const ULONG &State = 0, bool sequence = true);
I was having a problem on Ubuntu 18.04 on Mysql. When I needed to create a new user, the policy was always high.
The way I figured out how to disable, for future colleagues who come to investigate, was set to low.
Login to the mysql server as root
mysql -h localhost -u root -p
Set the new type of validation
SET GLOBAL validate_password_policy=0; //For Low
Restart mysql
sudo service mysql restart
Swift 3.0 very simple implementation would be:
func dateByAddingDays(inDays: Int) -> Date {
let today = Date()
return Calendar.current.date(byAdding: .day, value: inDays, to: today)!
}
Use elevation to implement shadows on RN Android. Added elevation prop #27
<View elevation={5}>
</View>
UITextView
does not have any methods which will be called when the user hits the return key. If you want the user to be able to add only one line of text, use a UITextField
. Hitting the return and hiding the keyboard for a UITextView
does not follow the interface guidelines.
Even then if you want to do this, implement the textView:shouldChangeTextInRange:replacementText:
method of UITextViewDelegate
and in that check if the replacement text is \n
, hide the keyboard.
There might be other ways but I am not aware of any.
At onCreate
of your Activity, just add use clearFocus()
on your EditText element.
For example,
edittext = (EditText) findViewById(R.id.edittext);
edittext.clearFocus();
And if you want to divert the focus to another element, use requestFocus()
on that.
For example,
button = (Button) findViewById(R.id.button);
button.requestFocus();
I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP
How to update your forked repo on your local machine?
First, check your remote/master
git remote -v
You should have origin and upstream. For example:
origin https://github.com/your___name/kredis.git (fetch)
origin https://github.com/your___name/kredis.git (push)
upstream https://github.com/rails/kredis.git (fetch)
upstream https://github.com/rails/kredis.git (push)
After that go to main:
git checkout main
and merge from upstream to main:
git merge upstream/main
If you have tried .attr("value", "")
and didn't work, don't panic (like I did)
just do .val("")
instead, and will work fine
Accepted answer didn't work for me, this does:
https://www.facebook.com/app_scoped_user_id/10152384781676191
The deduplication (to select the max T1) and the aggregation need to be done as distinct steps. I've used a CTE since I think this makes it clearer:
;WITH sumCTE
AS
(
SELECT Rel.t2ID, SUM(Price) price
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
GROUP
BY Rel.t2ID
)
,maxCTE
AS
(
SELECT Rel.t2ID, Rel.t1ID,
ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
FROM @t1 AS T1
JOIN @relation AS Rel
ON Rel.t1ID=T1.ID
)
SELECT T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,sumT1.Price
FROM @t2 AS T2
JOIN sumCTE AS sumT1
ON sumT1.t2ID = t2.ID
JOIN maxCTE AS maxT1
ON maxT1.t2ID = t2.ID
JOIN @t1 AS T1
ON T1.ID = maxT1.t1ID
WHERE maxT1.PriceList = 1
Note that, in addition to number of predictive variables, the Adjusted R-squared formula above also adjusts for sample size. A small sample will give a deceptively large R-squared.
Ping Yin & Xitao Fan, J. of Experimental Education 69(2): 203-224, "Estimating R-squared shrinkage in multiple regression", compares different methods for adjusting r-squared and concludes that the commonly-used ones quoted above are not good. They recommend the Olkin & Pratt formula.
However, I've seen some indication that population size has a much larger effect than any of these formulas indicate. I am not convinced that any of these formulas are good enough to allow you to compare regressions done with very different sample sizes (e.g., 2,000 vs. 200,000 samples; the standard formulas would make almost no sample-size-based adjustment). I would do some cross-validation to check the r-squared on each sample.
import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.
This is an old post, but I thought I should provide an illustrated answer anyway.
Use javascript's object notation. Like so:
states_dictionary={
"CT":["alex","harry"],
"AK":["liza","alex"],
"TX":["fred", "harry"]
};
And to access the values:
states_dictionary.AK[0] //which is liza
or you can use javascript literal object notation, whereby the keys not require to be in quotes:
states_dictionary={
CT:["alex","harry"],
AK:["liza","alex"],
TX:["fred", "harry"]
};
I tried the win32com way and xlwings way but I didn't get any luck. I use PyCharm and didn't see the .WorkBook option in the autocompletion for win32com. I got the -2147352567 error when I tried to pass a workbook as variable.
Then, I found a work around using vba shell to run my Python script. Write something on the XLS file you are working with when everything is done. So that Excel knows that it's time to run the VBA macro.
But the vba Application.wait function will take up 100% cpu which is wierd. Some people said that using the windows Sleep function would fix it.
Import xlsxwriter
Shell "C:\xxxxx\python.exe
C:/Users/xxxxx/pythonscript.py"
exitLoop = 0
wait for Python to finish its work.
Do
waitTime = TimeSerial(Hour(Now), Minute(Now), Second(Now) + 30)
Application.Wait waitTime
Set wb2 = Workbooks.Open("D:\xxxxx.xlsx", ReadOnly:=True)
exitLoop = wb2.Worksheets("blablabla").Cells(50, 1)
wb2.Close exitLoop
Loop While exitLoop <> 1
Call VbaScript
Sharing my version of the great answer from @bulltorious, updated for newer angular builds (I used version 1.5.8 with this code), and also incorporated @JMaylin's idea of using a counter so as to be robust to multiple simultaneous requests, and the option to skip showing the animation for requests taking less than some minimum number of milliseconds:
var app = angular.module('myApp');
var BUSY_DELAY = 1000; // Will not show loading graphic until 1000ms have passed and we are still waiting for responses.
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('busyHttpInterceptor');
})
.factory('busyHttpInterceptor', ['$q', '$timeout', function ($q, $timeout) {
var counter = 0;
return {
request: function (config) {
counter += 1;
$timeout(
function () {
if (counter !== 0) {
angular.element('#busy-overlay').show();
}
},
BUSY_DELAY);
return config;
},
response: function (response) {
counter -= 1;
if (counter === 0) {
angular.element('#busy-overlay').hide();
}
return response;
},
requestError: function (rejection) {
counter -= 1;
if (counter === 0) {
angular.element('#busy-overlay').hide();
}
return rejection;
},
responseError: function (rejection) {
counter -= 1;
if (counter === 0) {
angular.element('#busy-overlay').hide();
}
return rejection;
}
}
}]);
Here's a quote from a recent blog post from Dare Obasanjo.
SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.
However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.
To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.
Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.
Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)
I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL
Try doing: INSERT INTO table(data, date) VALUES ('$data', now() + interval 1 day)
This solution builds upon previous solutions, but takes into account both metric and binary units:
function formatBytes(bytes, decimals, binaryUnits) {
if(bytes == 0) {
return '0 Bytes';
}
var unitMultiple = (binaryUnits) ? 1024 : 1000;
var unitNames = (unitMultiple === 1024) ? // 1000 bytes in 1 Kilobyte (KB) or 1024 bytes for the binary version (KiB)
['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']:
['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var unitChanges = Math.floor(Math.log(bytes) / Math.log(unitMultiple));
return parseFloat((bytes / Math.pow(unitMultiple, unitChanges)).toFixed(decimals || 0)) + ' ' + unitNames[unitChanges];
}
Examples:
formatBytes(293489203947847, 1); // 293.5 TB
formatBytes(1234, 0); // 1 KB
formatBytes(4534634523453678343456, 2); // 4.53 ZB
formatBytes(4534634523453678343456, 2, true)); // 3.84 ZiB
formatBytes(4566744, 1); // 4.6 MB
formatBytes(534, 0); // 534 Bytes
formatBytes(273403407, 0); // 273 MB
I would use the SET command from the command prompt to export all the variables, rather than just PATH as recommended above.
C:\> SET >> allvariables.txt
To import the variablies, one can use a simple loop:
C:\> for /F %A in (allvariables.txt) do SET %A
As stated in other answers, label is an inline element. However, you can apply display: inline-block
to the label and then center with text-align
.
#name_label {
display: inline-block;
width: 90%;
text-align: right;
}
Why display: inline-block
and not display: inline
? For the same reason that you can't align label
, it's inline.
Why display: inline-block
and not display: block
? You could use display: block
, but it will be on another line. display: inline-block
combines the properties of inline
and block
. It's inline, but you can also give it a width, height, and align it.
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
Only JWT's privateKey, which is on your server will decrypt the encrypted JWT. Those who know the privateKey will be able to decrypt the encrypted JWT.
Hide the privateKey in a secure location in your server and never tell anyone the privateKey.
I found a simple solution, try this:
var Ocasiao = "";
$('#ctl00_rdlOcasioesMarcas input').each(function() { if (this.checked) { Ocasiao = this.value } });
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
Assuming that you are using UTF-8 encoding:
string convert = "This is the string to be converted";
// From string to byte array
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(convert);
// From byte array to string
string s = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);
We have set compatibility mode for IE11 to resolve an issue: Settings>Compatibility View Settings>Add your site name or Check "Display intranet sites in Compatibility View" if your portal is in the intranet.
IE version 11.0.9600.16521
Worked for us, hope this helps someone.
What you could do is, create the "function" as another template file and then include that file passing the parameters to it.
Inside index.html
<h3> Latest Songs </h3>
{% include "song_player_list.html" with songs=latest_songs %}
Inside song_player_list.html
<ul>
{% for song in songs %}
<li>
<div id='songtile'>
<a href='/songs/download/{{song.id}}/'><i class='fa fa-cloud-download'></i> Download</a>
</div>
</li>
{% endfor %}
</ul>
See this: http://en.wikipedia.org/wiki/URI_scheme#Generic_syntax
foo://username:[email protected]:8042/over/there/index.dtb;type=animal?name=ferret#nose
\ / \________________/\_________/ \__/ \___/ \_/ \_________/ \_________/ \__/
| | | | | | | | |
| userinfo hostname port | | parameter query fragment
| \_______________________________/ \_____________|____|____________/
scheme | | | |
| authority |path|
| | |
| path interpretable as filename
| ___________|____________ |
/ \ / \ |
urn:example:animal:ferret:nose interpretable as extension
An absolute URL includes the parts before the "path" part - in other words, it includes the scheme (the http
in http://foo/bar/baz
) and the hostname (the foo
in http://foo/bar/baz
) (and optionally port, userinfo and port).
Relative URLs start with a path.
Absolute URLs are, well, absolute: the location of the resource can be resolved looking only at the URL itself. A relative URL is in a sense incomplete: to resolve it, you need the scheme and hostname, and these are typically taken from the current context. For example, in a web page at
http://myhost/mypath/myresource1.html
you could put a link like so
<a href="pages/page1">click me</a>
In the href
attribute of the link, a relative URLs used, and if it is clicked, it has to be resolved in order to follow it. In this case, the current context is
http://myhost/mypath/myresource1.html
so the schema, hostname, and leading path of these are taken and prepended to pages/page1
, yielding
http://myhost/mypath/pages/page1
If the link would have been:
<a href="/pages/page1">click me</a>
(note the /
appearing at the start of the URL) then it would have been resolved as
http://myhost/pages/page1
because the leading /
indicates the root of the host.
In a webapplication, I would advise to use relative URLs for all resources that belong to your app. That way, if you change the location of the pages, everything will continue to work. Any external resources (could be pages completely outside your application, but also static content that you deliver through a content delivery network) should always be pointed to using absolute URLs: if you don't there simply is no way to locate them, because they reside on a different server.
Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.
_dsACL.Documents.FirstOrDefault(o => o.ID == id);
For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.
I had trouble in IE10+ downloading a PDF and used @dandavis' download
function (https://github.com/rndme/download).
IE10+ needs msSaveBlob
.
Try this one:
public boolean isTableExists(String tableName, boolean openDb) {
if(openDb) {
if(mDatabase == null || !mDatabase.isOpen()) {
mDatabase = getReadableDatabase();
}
if(!mDatabase.isReadOnly()) {
mDatabase.close();
mDatabase = getReadableDatabase();
}
}
String query = "select DISTINCT tbl_name from sqlite_master where tbl_name = '"+tableName+"'";
try (Cursor cursor = mDatabase.rawQuery(query, null)) {
if(cursor!=null) {
if(cursor.getCount()>0) {
return true;
}
}
return false;
}
}
An old question, but still valid.
My approach is to create a new interface and class to wrap the System.DateTime.Now
call
public interface INow
{
DateTime Execute();
}
public sealed class Now : INow
{
public DateTime Execute()
{
return DateTime.Now
}
}
This interface can be injected into any class that needs to get the current date and time. In this example, I have a class that adds a timespan to the current date and time (a unit testable System.DateTime.Now.Add(TimeSpan))
public interface IAddTimeSpanToCurrentDateAndTime
{
DateTime Execute(TimeSpan input);
}
public class AddTimeSpanToCurrentDateAndTime : IAddTimeSpanToCurrentDateAndTime
{
private readonly INow _now;
public AddTimeSpanToCurrentDateAndTime(INow now)
{
this._now = now;
}
public DateTime Execute(TimeSpan input)
{
var currentDateAndTime = this._now.Execute();
return currentDateAndTime.Add(input);
}
}
And tests can be written to ensure that it functions correctly. I'm using NUnit and Moq but any test framework will do
public class Execute
{
private Moq.Mock<INow> _nowMock;
private AddTimeSpanToCurrentDateAndTime _systemUnderTest;
[SetUp]
public void Initialize()
{
this._nowMock = new Moq.Mock<INow>(Moq.MockBehavior.Strict);
this._systemUnderTest = AddTimeSpanToCurrentDateAndTime(
this._nowMock.Object);
}
[Test]
public void AddTimeSpanToCurrentDateAndTimeExecute0001()
{
// arrange
var input = new TimeSpan(911252);
// arrange : mocks
this._nowMock
.Setup(a => a.Execute())
.Returns(new DateTime(348756););
// arrange : expected
var expected = new DateTime(911252 + 348756);
// act
var actual = this._systemUnderTest.Execute(input).Result;
// assert
Assert.Equals(actual, expected);
}
}
This pattern will work for any functions which depend on external factors, like System.Random.Next()
, System.DateTime.Now.UtcNow
, System.Guid.NewGuid()
etc.
See https://loadlimited.visualstudio.com/Stamina/_git/Stamina.Core for further examples or get the https://www.nuget.org/packages/Stamina.Core nuget package.
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
Use cut:
cut -d <The character between characters> -f <number of first column>,<number of last column> <file name>
e.g.: If you have file1
containing : car.is.nice.equal.bmw
Run : cut -d . -f1,3 file1
will print car.is.nice
For me it was a certificate problem. Following worked for me
$context = stream_context_create([
'ssl' => [
// set some SSL/TLS specific options
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
$client = new SoapClient(null, [
'location' => 'https://...',
'uri' => '...',
'stream_context' => $context
]);
This is just an add-on to the solution in case you want to compute not only unique values but other aggregate functions:
df.groupby(['group']).agg(['min','max','count','nunique'])
Hope you find it useful
you can use webview to show the pdf inside an application , for that you have to :
Many pdf to html online converter available.
Example:
consent_web = (WebView) findViewById(R.id.consentweb);
consent_web.getSettings().setLoadWithOverviewMode(true);
consent_web.getSettings().setUseWideViewPort(true);
consent_web.loadUrl("file:///android_asset/spacs_html.html");
In my case, the problem was that the phpMyAdmin version was specified wrongly in the phpmyadmin.conf
file. You may check that:
Go to wamp/apps/phpmyadmin3.x.x: notice the file name - what version you are currently using?
Open file wamp/alias/phpmyadmin.conf:
Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all
Check the first line (directory "c:/wamp/apps/phpmyadmin3.x.x/") is the file name exactly the same as your actual file name.
Make sure the directory file name is absolutely correct.
Yes, this is possible now in browsers also. Chrome release this feature in version 84 and above. With the help of WEBOTP API, we can detect OTP on the web for mobile devices.
Here is a Web-OTP integrated code with Angular PWA Apps: https://github.com/Rohit3230/webOtpAutoReadByAngular
Go for live working URL for angular PWA app. https://rohit3230.github.io/webOtpAutoReadByAngular/
$("#selectID option:selected").each(function(){
$(this).removeAttr("selected");
});
This would iterate through each item and unselect only the ones which are checked
In Ubuntu (at least 12.04) it seems sendmail is not installed by default. You will have to install it using the command
sudo apt-get install sendmail-bin
You may also need to configure the proper permissions for it as mentioned above.
// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
simply try this 'listBox' is your list and 'yu' is a veriable to which the value on index 0 will be assigned
string yu = listBox1.Items[0].ToString();
MessageBox.Show(yu);
I won't stress much on the difference as it is already covered, but notice the below:
android:backgroundTint
android:backgroundTintMode
are only available at API 21android:background
, and you want to change its default color, then you can use android:backgroundTint
to add a shade to it.example
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email" />
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email"
android:backgroundTint="@color/colorAccent" />
Another example
If you try to change the accent color of the FloatingActionButton
using android:background
you won't notice a change, that is because it's already utilizes app:srcCompat
, so in order to do that you can use android:backgroundTint
instead
My solution was to remove the entity framework from the project via the nuget manager and add it back in.
This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,
class Myclass {
int a;
class SubClass {
int b;
}
}
With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,
MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String
Now you can pass this String across activities as a StringExtra with the activity intent.
Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);
Then in the receiving activity, create the original object from the string representation.
String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object
It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.
UPDATE
While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.
There is also a simple answer for defining specific styles that are only going to be applied to that specific button and you can have Jquery declare element style when declaring the dialog:
id: "button-delete",
text: "Delete",
style: "display: none;",
click: function () {}
after doing that here is what the html shows:
doing this allows you to set it, but it is not necessarily easy to change using jquery later.
With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.
var json = Json.Encode(new {
orientation = Cache["orientation"],
alerted = Cache["alerted"] as bool?,
since = Cache["since"] as DateTime?
});
Response.Write(json);
I had problems with this recently, i use this code and work fine for me.
var data = 'Peter';
db.User.find({'name' : new RegExp(data, 'i')}, function(err, docs){
cb(docs);
});
Use directly /Peter/i
work, but i use '/'+data+'/i'
and not work for me.
As an extension to Jonathan Leffler's Unix to DOS solution, to safely convert to DOS when you're unsure of the file's current line endings:
sed '/^M$/! s/$/^M/'
This checks that the line does not already end in CRLF before converting to CRLF.
Despite what the Accepted answer says, you actually CAN do what you were intending to do, but you need to set it up as a configurable provider, so that it's available as a service during the configuration phase.. First, change your Service
to a provider as shown below. The key difference here is that after setting the value of defer
, you set the defer.promise
property to the promise object returned by $http.get
:
Provider Service: (provider: service recipe)
app.provider('dbService', function dbServiceProvider() {
//the provider recipe for services require you specify a $get function
this.$get= ['dbhost',function dbServiceFactory(dbhost){
// return the factory as a provider
// that is available during the configuration phase
return new DbService(dbhost);
}]
});
function DbService(dbhost){
var status;
this.setUrl = function(url){
dbhost = url;
}
this.getData = function($http) {
return $http.get(dbhost+'db.php/score/getData')
.success(function(data){
// handle any special stuff here, I would suggest the following:
status = 'ok';
status.data = data;
})
.error(function(message){
status = 'error';
status.message = message;
})
.then(function(){
// now we return an object with data or information about error
// for special handling inside your application configuration
return status;
})
}
}
Now, you have a configurable custom Provider, you just need to inject it. Key difference here being the missing "Provider on your injectable".
config:
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
dbData: function(DbService, $http) {
/*
*dbServiceProvider returns a dbService instance to your app whenever
* needed, and this instance is setup internally with a promise,
* so you don't need to worry about $q and all that
*/
return DbService('http://dbhost.com').getData();
}
}
})
});
use resolved data in your appCtrl
app.controller('appCtrl',function(dbData, DbService){
$scope.dbData = dbData;
// You can also create and use another instance of the dbService here...
// to do whatever you programmed it to do, by adding functions inside the
// constructor DbService(), the following assumes you added
// a rmUser(userObj) function in the factory
$scope.removeDbUser = function(user){
DbService.rmUser(user);
}
})
The following alternative is a similar approach, but allows definition to occur within the .config
, encapsulating the service to within the specific module in the context of your app. Choose the method that right for you. Also see below for notes on a 3rd alternative and helpful links to help you get the hang of all these things
app.config(function($routeProvider, $provide) {
$provide.service('dbService',function(){})
//set up your service inside the module's config.
$routeProvider
.when('/', {
templateUrl: "partials/editor.html",
controller: "AppCtrl",
resolve: {
data:
}
})
});
$http
specific in the context of this requestfactory
/service
/provider
at clevertech.biz.The provider gives you a bit more configuration over the .service
method, which makes it better as an application level provider, but you could also encapsulate this within the config object itself by injecting $provide
into config like so:
Although Mongodb does not provide the rename Database command, it provides the rename Collection command, which not only modifies the collection name, but also modifies the database name.
{ renameCollection: "<source_namespace>", to: "<target_namespace>", dropTarget: <true|false> writeConcern: <document> }
db.adminCommand({renameCollection: "db1.test1", to: "db2.test2"})
This command only modifies the metadata, the cost is very small, we only need to traverse all the collections under db1
, renamed to db2
to achieve rename Database name.
you can do it in this Js script
var source = "source";
var dest = "dest";
var colls = db.getSiblingDB(source).getCollectionNames();
for (var i = 0; i < colls.length; i++) {
var from = source + "." + colls[i];
var to = dest + "." + colls[i];
db.adminCommand({renameCollection: from, to: to});
}
Be careful when you use this command
renameCollection has different performance implications depending on the target namespace.
If the target database is the same as the source database, renameCollection simply changes the namespace. This is a quick operation.
If the target database differs from the source database, renameCollection copies all documents from the source collection to the target collection. Depending on the size of the collection, this may take longer to complete.
In a Python interpreter or script, you can do
import site
site.getsitepackages() # List of global package locations
and
site.getusersitepackages() # String for user-specific package location
For locations third-party packages (those not in the core Python distribution) are installed to.
On my Homebrew-installed Python on macOS, the former outputs
['/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']
,
which canonicalizes to the same path output by pip show
, as mentioned in a previous answer:
$ readlink -f /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
/usr/local/lib/python3.7/site-packages
Reference: https://docs.python.org/3/library/site.html#site.getsitepackages
You can use
String hex = String.format("#%02x%02x%02x", r, g, b);
Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF
vs. #ffffff
).
Generally, it's considered a bad practice to style standard form controls because the output looks so different on each browser. See: http://www.456bereastreet.com/lab/styling-form-controls-revisited/select-single/ for some rendered examples.
That being said, I've had some luck making the background color an RGBA value:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background: #d00;
}
select {
background: rgba(255,255,255,0.1) url('http://www.google.com/images/srpr/nav_logo6g.png') repeat-x 0 0;
padding:4px;
line-height: 21px;
border: 1px solid #fff;
}
</style>
</head>
<body>
<select>
<option>Foo</option>
<option>Bar</option>
<option>Something longer</option>
</body>
</html>
Google Chrome still renders a gradient on top of the background image in the color that you pass to rgba(r,g,b,0.1) but choosing a color that compliments your image and making the alpha 0.1 reduces the effect of this.
None of the solutions worked for me. If you are using PIP do:
pip install pycrypto==2.6.1
Did you restart the server after you changed the config file?
Can you telnet to the server from a different machine?
Can you telnet to the server from the server itself?
telnet <ip address> 80
telnet localhost 80
if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")
To check an ajax request you can use if (Request::ajax())
Note: If you are using laravel 5, then in the controller replace
use Illuminate\Http\Request;
with
use Request;
I hope it'll work.
For server/protocol errors I would try to be as REST/HTTP as possible (Compare this with you typing in URL's in your browser):
For domain/business logic specific errors I would say the protocol is used in the right way and there's no server internal error, so respond with an error JSON/XML object or whatever you prefer to describe your data with (Compare this with you filling in forms on a website):
Basically you can’t put an icon inside of a textInput but you can fake it by wrapping it inside a view and setting up some simple styling rules.
Here's how it works:
Code:
<View style={styles.passwordContainer}>
<TextInput
style={styles.inputStyle}
autoCorrect={false}
secureTextEntry
placeholder="Password"
value={this.state.password}
onChangeText={this.onPasswordEntry}
/>
<Icon
name='what_ever_icon_you_want'
color='#000'
size={14}
/>
</View>
Style:
passwordContainer: {
flexDirection: 'row',
borderBottomWidth: 1,
borderColor: '#000',
paddingBottom: 10,
},
inputStyle: {
flex: 1,
},
(Note: the icon is underneath the TextInput so it appears on the far right, if it was above TextInput it would appear on the left.)
This ERROR can happen when you use Mockito to mock final classes.
Consider using Mockito inline or Powermock instead.
For casting varchar fields/values to number format can be little hack used:
SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`
Or simply use
word-wrap: break-word;
supported in IE 5.5+, Firefox 3.5+, and WebKit browsers such as Chrome and Safari.
Both the verifyNoMoreInteractions()
and verifyZeroInteractions()
method internally have the same implementation as:
public static transient void verifyNoMoreInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
public static transient void verifyZeroInteractions(Object mocks[])
{
MOCKITO_CORE.verifyNoMoreInteractions(mocks);
}
so we can use any one of them on mock object or array of mock objects to check that no methods have been called using mock objects.
Well, data.str().c_str()
yields a char const*
but your function Printfunc()
wants to have char*
s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be
void Printfunc(int a, char const* loc, char const* stream)
The alternative might be to turn the char const*
into a char*
but fixing the declaration is preferable:
Printfunc(num, addr, const_cast<char*>(data.str().c_str()));
The shorthand for $(document).ready(handler)
is $(handler)
(where handler
is a function). See here.
The code in your question has nothing to do with .ready()
. Rather, it is an immediately-invoked function expression (IIFE) with the jQuery object as its argument. Its purpose is to restrict the scope of at least the $
variable to its own block so it doesn't cause conflicts. You typically see the pattern used by jQuery plugins to ensure that $ == jQuery
.
Here is a simpler way to iterate and print values in vector.
for(int x: A) // for integer x in vector A
cout<< x <<" ";
Bootstrap 4
<div class="col-md-9 col-xs-12 text-md-left text-center">md left, xs center</div>
<div class="col-md-9 col-xs-12 text-md-right text-center">md right, xs center</div>
The best way to remove the error is: 1) Select the Class File (.m) 2) Under "Target Membership", "check" the Project name entry
Read Cookie
in Web Api
var cookie = actionContext.Request.Headers.GetCookies("newhbsslv1");
Logger.Log("Cookie " + cookie, LoggerLevel.Info);
Logger.Log("Cookie count " + cookie.Count, LoggerLevel.Info);
if (cookie != null && cookie.Count > 0)
{
Logger.Log("Befor For " , LoggerLevel.Info);
foreach (var perCookie in cookie[0].Cookies)
{
Logger.Log("perCookie " + perCookie, LoggerLevel.Info);
if (perCookie.Name == "newhbsslv1")
{
strToken = perCookie.Value;
}
}
}
You can also cheat in some way by hidding a submit button on your form and triggering it when you click on your modal button.
This does not answer the question nor does it show any non-jQuery code. See @ sospedra's answer below.
The nice thing about $(document).ready()
is that it fires before window.onload
. The load function waits until everything is loaded, including external assets and images. $(document).ready
, however, fires when the DOM tree is complete and can be manipulated. If you want to acheive DOM ready, without jQuery, you might check into this library. Someone extracted just the ready
part from jQuery. Its nice and small and you might find it useful:
The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.
The only solution is to use less data in your Unique Index. Your key can be NVARCHAR(450) at most.
"SQL Server retains the 900-byte limit for the maximum total size of all index key columns."
Read more at MSDN
Let me tell you my understanding of prototypes. I am not going to compare the inheritance here with other languages. I wish people would stop comparing languages, and just understand the language as itself. Understanding prototypes and prototypal inheritance is so simple, as I will show you below.
Prototype is like a model, based on which you create a product. The crucial point to understand is that when you create an object using another object as it's prototype, the link between the prototype and the product is ever-lasting. For instance:
var model = {x:2};
var product = Object.create(model);
model.y = 5;
product.y
=>5
Every object contains an internal property called the [[prototype]], which can be accessed by the Object.getPrototypeOf()
function. Object.create(model)
creates a new object and sets it's [[prototype]] property to the object model. Hence when you do Object.getPrototypeOf(product)
, you will get the object model.
Properties in the product are handled in the following way:
Such a linking of objects using the prototype property is called prototypal inheritance. There, it is so simple, agree?
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
Download the SDK from here: http://developer.android.com/sdk/ to C:\android-sdk\.
Then when you launch Android Studio again, it will prompt you for the SDK path just point it to: C:\android-sdk\.
Update: new download location, https://developer.android.com/studio/#command-tools
After digging into the Spark API, I found I can first use alias
to create an alias for the original dataframe, then I use withColumnRenamed
to manually rename every column on the alias, this will do the join
without causing the column name duplication.
More detail can be refer to below Spark Dataframe API:
pyspark.sql.DataFrame.withColumnRenamed
However, I think this is only a troublesome workaround, and wondering if there is any better way for my question.
Your test requires a ServletContext: add @WebIntegrationTest
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class, loader = AnnotationConfigContextLoader.class)
@WebIntegrationTest
public class UserServiceImplIT
...or look here for other options: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html
UPDATE
In Spring Boot 1.4.x and above @WebIntegrationTest
is no longer preferred. @SpringBootTest
or @WebMvcTest
Declare @tablename varchar(50)
set @tablename = 'Your table Name'
EXEC('select * from ' + @tablename)
Both do different things.
The first creates an object with automatic storage duration. It is created, used, and then goes out of scope when the current block ({ ... }
) ends. It's the simplest way to create an object, and is just the same as when you write int x = 0;
The second creates an object with dynamic storage duration and allows two things:
Fine control over the lifetime of the object, since it does not go out of scope automatically; you must destroy it explicitly using the keyword delete
;
Creating arrays with a size known only at runtime, since the object creation occurs at runtime. (I won't go into the specifics of allocating dynamic arrays here.)
Neither is preferred; it depends on what you're doing as to which is most appropriate.
Use the former unless you need to use the latter.
Your C++ book should cover this pretty well. If you don't have one, go no further until you have bought and read, several times, one of these.
Good luck.
Your original code is broken, as it delete
s a char
array that it did not new
. In fact, nothing new
d the C-style string; it came from a string literal. delete
ing that is an error (albeit one that will not generate a compilation error, but instead unpredictable behaviour at runtime).
Usually an object should not have the responsibility of delete
ing anything that it didn't itself new
. This behaviour should be well-documented. In this case, the rule is being completely broken.
You can avoid the loop and cut etc by using:
awk -F ':' '{system("ping " $1);}' config.txt
However it would be better if you post a snippet of your config.txt
You can try calling this method in you program:
static double string_double(string s)
{
double temp = 0;
double dtemp = 0;
int b = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '.')
{
i++;
while (i < s.Length)
{
dtemp = (dtemp * 10) + (int)char.GetNumericValue(s[i]);
i++;
b++;
}
temp = temp + (dtemp * Math.Pow(10, -b));
return temp;
}
else
{
temp = (temp * 10) + (int)char.GetNumericValue(s[i]);
}
}
return -1; //if somehow failed
}
Example:
string s = "12.3";
double d = string_double (s); //d = 12.3
And the requisite, non-jquery way, for followers, since google seems to send everyone here:
var select = document.getElementById("select_id");
for (var i = 0; i < select.length; i++){
var option = select.options[i];
// now have option.text, option.value
}
None of the video settings posted above worked in modern browsers I tested (like Firefox) using the embed
or object
elements in HTML5. For video
or audio
elements they did stop autoplay. For embed
and object
they did not.
I tested this using the embed
and object
elements using several different media types as well as HTML attributes (like autostart and autoplay). These videos always played regardless of any combination of settings in several browsers. Again, this was not an issue using the newer HTML5 video
or audio
elements, just when using embed
and object
.
It turns out the new browser settings for video "autoplay" have changed. Firefox will now ignore the autoplay
attributes on these tags and play videos anyway unless you explicitly set to "block audio and video" autoplay in your browser settings.
To do this in Firefox I have posted the settings below:
Your videos will NOT autoplay now when displaying videos in web pages using object
or embed
elements.
You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$status_codes = array (
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
To run once, daily at 10PM you should do something like this:
0 22 * * *
Full size image: http://i.stack.imgur.com/BeXHD.jpg
Source: softpanorama.org
I was not absolutely happy with any of the answers. But I have picked up some ideas from @Matt Way.
Here is my solution:
Definitions:
const Switch = props => {
const { test, children = null } = props;
return children && children.find(child => child && child.props && child.props.casevalue === test) || null;
}
const Case = ({ casevalue = false, children = null }) => <div casevalue={`${casevalue}`}>{children}</div>;
Case.propTypes = {
casevalue: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
}
const Default = ({ children }) => children || <h1>NO_RESULT</h1>;
const SwitchCase = ({ test, cases = [], defaultValue = null }) => {
const defaultVal = defaultValue
&& React.cloneElement(defaultValue, { key: 'default-key', casevalue: `${test}` })
|| <Default key='default-key' casevalue={`${test}`} />;
return (
<Switch test={`${test}`} >
{
cases.map((cas, i) => {
const { props = {} } = cas || {};
const { casevalue = false, ...rest } = props || {};
return <Case key={`case-key-${i}`} casevalue={`${casevalue}`}>{ React.cloneElement(cas, rest)}</Case>
})
.concat(defaultVal)
}
</Switch>
);
}
Usage:
<SwitchCase
cases={[
<div casevalue={`${false}`}>#1</div>,
<div casevalue={`${true}`}>#2</div>,
<div casevalue={`${false}`}>#3</div>,
]}
defaultValue={<h1>...nothing to see here</h1>} // You can leave it blank.
test={`${true}`}
/>
The best solution that worked great for me.
You have to: Copy this code to your main CSS file,
.responsive-video {
position: relative;
padding-bottom: 56.25%;
padding-top: 60px; overflow: hidden;
}
.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
and then put your embeded video to
<div class="responsive-video">
<iframe ></iframe>
</div>
That’s it! Now you can use responsive videos on your site.
private JSONObject uploadToServer() throws IOException, JSONException {
String query = "https://example.com";
String json = "{\"key\":1}";
URL url = new URL(query);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
JSONObject jsonObject = new JSONObject(result);
in.close();
conn.disconnect();
return jsonObject;
}
I also occured the error,and I sloved it by removing the curly braces,hope it will help someone else.
You can see that ,I did not put the con in the curly brace,and the error occured ,when I remove the burly brace , the error disappeared.
const modal = (props) => {
const { show, onClose } = props;
let con = <div className="modal" onClick={onClose}>
{props.children}
</div>;
return show === true ? (
{con}
) : (
<div>hello</div>
);
There are an article about the usage of the curly brace.click here
For me it works a deleting "C:\ProgramData\Oracle\Java\javapath" in my system enviroment PATH variable
Edit: If you don't have that variable or it does not work you can directly delete or rename the directory "C:\ProgramData\Oracle\Java\javapath"
The code you posted looks like it should correctly remove the forms authentication token, so it is possible that the folders/pages in question are not actually protected.
Have you confirmed that the pages cannot be accessed before a login has occured?
Can you post the web.config settings and login code that you are using?
Aonepathan's one-liner was working for me until a recent typescript update.
I found Jecelyn Yeen's post which suggests posting this snippet into your TS Definition file
add file typings.d.ts
to the project's root folder with below content
declare module "*.json" {
const value: any;
export default value;
}
and then import your data like this:
import * as data from './example.json';
Typescript 2.9 (docs) introduced a better, smarter solution. Steps:
resolveJsonModule
support with this line in your tsconfig.json
file: "compilerOptions": {
...
"resolveJsonModule": true
}
the import statement can now assumes a default export:
import data from './example.json';
and intellisense will now check the json file to see whether you can use Array etc. methods. pretty cool.
You may want to use Vim global marks.
This way you can quickly bounce between files, and even to the marked location in the file. Also, the key commands are short:
'C
takes me to the code I'm working with,
'T
takes me to the unit test I'm working with.
When you change places, resetting the marks is quick too:
mC
marks the new code spot,
mT
marks the new test spot.
Simply you can put a back slash in front of your css link
String onevalue;
if(request.getParameterMap().containsKey("one")!=false)
{
onevalue=request.getParameter("one").toString();
}
struct A {};
struct B : A {};
struct C {};
int main()
{
A* a = new A;
int i = 10;
a = (A*) (&i); // NO ERROR! FAIL!
//a = static_cast<A*>(&i); ERROR! SMART!
A* b = new B;
B* b2 = static_cast<B*>(b); // NO ERROR! SMART!
C* c = (C*)(b); // NO ERROR! FAIL!
//C* c = static_cast<C*>(b); ERROR! SMART!
}
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Two possible approaches.
If you have a foreign key, declare it as on-delete-cascade and delete the parent rows older than 30 days. All the child rows will be deleted automatically.
Based on your description, it looks like you know the parent rows that you want to delete and need to delete the corresponding child rows. Have you tried SQL like this?
delete from child_table
where parent_id in (
select parent_id from parent_table
where updd_tms != (sysdate-30)
-- now delete the parent table records
delete from parent_table
where updd_tms != (sysdate-30);
---- Based on your requirement, it looks like you might have to use PL/SQL. I'll see if someone can post a pure SQL solution to this (in which case that would definitely be the way to go).
declare
v_sqlcode number;
PRAGMA EXCEPTION_INIT(foreign_key_violated, -02291);
begin
for v_rec in (select parent_id, child id from child_table
where updd_tms != (sysdate-30) ) loop
-- delete the children
delete from child_table where child_id = v_rec.child_id;
-- delete the parent. If we get foreign key violation,
-- stop this step and continue the loop
begin
delete from parent_table
where parent_id = v_rec.parent_id;
exception
when foreign_key_violated
then null;
end;
end loop;
end;
/
Adding external Jar is not smart in case you want to change the project location in filesystem.
The best way is to add the jar to build path so your project will compile if exported:
Create a folder called lib in your project folder.
copy to this folder all the jar files you need.
Refresh your project in eclipse.
Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path
My Cascading Style Sheet used:
body {background-color: #FAF0E6; font-family: arial, sans-serif }
It worked in Internet Explorer but failed in Firefox and Chrome. I changed it to:
body {background: #FAF0E6; font-family: arial, sans-serif }
(i.e. I removed -color
.)
It works in all three browsers. (I had to restart Chrome.)
see this is working for me.
ActStatus.pipe.ts First this is my pipe
import {Pipe,PipeTransform} from "@angular/core";
@Pipe({
name:'actStatusPipe'
})
export class ActStatusPipe implements PipeTransform{
transform(status:any):any{
switch (status) {
case 1:
return "UN_PUBLISH";
case 2:
return "PUBLISH";
default:
return status
}
}
}
main-pipe.module.ts in pipe module, i need to declare my pipe/s and export it.
import { NgModule } from '@angular/core';
import {CommonModule} from "@angular/common";
import {ActStatusPipe} from "./ActStatusPipe.pipe"; // <---
@NgModule({
declarations:[ActStatusPipe], // <---
imports:[CommonModule],
exports:[ActStatusPipe] // <---
})
export class MainPipe{}
app.module.ts user this pipe module in any module.
@NgModule({
declarations: [...],
imports: [..., MainPipe], // <---
providers: [...],
bootstrap: [AppComponent]
})
you can directly user pipe in this module. but if you feel that your pipe is used with in more than one component i suggest you to follow my approach.
How to use pipe totally depends on your project complexity and requirement. you might have just one pipe which used only once in the whole project. in that case you can directly use it without creating a pipe/s module (module approach).
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
Viblend WPF themes are free.
Here is the alternative solution to check whether a particular string contains some predefined string. It uses IndexOf
Function:
'this is your string
Dim strMyString As String = "aaSomethingbb"
'if your string contains these strings
Dim TargetString1 As String = "Something"
Dim TargetString2 As String = "Something2"
If strMyString.IndexOf(TargetString1) <> -1 Or strMyString.IndexOf(TargetString2) <> -1 Then
End If
NOTE: This solution has been tested with Visual Studio 2010.
To find out if a string contains substring you can use the index
function:
if (index($str, $substr) != -1) {
print "$str contains $substr\n";
}
It will return the position of the first occurrence of $substr
in $str
, or -1 if the substring is not found.
This error may be triggered by insufficient memory on RDP server.
After few tries with this error, RDP managed to get a connection to the server and I was able to stop a bogus service consuming too much memory. This can be done also with sysinternals or sc.
You should use flexbox to achieve this. It's not supported in IE8 and IE9 and only with the -ms prefix in IE10, but all other browsers support it. For vendor prefixes, you should also use autoprefixer.
.parent {
display: flex;
flex-wrap: wrap; // allow wrapping items
}
.child {
flex-grow: 1;
flex-basis: 50%; // 50% for two in a row, 33% three in a row etc.
}
In case this may interest anyone, I've profiled the top three proposed methods. I have about ~500K files in the globbed folder (in total), and 2K files that match the desired pattern.
here's the (very basic) code
import glob
import json
import fnmatch
import os
from pathlib import Path
from time import time
def find_files_iglob():
return glob.iglob("./data/**/data.json", recursive=True)
def find_files_oswalk():
for root, dirnames, filenames in os.walk('data'):
for filename in fnmatch.filter(filenames, 'data.json'):
yield os.path.join(root, filename)
def find_files_rglob():
return Path('data').rglob('data.json')
t0 = time()
for f in find_files_oswalk(): pass
t1 = time()
for f in find_files_rglob(): pass
t2 = time()
for f in find_files_iglob(): pass
t3 = time()
print(t1-t0, t2-t1, t3-t2)
And the results I got were:
os_walk: ~3.6sec
rglob ~14.5sec
iglob: ~16.9sec
The platform: Ubuntu 16.04, x86_64 (core i7),
This is how to do it in Excel as UDF and in VBA:
Public Function ReverseMe(textToReverse As String, _
Optional delim As String = " ") As String
Dim test As String
Dim arr As Variant
Dim arr2 As Variant
Dim arrPart As Variant
Dim cnt As Long
arr = Split(textToReverse, ".")
ReDim arr2(UBound(arr))
For Each arrPart In arr
arr2(cnt) = StrReverse(arrPart)
cnt = cnt + 1
Next arrPart
ReverseMe = StrReverse(Join(arr2, "."))
End Function
Public Sub TestMe()
Debug.Print ReverseMe("veso.dosev.diri.rid", ".")
Debug.Print ReverseMe("VBA is the best language")
End Sub
Try to sort items by creation time. Example below sorts files in a folder and gets first element which is latest.
import glob
import os
files_path = os.path.join(folder, '*')
files = sorted(
glob.iglob(files_path), key=os.path.getctime, reverse=True)
print files[0]
I would recommend that you don't. Do you really want to have a class that is dependent on how the text editing is implemented in the form, or do you want a mechanism allowing you to get and set the text?
I would suggest the latter. So in your form, create a property that wraps the Text
property of the TextBox
control in question:
public string FirstName
{
get { return firstNameTextBox.Text; }
set { firstNameTextBox.Text = value; }
}
Next, create some mechanism through which you class can get a reference to the form (through the contructor for instance). Then that class can use the property to access and modify the text:
class SomeClass
{
private readonly YourFormClass form;
public SomeClass(YourFormClass form)
{
this.form = form;
}
private void SomeMethodDoingStuffWithText()
{
string firstName = form.FirstName;
form.FirstName = "some name";
}
}
An even better solution would be to define the possible interactions in an interface, and let that interface be the contract between your form and the other class. That way the class is completely decoupled from the form, and can use anyting implementing the interface (which opens the door for far easier testing):
interface IYourForm
{
string FirstName { get; set; }
}
In your form class:
class YourFormClass : Form, IYourForm
{
// lots of other code here
public string FirstName
{
get { return firstNameTextBox.Text; }
set { firstNameTextBox.Text = value; }
}
}
...and the class:
class SomeClass
{
private readonly IYourForm form;
public SomeClass(IYourForm form)
{
this.form = form;
}
// and so on
}