The header <math.h>
is a C std lib header. It defines a lot of stuff in the global namespace. The header <cmath>
is the C++ version of that header. It defines essentially the same stuff in namespace std
. (There are some differences, like that the C++ version comes with overloads of some functions, but that doesn't matter.) The header <cmath.h>
doesn't exist.
Since vendors don't want to maintain two versions of what is essentially the same header, they came up with different possibilities to have only one of them behind the scenes. Often, that's the C header (since a C++ compiler is able to parse that, while the opposite won't work), and the C++ header just includes that and pulls everything into namespace std
. Or there's some macro magic for parsing the same header with or without namespace std
wrapped around it or not. To this add that in some environments it's awkward if headers don't have a file extension (like editors failing to highlight the code etc.). So some vendors would have <cmath>
be a one-liner including some other header with a .h
extension. Or some would map all includes matching <cblah>
to <blah.h>
(which, through macro magic, becomes the C++ header when __cplusplus
is defined, and otherwise becomes the C header) or <cblah.h>
or whatever.
That's the reason why on some platforms including things like <cmath.h>
, which ought not to exist, will initially succeed, although it might make the compiler fail spectacularly later on.
I have no idea which std lib implementation you use. I suppose it's the one that comes with GCC, but this I don't know, so I cannot explain exactly what happened in your case. But it's certainly a mix of one of the above vendor-specific hacks and you including a header you ought not to have included yourself. Maybe it's the one where <cmath>
maps to <cmath.h>
with a specific (set of) macro(s) which you hadn't defined, so that you ended up with both definitions.
Note, however, that this code still ought not to compile:
#include <cmath>
double f(double d)
{
return abs(d);
}
There shouldn't be an abs()
in the global namespace (it's std::abs()
). However, as per the above described implementation tricks, there might well be. Porting such code later (or just trying to compile it with your vendor's next version which doesn't allow this) can be very tedious, so you should keep an eye on this.
For PyCharm 5 (or 2016.1), you can:
I will provide a detailed differences between Visual Studio and Visual Studio Code below.
If you really look at it the most obvious difference is that .NET has been split into two:
All native user interface technologies (Windows Presentation Foundation, Windows Forms, etc.) are part of the framework, not the core.
The "Visual" in Visual Studio (from Visual Basic) was largely synonymous with visual UI (drag & drop WYSIWYG) design, so in that sense, Visual Studio Code is Visual Studio without the Visual!
The second most obvious difference is that Visual Studio tends to be oriented around projects & solutions.
Visual Studio Code:
Visual Studio:
Visual Studio is aimed to be the world’s best IDE (integrated development environment), which provide full stack develop toolsets, including a powerful code completion component called IntelliSense, a debugger which can debug both source code and machine code, everything about ASP.NET development, and something about SQL development.
In the latest version of Visual Studio, you can develop cross-platform application without leaving the IDE. And Visual Studio takes more than 8 GB disk space (according to the components you select).
In brief, Visual Studio is an ultimate development environment, and it’s quite heavy.
Reference: https://www.quora.com/What-is-the-difference-between-Visual-Studio-and-Visual-Studio-Code
->
calls/sets object variables. Ex:
$obj = new StdClass;
$obj->foo = 'bar';
var_dump($obj);
=> Sets key/value pairs for arrays. Ex:
$array = array(
'foo' => 'bar'
);
var_dump($array);
You can use:
objects_all=Class.objects.filter(filter_condition="")
This will return a query set even if it gets one object. If you need exactly one object use:
obj=Class.objects.get(conditon="")
One option would be:
SET SERVEROUTPUT ON
EXEC DBMS_OUTPUT.PUT_LINE(your_fn_name(your_fn_arguments));
Recent versions of Mercurial include the evolve
extension which provides the hg amend
command. This allows amending a commit without losing the pre-amend history in your version control.
hg amend [OPTION]... [FILE]...
aliases: refresh
combine a changeset with updates and replace it with a new one
Commits a new changeset incorporating both the changes to the given files and all the changes from the current parent changeset into the repository. See 'hg commit' for details about committing changes. If you don't specify -m, the parent's message will be reused. Behind the scenes, Mercurial first commits the update as a regular child of the current parent. Then it creates a new commit on the parent's parents with the updated contents. Then it changes the working copy parent to this new combined changeset. Finally, the old changeset and its update are hidden from 'hg log' (unless you use --hidden with log).
See https://www.mercurial-scm.org/doc/evolution/user-guide.html#example-3-amend-a-changeset-with-evolve for a complete description of the evolve
extension.
As a good practice I think it is a good idea to test if a popup was blocked and take action in case. You need to know that window.open has a return value, and that value may be null if the action failed. For example, in the following code:
function pop(url,w,h) {
n=window.open(url,'_blank','toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width='+w+',height='+h);
if(n==null) {
return true;
}
return false;
}
if the popup is blocked, window.open will return null. So the function will return false.
As an example, imagine calling this function directly from any link with
target="_blank"
: if the popup is successfully opened, returningfalse
will block the link action, else if the popup is blocked, returningtrue
will let the default behavior (open new _blank window) and go on.
<a href="http://whatever.com" target="_blank" onclick='return pop("http://whatever.com",300,200);' >
This way you will have a popup if it works, and a _blank window if not.
If the popup does not open, you can:
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb");
if (fp) {
read_scores(fp);
}
// Later...
// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
error();
write_scores(fp);
i also facing this same problem in django server.So i changed DEBUG = True in settings.py file its working
Something like:
DateTime today = DateTime.Today;
DateTime endOfMonth = new DateTime(today.Year, today.Month, 1).AddMonths(1).AddDays(-1);
Which is to say that you get the first day of next month, then subtract a day. The framework code will handle month length, leap years and such things.
You can put this view between your views to imitate the line
<View
android:layout_width="fill_parent"
android:layout_height="2dp"
android:background="#c0c0c0"/>
DELETE i1.*
FROM items i1
LEFT JOIN
(
SELECT id
FROM items ii
ORDER BY
id DESC
LIMIT 20
) i2
ON i1.id = i2.id
WHERE i2.id IS NULL
The answers so far will work.. if you only want to use the height without padding, borders, etc.
If you would like to account for padding, borders, and margin, you should use .outerHeight
.
var bottom = $('#bottom').position().top + $('#bottom').outerHeight(true);
If you don't want to touch the original process' stdout and stderr, you can redirect stderr to file descriptor 3 and back:
$ { time { perl -le "print 'foo'; warn 'bar';" 2>&3; }; } 3>&2 2> time.out
foo
bar at -e line 1.
$ cat time.out
real 0m0.009s
user 0m0.004s
sys 0m0.000s
You could use that for a wrapper (e.g. for cronjobs) to monitor runtimes:
#!/bin/bash
echo "[$(date)]" "$@" >> /my/runtime.log
{ time { "$@" 2>&3; }; } 3>&2 2>> /my/runtime.log
If you're using jQuery, use .data()
:
div.data('myval', 20);
You can store arbitrary data with .data()
, but you're restricted to just strings when using .attr()
.
To mark a directory as a package you need a file named __init__.py
, does this help?
Insert single quotes.
Example
$department = mysql_real_escape_string($_POST['department']);
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST['message']);
InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources.
For example, you can write primitive data to a file:
File file = new File("C:/text.bin");
file.createNewFile();
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
stream.writeBoolean(true);
stream.writeInt(1234);
stream.close();
To read the written contents:
File file = new File("C:/text.bin");
DataInputStream stream = new DataInputStream(new FileInputStream(file));
boolean isTrue = stream.readBoolean();
int value = stream.readInt();
stream.close();
System.out.printlin(isTrue + " " + value);
You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency:
DataInputStream stream = new DataInputStream(
new BufferedInputStream(new FileInputStream(file)));
You can write other data such as objects:
MyClass myObject = new MyClass(); // MyClass have to implement Serializable
ObjectOutputStream stream = new ObjectOutputStream(
new FileOutputStream("C:/text.obj"));
stream.writeObject(myObject);
stream.close();
You can read from other different input sources:
byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9};
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test));
int value0 = stream.readInt();
int value1 = stream.readInt();
byte value2 = stream.readByte();
byte value3 = stream.readByte();
stream.close();
System.out.println(value0 + " " + value1 + " " + value2 + " " + value3);
For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).
I know this question is old. But this might be useful for someone who is having the problem with legend. In addition to the answer given by ZaneDarken, I modified the chart.js file to show the legend in my pie chart. I changed the legendTemplate(which is declared many times for every chart type) just above these lines :
Chart.Type.extend({_x000D_
//Passing in a name registers this chart in the Chart namespace_x000D_
name: "Doughnut",_x000D_
//Providing a defaults will also register the deafults in the chart namespace_x000D_
defaults: defaultConfig,_x000D_
.......
_x000D_
My legendTemplate is changed from
legendTemplate : "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
<% for (var i=0; i<datasets.length; i++){%>_x000D_
<li><span style=\ "background-color:<%=datasets[i].strokeColor%>\"></span>_x000D_
<%if(datasets[i].label){%>_x000D_
<%=datasets[i].label%>_x000D_
<%}%>_x000D_
</li>_x000D_
<%}%>_x000D_
</ul>"
_x000D_
To
legendTemplate: "_x000D_
<ul class=\ "<%=name.toLowerCase()%>-legend\">_x000D_
<% for (var i=0; i<segments.length; i++){%>_x000D_
<li><span style=\ "-moz-border-radius:7px 7px 7px 7px; border-radius:7px 7px 7px 7px; margin-right:10px;width:15px;height:15px;display:inline-block;background-color:<%=segments[i].fillColor%>\"> </span>_x000D_
<%if(segments[i].label){%>_x000D_
<%=s egments[i].label%>_x000D_
<%}%>_x000D_
</li>_x000D_
<%}%>_x000D_
</ul>"
_x000D_
Edit: Thanks Marc, read up on the struct vs class issue and you're right, thank you!
I tend to use the following method for doing what you describe, using a static method of JSon.Net:
MyObject deserializedObject = JsonConvert.DeserializeObject<MyObject>(json);
Link: Serializing and Deserializing JSON with Json.NET
For the Objects list, may I suggest using generic lists out made out of your own small class containing attributes
and position
class. You can use the Point
struct in System.Drawing
(System.Drawing.Point
or System.Drawing.PointF
for floating point numbers) for you X and Y.
After object creation it's much easier to get the data you're after vs. the text parsing you're otherwise looking at.
The error message is telling you.
Try just
"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
When you enclose the string in single-quotes, this makes everything inside a valid string, including the "
chars. By removing the single-quotes, the shell will process the dbl-quotes as string "wrappers".
I would also wrap the filename variable in dbl-quotes so you can easily process files with spaces in their names, i.e.
"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe" /t "$pdf"
IHTH
It is very easy, you can use a plugin on android studio to make objects Parcelables.
public class Persona implements Parcelable {
String nombre;
int edad;
Date fechaNacimiento;
public Persona(String nombre, int edad, Date fechaNacimiento) {
this.nombre = nombre;
this.edad = edad;
this.fechaNacimiento = fechaNacimiento;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.nombre);
dest.writeInt(this.edad);
dest.writeLong(fechaNacimiento != null ? fechaNacimiento.getTime() : -1);
}
protected Persona(Parcel in) {
this.nombre = in.readString();
this.edad = in.readInt();
long tmpFechaNacimiento = in.readLong();
this.fechaNacimiento = tmpFechaNacimiento == -1 ? null : new Date(tmpFechaNacimiento);
}
public static final Parcelable.Creator<Persona> CREATOR = new Parcelable.Creator<Persona>() {
public Persona createFromParcel(Parcel source) {
return new Persona(source);
}
public Persona[] newArray(int size) {
return new Persona[size];
}
};}
I would suggest mp3-tagger. Best thing about this is it is distributed under MIT License and supports all the required attributes.
- artist;
- album;
- song;
- track;
- comment;
- year;
- genre;
- band;
- composer;
- copyright;
- url;
- publisher.
Example:
from mp3_tagger import MP3File
# Create MP3File instance.
mp3 = MP3File('File_Name.mp3')
# Get all tags.
tags = mp3.get_tags()
print(tags)
It supports set, get, update and delete attributes of mp3 files.
If the input field has a class name formData use this :
$(".formData").val("data")
If the input field has an id attribute name formData use this :
$("#formData").val("data")
If the input name is given use this :
$("input[name='formData']").val("data")
You can also mention the type. Then it will refer to all the inputs of that type and the given class name:
$("input[type='text'].formData").val("data")
I am calling myScript1.ps1 from myScript2.ps1 .
Assuming both of the script are at the same location, first get the location of the script by using this command :
$PSScriptRoot
And, then, append the script name you want to call like this :
& "$PSScriptRoot\myScript1.ps1"
This should work.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar;
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_drawer,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_drawer){
drawerLayout.openDrawer(GravityCompat.END);
if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
drawerLayout.closeDrawer(GravityCompat.END);
} else {
drawerLayout.openDrawer(GravityCompat.END);
}
}
return super.onOptionsItemSelected(item);
}
res/layout/drawer_menu
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_drawer"
android:title="@string/app_name"
android:icon="@drawable/ic_menu_black_24dp"
app:showAsAction="always"/>
</menu>
toolbar.xml
<com.google.android.material.appbar.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:titleTextColor="@android:color/white"
app:titleTextAppearance="@style/TextAppearance.Widget.Event.Toolbar.Title">
<TextView
android:id="@+id/toolbar_title"
android:layout_gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/app_name"
android:textColor="@android:color/white"
style="@style/TextAppearance.AppCompat.Widget.ActionBar.Title" />
</androidx.appcompat.widget.Toolbar>
You're resetting the margin on all elements in the second css block. Default margin is 40px - this should solve the problem:
.my_container ul {list-style:disc outside none; margin-left:40px;}
Another way of changing the size of the bullets would be:
::before
pseudo-element.Example:
ul {_x000D_
list-style-type: none;_x000D_
}_x000D_
_x000D_
li::before {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
width: 5px;_x000D_
height: 5px;_x000D_
background-color: #000000;_x000D_
margin-right: 8px;_x000D_
content: ' '_x000D_
}
_x000D_
<ul>_x000D_
<li>first element</li>_x000D_
<li>second element</li>_x000D_
</ul>
_x000D_
No markup changes needed
Use the following syntax:
$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05
Disclaimer: Leading zeros only work in >=bash-4
.
If you want to use printf
, nothing prevents you from putting its result in a variable for further use:
$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05
I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.
SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';
SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"`
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ," AFTER
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME
FROM information_schema.COLUMNS c2
WHERE c2.TABLE_NAME = t.TABLE_NAME);
Solutions above are good but they require ~/.bash_profile. /usr/local/bin
is already in the $PATH and it can be confirmed by doing echo $PATH
. Download maven and run the following commands -
$ cd ~/Downloads
$ tar xvf apache-maven-3.5.3-bin.tar.gz
$ mv apache-maven-3.5.3 /usr/local/
$ cd /usr/local/bin
$ sudo ln -s ../apache-maven-3.5.3/bin/mvn mvn
$ mvn -version
$ which mvn
Note: The version of apache maven would be the one you will download.
I think its worth referencing this similar answer: https://stackoverflow.com/a/5288804/64313
Here is a another quick solution. There are other variations possible on this using the <available>
tag:
# exit with failure if no files are found
<property name="file" value="${some.path}/some.txt" />
<fail message="FILE NOT FOUND: ${file}">
<condition><not>
<available file="${file}" />
</not></condition>
</fail>
... or you could avoid the .
and $
constructions by using pipelining:
third xs = xs |> tail |> tail |> head
That's after you've added in the helper function:
(|>) x y = y x
To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.
To install OpenSSL development package on Debian, Ubuntu or their derivatives:
$ sudo apt-get install libssl-dev
To install OpenSSL development package on Fedora, CentOS or RHEL:
$ sudo yum install openssl-devel
Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :
dnf install openssl-devel
May I suggest that you initialize your "max and min so far" variables not to infinity, but to the first number in the array?
Let me add here that one very minor issue that could generate this type of error is the missing .git
extension in the repository URL. Ensure you enter the fully qualified URL ending with .git
. I use bitbucket so what I do do is do click 'clone' and the fully qualified URL is automatically generated for me. There is a similar approach with github.
Connect with SSH and follow these instructions to install Node on a shared hosting
In short you first install NVM, then you install the Node version of your choice with NVM.
wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash
Your restart your shell (close and reopen your sessions). Then you
nvm install stable
to install the latest stable version for example. You can install any version of your choice. Check node --version
for the node version you are currently using and nvm list
to see what you've installed.
In bonus you can switch version very easily (nvm use <version>
)
There's no need of PHP or whichever tricky workaround if you have SSH.
check up blur()
:
$('#textarea').blur()
source: http://api.jquery.com/blur/
To store the array values in cookie, first you need to convert them to string, so here is some options.
Storing code
setcookie('your_cookie_name', json_encode($info), time()+3600);
Reading code
$data = json_decode($_COOKIE['your_cookie_name'], true);
JSON can be good choose also if you need read cookie in front end with JavaScript.
Actually you can use any encrypt_array_to_string
/decrypt_array_from_string
methods group that will convert array to string and convert string back to same array.
For example you can also use explode
/implode
for array of integers.
From PHP.net
Do not pass untrusted user input to unserialize().
- Anything that coming by HTTP including cookies is untrusted!
References related to security
setcookie('my_array[0]', 'value1' , time()+3600);
setcookie('my_array[1]', 'value2' , time()+3600);
setcookie('my_array[2]', 'value3' , time()+3600);
And after if you will print $_COOKIE
variable, you will see the following
echo '<pre>';
print_r( $_COOKIE );
die();
Array ( [my_array] => Array ( [0] => value1 [1] => value2 [2] => value3 ) )
This is documented PHP feature.
From PHP.net
Cookies names can be set as array names and will be available to your PHP scripts as arrays but separate cookies are stored on the user's system.
What is the difference between web service and WCF?
Web service use only HTTP protocol while transferring data from one application to other application.
But WCF supports more protocols for transporting messages than ASP.NET Web services. WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ).
To develop a service in Web Service, we will write the following code
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF, we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
Web Service is not architecturally more robust. But WCF is architecturally more robust and promotes best practices.
Web Services use XmlSerializer but WCF uses DataContractSerializer. Which is better in performance as compared to XmlSerializer?
For internal (behind firewall) service-to-service calls we use the net:tcp binding, which is much faster than SOAP.
WCF is 25%—50% faster than ASP.NET Web Services, and approximately 25% faster than .NET Remoting.
When would I opt for one over the other?
WCF is used to communicate between other applications which has been developed on other platforms and using other Technology.
For example, if I have to transfer data from .net platform to other application which is running on other OS (like Unix or Linux) and they are using other transfer protocol (like WAS, or TCP) Then it is only possible to transfer data using WCF.
Here is no restriction of platform, transfer protocol of application while transferring the data between one application to other application.
Security is very high as compare to web service
I would like to clarify a few things due to seemingly conflicting responses (mostly surrounding IEnumerable).
(1) IQueryable
extends the IEnumerable
interface. (You can send an IQueryable
to something which expects IEnumerable
without error.)
(2) Both IQueryable
and IEnumerable
LINQ attempt lazy loading when iterating over the result set. (Note that implementation can be seen in interface extension methods for each type.)
In other words, IEnumerables
are not exclusively "in-memory". IQueryables
are not always executed on the database. IEnumerable
must load things into memory (once retrieved, possibly lazily) because it has no abstract data provider. IQueryables
rely on an abstract provider (like LINQ-to-SQL), although this could also be the .NET in-memory provider.
Sample use case
(a) Retrieve list of records as IQueryable
from EF context. (No records are in-memory.)
(b) Pass the IQueryable
to a view whose model is IEnumerable
. (Valid. IQueryable
extends IEnumerable
.)
(c) Iterate over and access the data set's records, child entities and properties from the view. (May cause exceptions!)
Possible Issues
(1) The IEnumerable
attempts lazy loading and your data context is expired. Exception thrown because provider is no longer available.
(2) Entity Framework entity proxies are enabled (the default), and you attempt to access a related (virtual) object with an expired data context. Same as (1).
(3) Multiple Active Result Sets (MARS). If you are iterating over the IEnumerable
in a foreach( var record in resultSet )
block and simultaneously attempt to access record.childEntity.childProperty
, you may end up with MARS due to lazy loading of both the data set and the relational entity. This will cause an exception if it is not enabled in your connection string.
Solution
Execute the query and store results by invoking resultList = resultSet.ToList()
This seems to be the most straightforward way of ensuring your entities are in-memory.
In cases where the you are accessing related entities, you may still require a data context. Either that, or you can disable entity proxies and explicitly Include
related entities from your DbSet
.
out: dict_values([{1:a, 2:b}])
in: str(dict.values())[14:-3]
out: 1:a, 2:b
Purely for visual purposes. Does not produce a useful product... Only useful if you want a long dictionary to print in a paragraph type form.
Jianxun's solution did the job for me but broke the y value indicator at the bottom left of the window.
I ended up using FuncFormatter
instead (and also stripped the uneccessary trailing zeroes as suggested here):
import pandas as pd
import numpy as np
from matplotlib.ticker import FuncFormatter
df = pd.DataFrame(np.random.randn(100,5))
ax = df.plot()
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
Generally speaking I'd recommend using FuncFormatter
for label formatting: it's reliable, and versatile.
dependencies {
compile ('org.springframework.kafka:spring-kafka-test:2.2.7.RELEASE') { dep ->
['org.apache.kafka:kafka_2.11','org.apache.kafka:kafka-clients'].each { i ->
def (g, m) = i.tokenize( ':' )
dep.exclude group: g , module: m
}
}
}
If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:
$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});
If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:
$.post('/url/to/page', {'someKeyName': ['value','value']});
If you want to pass a JavaScript array then you can do:
$.post('/url/to/page', {'someKeyName': variableName});
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
install MySQLWorkbench, then
export PATH=$PATH:/Applications/MySQLWorkbench.app/Contents/MacOS
If you are using "MVC 5" you may not see the file, and you should follow these steps: http://www.techjunkieblog.com/2015/05/aspnet-mvc-empty-project-adding.html
If you are using "ASP.NET 5" it has stopped using "bundling and minification" instead was replaced by gulp, bower, and npm. More information see https://jeffreyfritz.com/2015/05/where-did-my-asp-net-bundles-go-in-asp-net-5/
The If else statement needs to be wrapped in a .get or a .post to redirect. Such as
app.post('/login', function(req, res) {
});
or
app.get('/login', function(req, res) {
});
Project > Generate Javadoc....
In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).
Check the box next to the project/package/file for which you are creating the Javadoc.
In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).
Click Finish.
You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.
AFAIK, the browser (at least Firefox) requests every resource as soon as it parses it. If it encounters an img tag it will request that image as soon as the img tag has been parsed. And that can be even before it has received the totality of the HTML document... that is it could still be downloading the HTML document when that happens.
For Firefox, there are browser queues that apply, depending on how they are set in about:config. For example it will not attempt to download more then 8 files at once from the same server... the additional requests will be queued. I think there are per-domain limits, per proxy limits, and other stuff, which are documented on the Mozilla website and can be set in about:config. I read somewhere that IE has no such limits.
The jQuery ready event is fired as soon as the main HTML document has been downloaded and it's DOM parsed. Then the load event is fired once all linked resources (CSS, images, etc.) have been downloaded and parsed as well. It is made clear in the jQuery documentation.
If you want to control the order in which all that is loaded, I believe the most reliable way to do it is through JavaScript.
In a more general way you can use "INTERVAL". Here some examples:
1) add a day
select sysdate + INTERVAL '1' DAY from dual;
2) add 20 days
select sysdate + INTERVAL '20' DAY from dual;
2) add some minutes
select sysdate + INTERVAL '15' MINUTE from dual;
insert into OPT (email, campaign_id)
select '[email protected]',100
from dual
where not exists(select *
from OPT
where (email ='[email protected]' and campaign_id =100));
try this
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string = dateFormat.format(new Date());
System.out.println(string);
you can create any format see this
This my workaround to solve this problem and check the valid internet connection because as they said that Network info class cannot give you the expected result and it may return true when network connected but no internet.
So this my COMPLETE WORKAROUND based on @Levite Answer:
First you must have AsynckTask for checking Network availability and this is mine:
public class Connectivity {
private static final String TAG = "Connectivity";
private static boolean hasConnected = false, hasChecked = false;
private InternetListener internetListener;
private Activity activity;
public Connectivity(InternetListener internetListener, Activity activity) {
this.internetListener = internetListener;
this.activity = activity;
}
public void startInternetListener() {
CheckURL checkURL = new CheckURL(activity);
checkURL.execute();
long startTime = System.currentTimeMillis();
while (true) {
if (hasChecked && hasConnected) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onConnected();
}
});
checkURL.cancel(true);
return;
}
// check if time
if (System.currentTimeMillis() - startTime >= 1000) {
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
internetListener.onDisconnected();
}
});
checkURL.cancel(true);
return;
}
}
//return hasConnected;
}
class CheckURL extends AsyncTask<Void, Void, Boolean> {
private Activity activity;
public CheckURL(Activity activity) {
this.activity = activity;
}
@Override
protected Boolean doInBackground(Void... params) {
if (!isNetWorkAvailable(activity)) {
Log.i(TAG, "Internet not available!");
return false;
}
int timeoutMs = 3000;
try {
Socket sock = new Socket();
SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);
sock.connect(sockaddr, timeoutMs);
sock.close();
Log.i(TAG, "Internet available :)");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
hasChecked = true;
hasConnected = result;
super.onPostExecute(result);}}
private static final String TAG = "Connectivity";
private static boolean isNetWorkAvailable(Activity activity) {
ConnectivityManager connectivityManager =
(ConnectivityManager)
activity.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);}
}}
private static boolean isNetWorkAvailable(Context context) {
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo =
null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
boolean isConnected;
boolean isWifiAvailable = false;
if (networkInfo != null) {
isWifiAvailable = networkInfo.isAvailable();
}
boolean isWifiConnected = false;
if (networkInfo != null) {
isWifiConnected = networkInfo.isConnected();
}
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
}
boolean isMobileAvailable = false;
if (networkInfo != null) {
isMobileAvailable = networkInfo.isAvailable();
}
boolean isMobileConnected = false;
if (networkInfo != null) {
isMobileConnected = networkInfo.isConnected();
}
isConnected = (isMobileAvailable && isMobileConnected) ||
(isWifiAvailable && isWifiConnected);
return (isConnected);
}
}
After that you should create another thread to start AscnkTask And listen for result with the InternetListener.
public interface InternetListener {
void onConnected();
void onDisconnected();
}
And the Thread that is waiting for AsynckTask result you can put it in Utility class:
private static Thread thread;
public static void startNetworkListener(Context context, InternetListener
internetListener) {
if (thread == null){
thread = new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
new Connectivity(internetListener,context).startInternetListener();
}
});
}
thread.start();
}
Finally call the startNetworkListener() method and listen for result.
example in activity from My Utils.java class :
Utils.startNetworkListener(this, new InternetListener() {
@Override
public void onConnected() {
// do your work when internet available.
}
@Override
public void onDisconnected() {
// do your work when no internet available.
}
});
Happy Coding :).
Something like this should suffice, to do what your batch file was doing (dumping the result set as semi-colon delimited text to the console):
// sqlcmd.exe
// -S .\PDATA_SQLEXPRESS
// -U sa
// -P 2BeChanged!
// -d PDATA_SQLEXPRESS
// -s ; -W -w 100
// -Q "SELECT tPatCulIntPatIDPk, tPatSFirstname, tPatSName, tPatDBirthday FROM [dbo].[TPatientRaw] WHERE tPatSName = '%name%' "
DataTable dt = new DataTable() ;
int rows_returned ;
const string credentials = @"Server=(localdb)\.\PDATA_SQLEXPRESS;Database=PDATA_SQLEXPRESS;User ID=sa;Password=2BeChanged!;" ;
const string sqlQuery = @"
select tPatCulIntPatIDPk ,
tPatSFirstname ,
tPatSName ,
tPatDBirthday
from dbo.TPatientRaw
where tPatSName = @patientSurname
" ;
using ( SqlConnection connection = new SqlConnection(credentials) )
using ( SqlCommand cmd = connection.CreateCommand() )
using ( SqlDataAdapter sda = new SqlDataAdapter( cmd ) )
{
cmd.CommandText = sqlQuery ;
cmd.CommandType = CommandType.Text ;
connection.Open() ;
rows_returned = sda.Fill(dt) ;
connection.Close() ;
}
if ( dt.Rows.Count == 0 )
{
// query returned no rows
}
else
{
//write semicolon-delimited header
string[] columnNames = dt.Columns
.Cast<DataColumn>()
.Select( c => c.ColumnName )
.ToArray()
;
string header = string.Join("," , columnNames) ;
Console.WriteLine(header) ;
// write each row
foreach ( DataRow dr in dt.Rows )
{
// get each rows columns as a string (casting null into the nil (empty) string
string[] values = new string[dt.Columns.Count];
for ( int i = 0 ; i < dt.Columns.Count ; ++i )
{
values[i] = ((string) dr[i]) ?? "" ; // we'll treat nulls as the nil string for the nonce
}
// construct the string to be dumped, quoting each value and doubling any embedded quotes.
string data = string.Join( ";" , values.Select( s => "\""+s.Replace("\"","\"\"")+"\"") ) ;
Console.WriteLine(values);
}
}
None of these solutions worked for me. Instead, what worked was to go to a command line tool (or terminal in Mac), CD into the SDK/platform-tools directory, and then run this:
adb kill-server
then run this:
adb start-server
After I did this everything worked again. Why? Who knows.
On my MAC the path to the platform-tools folder was $HOME/Installations/adt-bundle-mac-x86_64-20130522/sdk/platform-tools It will probably be somewhere else on your machine.
I also found this page that presents some helpful steps:
http://android.okhelp.cz/android-emulator-wont-run-application-started-from-eclipse/
Have you considered using span
instead of div
? It is the in-line version of div
.
Here is an example using openssl_encrypt
//Encryption:
$textToEncrypt = "My Text to Encrypt";
$encryptionMethod = "AES-256-CBC";
$secretHash = "encryptionhash";
$iv = mcrypt_create_iv(16, MCRYPT_RAND);
$encryptedText = openssl_encrypt($textToEncrypt,$encryptionMethod,$secretHash, 0, $iv);
//Decryption:
$decryptedText = openssl_decrypt($encryptedText, $encryptionMethod, $secretHash, 0, $iv);
print "My Decrypted Text: ". $decryptedText;
It is possible that the offset
could be a non-integer, using em
as the measurement unit, relative font-sizes
in %
.
I also theorise that the offset
might not be a whole number when the zoom
isn't 100%
but that depends how the browser handles scaling.
In eclipse Galileo :
From there you can Add External Jars
Further into direction pointed out by Brian and based on sh (1.0.8+)
from sh import cd, ls
cd('/tmp')
print ls()
New line depends on your OS:
DOS & Windows: \r\n 0D0A (hex), 13,10 (decimal)
Unix & Mac OS X: \n, 0A, 10
Macintosh (OS 9): \r, 0D, 13
More details here: https://ccrma.stanford.edu/~craig/utility/flip/
When in doubt, use any freeware hex viewer/editor to see how a file encodes its new line.
For me, I use following guide to help me remember: 0D0A = \r\n = CR,LF = carriage return, line feed
You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'
The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.
You can use System.IO.Directory.GetParent()
to retrieve the parent directory of a given directory.
To change to python3, you can use the following command in terminal alias python=python3
.
Here's an example with a Windows path:
docker run -P -it --name organizr --mount src="/c/Users/MyUserName/AppData/Roaming/DockerConfigs/Organizr",dst=/config,type=bind organizrtools/organizr-v2:latest
As a side note, during all of this hair pulling, having to wrestle with figuring out, and retyping paths over and over and over again, I decided to whip up a small AutoHotkey
script to convert a Windows path to a "Docker Windows" formatted path. This way all I have to do is copy any Windows path that I want to use as a mount point to the clipboard, press the "Apps Key" on the keyboard, and it'll format it into a path format that Docker appreciates.
For example:
Copy this to your clipboard:
C:\Users\My PC\AppData\Roaming\DockerConfigs\Organizr
press the Apps Key
while the cursor is where you want it on the command-line, and it'll paste this there:
"/c/Users/My PC/AppData/Roaming/DockerConfigs/Organizr"
Saves a lot to time for me. Here it is for anyone else who may find it useful.
; --------------------------------------------------------------------------------------------------------------
;
; Docker Utility: Convert a Windows Formatted Path to a Docker Formatter Path
; Useful for (example) when mounting Windows volumes via the command-line.
;
; By: J. Scott Elblein
; Version: 1.0
; Date: 2/5/2019
;
; Usage: Cut or Copy the Windows formatted path to the clipboard, press the AppsKey on your keyboard
; (usually right next to the Windows Key), it'll format it into a 'docker path' and enter it
; into the active window. Easy example usage would be to copy your intended volume path via
; Explorer, place the cursor after the "-v" in your Docker command, press the Apps Key and
; then it'll place the formatted path onto the line for you.
;
; TODO:: I may or may not add anything to this depending on needs. Some ideas are:
;
; - Add a tray menu with the ability to do some things, like just replace the unformatted path
; on the clipboard with the formatted one rather than enter it automatically.
; - Add 'smarter' handling so the it first confirms that the clipboard text is even a path in
; the first place. (would need to be able to handle Win + Mac + Linux)
; - Add command-line handling so the script doesn't need to always be in the tray, you could
; just pass the Windows path to the script, have it format it, then paste and close.
; Also, could have it just check for a path on the clipboard upon script startup, if found
; do it's job, then exit the script.
; - Add an 'all-in-one' action, to copy the selected Windows path, and then output the result.
; - Whatever else comes to mind.
;
; --------------------------------------------------------------------------------------------------------------
#NoEnv
SendMode Input
SetWorkingDir %A_ScriptDir%
AppsKey::
; Create a new var, store the current clipboard contents (should be a Windows path)
NewStr := Clipboard
; Rip out the first 2 chars (should be a drive letter and colon) & convert the letter to lowercase
; NOTE: I could probably replace the following 3 lines with a regexreplace, but atm I'm lazy and in a rush.
tmpVar := SubStr(NewStr, 1, 2)
StringLower, tmpVar, tmpVar
; Replace the uppercase drive letter and colon with the lowercase drive letter and colon
NewStr := StrReplace(NewStr, SubStr(NewStr, 1, 2), tmpVar)
; Replace backslashes with forward slashes
NewStr := StrReplace(NewStr, "\", "/")
; Replace all colons with nothing
NewStr := StrReplace(NewStr, ":", "")
; Remove the last char if it's a trailing forward slash
NewStr := RegExReplace(NewStr, "/$")
; Append a leading forward slash if not already there
if RegExMatch(NewStr, "^/") == 0
NewStr := "/" . NewStr
; If there are any spaces in the path ... wrap in double quotes
if RegExMatch(NewStr, " ") > 0
NewStr := """" . NewStr . """"
; Send the result to the active window
SendInput % NewStr
I was in same problem.
Below command solved my problem
pip3 install --upgrade https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.0.0-py3-none-any.whl
to find the list of all the urls based on the python version and CPU or GPU only refer to: https://www.tensorflow.org/install/pip
You use the modulo operator:
while(score)
{
printf("%d\n", score % 10);
score /= 10;
}
Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.
There is now a beta available of Google Maps KML Importing Utility.
It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams
KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());
or local resources
KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());
After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.
layer.addLayerToMap();
I wrote this code. I guess it can help someone...
Public Function VerifyCollection()
For i = 1 To 10 Step 1
MyKey = "A"
On Error GoTo KillError:
Dispersao.Add 1, MyKey
GoTo KeepInForLoop
KillError: 'If My collection already has the key A Then...
count = Dispersao(MyKey)
Dispersao.Remove (MyKey)
Dispersao.Add count + 1, MyKey 'Increase the amount in relationship with my Key
count = Dispersao(MyKey) 'count = new amount
On Error GoTo -1
KeepInForLoop:
Next
End Function
You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
I would caution you: if you are using absolute paths, then your application cannot be installed in a "subdirectory" of the server!
eg, http://yourserver.com/yourapp may work, but http://myserver.com/apps/yourapp will not!
It worked using PSCP. Instructions:
set PATH=<path to the pscp.exe file>
pscp
use the following command to copy file form remote server to the local system
pscp [options] [user@]host:source target
So to copy the file /etc/hosts
from the server example.com
as user fred
to the file
c:\temp\example-hosts.txt
, you would type:
pscp [email protected]:/etc/hosts c:\temp\example-hosts.txt
If you are using this module with Python3 and having trouble with import. try this.
pip uninstall crypto
pip uninstall pycryptodome
pip install pycryptodome
Good Luck!
I have set up Volley as a separate Project. That way its not tied to any project and exist independently.
I also have a Nexus server (Internal repo) setup so I can access volley as
compile 'com.mycompany.volley:volley:1.0.4' in any project I need.
Any time I update Volley project, I just need to change the version number in other projects.
I feel very comfortable with this approach.
Because setting the div
's display
style property to ""
doesn't change anything in the CSS rule itself. That basically just creates an "empty," inline CSS rule, which has no effect beyond clearing the same property on that element.
You need to set it to something that has a value:
document.getElementById('mybox').style.display = "block";
What you're doing would work if you were replacing an inline style on the div, like this:
<div id="myBox" style="display: none;"></div>
document.getElementById('mybox').style.display = "";
There is more than one way to do this.
Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html
At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.
If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.
SELECT * FROM V$TRANSACTION
WHERE STATUS='ACTIVE';
See: http://forums.oracle.com/forums/thread.jspa?threadID=691061
GO to SSMS and try this
Menu >> Tools >> Options >> Designers >> Uncheck “Prevent Saving changes that require table re-creation”.
Here is a very good explanation on this: http://blog.sqlauthority.com/2009/05/18/sql-server-fix-management-studio-error-saving-changes-in-not-permitted-the-changes-you-have-made-require-the-following-tables-to-be-dropped-and-re-created-you-have-either-made-changes-to-a-tab/
OS : Windows 7 & IIS 7
If you still have permission denied after adding IUSR & NETWORK SERVICE. Add also IIS_WPG. The addition of this last user solved my problem.
For people who can't find those users: when you're trying to add a user in security of the folder (properties of the folder), click on "Advanced" of the window "Select Users or Groups". Change the location to the computer name then click on "Find Now". You'll find those users in the list below.
Get "adbd insecure" from google play store, it helps give write access to custom roms that have it secured my the manufacturers.
If you are trying to do basic auth, you can try this:
const username = ''
const password = ''
const token = Buffer.from(`${username}:${password}`, 'utf8').toString('base64')
const url = 'https://...'
const data = {
...
}
axios.post(url, data, {
headers: {
'Authorization': `Basic ${token}`
},
})
This worked for me. Hope that helps
you can always do this:
jQuery.fn.animateAuto = function(prop, speed, callback){
var elem, height, width;
return this.each(function(i, el){
el = jQuery(el), elem = el.clone().css({"height":"auto","width":"auto"}).appendTo("body");
height = elem.css("height"),
width = elem.css("width"),
elem.remove();
if(prop === "height")
el.animate({"height":height}, speed, callback);
else if(prop === "width")
el.animate({"width":width}, speed, callback);
else if(prop === "both")
el.animate({"width":width,"height":height}, speed, callback);
});
}
here is a fiddle: http://jsfiddle.net/Zuriel/faE9w/2/
from the current directory provide the full path to the script directory to execute the command
/root/server/user/home/bin/script.sh
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script
. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat
. This will be in the $_POST
array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready();
enviroment
var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;
) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts()
function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100
or $('footer').offset().top
for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.log
s in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
use this in your view
<EditText
....
....
android:imeOptions="actionDone"
android:id="@+id/edtName"
/>
So why don't you simply use a key-value literal?
var params = {
'slide0001.html': 'Looking Ahead',
'slide0002.html': 'Forecase',
...
};
return params['slide0001.html']; // returns: Looking Ahead
Suppose you want to create a vector x whose length is zero. Now let v be any vector.
> v<-c(4,7,8)
> v
[1] 4 7 8
> x<-v[0]
> length(x)
[1] 0
Marquee (<marquee>
) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!
In one line we can set image with this code
[buttonName setBackgroundImage:[UIImage imageNamed:@"imageName"] forState:UIControlStateNormal];
You can use the services console, clicking on the left hand side and then selecting the "Connect to another computer" option in the Action menu.
If you wish to use the command line only, you can use
sc \\machine stop <service>
InnoDB doesn't cope well with 'random' primary keys. Try a sequential key or auto-increment, and I believe you'll see better performance. Your 'real' key field could still be indexed, but for a bulk insert you might be better off dropping and recreating that index in one hit after the insert in complete. Would be interested to see your benchmarks for that!
Some related questions
Pretty much what others have put before, but as a one liner that can be put at the beginning of a batch command. (Well, usually after @echo off.)
net.exe session 1>NUL 2>NUL || (Echo This script requires elevated rights. & Exit /b 1)
I have improved on the solution above by providing support for different log levels and by changing the log levels automatically depending on if the code is being run on a live device or on the emulator.
public class Log {
final static int WARN = 1;
final static int INFO = 2;
final static int DEBUG = 3;
final static int VERB = 4;
static int LOG_LEVEL;
static
{
if ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)) {
LOG_LEVEL = VERB;
} else {
LOG_LEVEL = INFO;
}
}
/**
*Error
*/
public static void e(String tag, String string)
{
android.util.Log.e(tag, string);
}
/**
* Warn
*/
public static void w(String tag, String string)
{
android.util.Log.w(tag, string);
}
/**
* Info
*/
public static void i(String tag, String string)
{
if(LOG_LEVEL >= INFO)
{
android.util.Log.i(tag, string);
}
}
/**
* Debug
*/
public static void d(String tag, String string)
{
if(LOG_LEVEL >= DEBUG)
{
android.util.Log.d(tag, string);
}
}
/**
* Verbose
*/
public static void v(String tag, String string)
{
if(LOG_LEVEL >= VERB)
{
android.util.Log.v(tag, string);
}
}
}
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
I just had the same problem and all I did was delete the user log in credentials in sql server using another user id and adding them back.
Without plugin cross browser with setInterval:
function rotatePic() {
jQuery({deg: 0}).animate(
{deg: 360},
{duration: 3000, easing : 'linear',
step: function(now, fx){
jQuery("#id").css({
'-moz-transform':'rotate('+now+'deg)',
'-webkit-transform':'rotate('+now+'deg)',
'-o-transform':'rotate('+now+'deg)',
'-ms-transform':'rotate('+now+'deg)',
'transform':'rotate('+now+'deg)'
});
}
});
}
var sec = 3;
rotatePic();
var timerInterval = setInterval(function() {
rotatePic();
sec+=3;
if (sec > 30) {
clearInterval(timerInterval);
}
}, 3000);
The earliest versions of Unix time had a 32-bit integer incrementing at a rate of 60 Hz, which was the rate of the system clock on the hardware of the early Unix systems. The value 60 Hz still appears in some software interfaces as a result. The epoch also differed from the current value. The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".
You can't do it directly. There are a number of ways to do it:
Use a std::stringstream
:
std::ostringstream s;
s << "(" << c1 << ", " << c2 << ")";
storedCorrect[count] = s.str()
Use boost::lexical_cast
:
storedCorrect[count] = "(" + boost::lexical_cast<std::string>(c1) + ", " + boost::lexical_cast<std::string>(c2) + ")";
Use std::snprintf
:
char buffer[256]; // make sure this is big enough!!!
snprintf(buffer, sizeof(buffer), "(%g, %g)", c1, c2);
storedCorrect[count] = buffer;
There are a number of other ways, using various double-to-string conversion functions, but these are the main ways you'll see it done.
You might also try an elseif.
x <- 1
if (x ==1){
print('same')
} else if (x > 1){
print('bigger')
} else {
print('smaller')
}
These days, the repeat
string method is implemented almost everywhere. (It is not in Internet Explorer.) So unless you need to support older browsers, you can simply write:
"a".repeat(10)
Before repeat
, we used this hack:
Array(11).join("a") // create string with 10 a's: "aaaaaaaaaa"
(Note that an array of length 11 gets you only 10 "a"s, since Array.join
puts the argument between the array elements.)
Simon also points out that according to this jsperf, it appears that it's faster in Safari and Chrome (but not Firefox) to repeat a character multiple times by simply appending using a for loop (although a bit less concise).
This is a late answer, but for completeness: it is difficult to get even close to fetching 90% all favicons.
A while ago I wrote a WordPress plugin which attempts to get closer to 100%.
This is how it works:
It starts by searching existing favicon repositories such as Google favicons and GetFavicons for the favicon.
If none of them returns an icon, the plugin attempts to get the icon itself. This involves traversing several pages on the domain.
The plugin then inspects the physical image file, because on some servers files get returned with the incorrect mime types.
The code is still not perfect because in the details you will find many weird situations: people have wrongly coded paths, e.g. img/favicon.ico
where img
is not in the root, duplicate headers in HTML output, different server responses from the head and body etc.
The core of the fetching part is here so you can reverse-engineer it, but be aware that validating the response should be done (checking image filetype, mime etc.).
From your config file, it seems like you're only excluding node_modules
from being parsed with babel-loader
, but not from being bundled.
In order to exclude node_modules
and native node libraries from bundling, you need to:
target: 'node'
to your webpack.config.js
. This will exclude native node modules (path, fs, etc.) from being bundled.node_modules
.So your result config file should look like:
var nodeExternals = require('webpack-node-externals');
...
module.exports = {
...
target: 'node', // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
...
};
Move path\to\anaconda
in the PATH above path\to\python
You can list all the files, in the aws s3 bucket using the command
aws s3 ls path/to/file
and to save it in a file, use
aws s3 ls path/to/file >> save_result.txt
if you want to append your result in a file otherwise:
aws s3 ls path/to/file > save_result.txt
if you want to clear what was written before.
It will work both in windows and Linux.
With regards to the poor performance there are any number of things it could be, and it really ought to be a separate question. However, there is one obvious thing that could be a problem:
WHERE TO_CHAR(HISTORY_DATE, 'DD.MM.YYYY') = '06.02.2009')
If HISTORY_DATE really is a date column and if it has an index then this rewrite will perform better:
WHERE HISTORY_DATE = TO_DATE ('06.02.2009', 'DD.MM.YYYY')
This is because a datatype conversion disables the use of a B-Tree index.
I use this. It works in iOS 8
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let image = UIImage(named: "YOURIMAGE")
navigationItem.titleView = UIImageView(image: image)
}
And here is an example how you can do it with CGRect.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 38, height: 38))
imageView.contentMode = .ScaleAspectFit
let image = UIImage(named: "YOURIMAGE")
imageView.image = image
navigationItem.titleView = imageView
}
Hope this will help.
Although most answers are suggesting RESEED
to 0
, and while some see this as a flaw for TRUNCATED
tables, Microsoft has a solution that excludes the ID
DBCC CHECKIDENT ('[TestTable]', RESEED)
This will check the table and reset to the next ID
. This has been available since MS SQL 2005 to current.
I had numpy installed on the same environment both by pip and by conda, and simply removing and reinstalling either was not enough.
I had to reinstall both.
I don't know why it suddenly happened, but the solution was
pip uninstall numpy
conda uninstall numpy
uninstalling from conda also removed torch
and torchvision
.
then
conda install pytorch-cpu torchvision-cpu -c pytorch
and
pip install numpy
this resolved the issue for me.
Found mine after:
whereis cuda
at
cuda: /usr/lib/cuda /usr/include/cuda.h
with
nvcc --version
CUDA Version 9.1.85
try this,
$("document").ready(function(){
$("your id here").trigger("click");
});
Just use Apache Commons IO
List<String> lines = IOUtils.readLines(new FileInputStream("path/of/text"));
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
and your method
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
For anyone who doesn't have the guarantee that the list will not be null, you can use the null-conditional operator to safely check for null and empty lists in a single conditional statement:
if (list?.Any() != true)
{
// Handle null or empty list
}
.fadeOut{
background-color: rgba(255, 0, 0, 0.83);
border-radius: 8px;
box-shadow: silver 3px 3px 5px 0px;
border: 2px dashed yellow;
padding: 3px;
}
.fadeOut.end{
transition: all 1s ease-in-out;
background-color: rgba(255, 0, 0, 0.0);
box-shadow: none;
border: 0px dashed yellow;
border-radius: 0px;
}
The full solution is not often found in one place ...
1) Create an app config file and name it "yourDllName.dll.config"
2) Right click on the config file created above in VS Solution Explorer, click properties
--- set "Build Action" = Content
--- set "Copy To Output Directory" = Always
3) Add an appSettings section to the configuration file (yourDllName.dll.config) with your yourKeyName and yourKeyValue
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="yourKeyName" value="yourKeyValue"/>
</appSettings>
</configuration>
4) Add System.Configuration to your dll/class/project references
5) Add the using statements to your code where you intend to access the config setting
using System.Configuration;
using System.Reflection;
6) To access the value
string keyValue = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location).AppSettings.Settings["yourKeyName"].Value;
7) rejoice, it works
IMHO, this should only be used when developing a new dll/library.
#if (DEBUG && !FINALTESTING)
string keyValue = ConfigurationManager.OpenExeConfiguration...(see 6 above)
#else
string keyValue = ConfigurationManager.AppSettings["yourKeyName"];
#endif
The config file ends up being a great reference, for when you add the dll's appSettings to your actual application.
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
There are cases where you don't want to use v-model
. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.
In these cases, it's not a good idea to use either watchers or computed properties.
Instead, take your v-model
and split it as above answer indicates
<input
:value="something"
@input="something = $event.target.value"
>
In practice, if you are decoupling your logic this way, you'll probably be calling a method.
This is what it would look like in a real world scenario:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
<p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var app = new Vue({_x000D_
el: "#app",_x000D_
data: function(){_x000D_
return {_x000D_
extendedCost: 0,_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
_onInputExtendedCost: function($event) {_x000D_
this.extendedCost = parseInt($event.target.value);_x000D_
// Go update other inputs here_x000D_
}_x000D_
}_x000D_
});_x000D_
</script>
_x000D_
targetList = list1.Concat(list2).ToList();
It's working fine I think so. As previously said, Concat returns a new sequence and while converting the result to List, it does the job perfectly.
I know this is very old, but none of these answers helped me, so I'm adding my answer. This, like @yichengliu's answer, uses the Pseudo ::after
element.
#div {
position: relative;
}
#div::after {
content: '';
position: absolute;
right: 0;
width: 1px;
height: 100%;
z-index: -1;
-webkit-box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
-moz-box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
box-shadow: 0px 0px 5px 0px rgba(0,0,0,1);
}
/*or*/
.filter.right::after {
content: '';
position: absolute;
right: 0;
top: 0;
width: 1px;
height: 100%;
background: white;
z-index: -1;
-webkit-filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 1));
filter: drop-shadow(0px 0px 1px rgba(0, 0, 0, 1));
}
If you decide to change the X of the drop shadow (first pixel measurement of the drop-shadow
or box-shadow
), changing the width will help so it doesn't look like there is a white gap between the div and the shadow.
If you decide to change the Y of the drop shadow (second pixel measurement of the drop-shadow
or box-shadow
), changing the height will help for the same reason as above.
Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.
a = 5
makes the variable name a
to refer to the integer 5. Later, a = "hello"
makes the variable name a
to refer to a string containing "hello". Static typed languages would have you declare int a
and then a = 5
, but assigning a = "hello"
would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a
refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.a = "5"
(the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5
to get "hello5"
.Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...
Using pgadmin4 :
Now there you can enable or disable login, roles and other options
git fetch [remotename]
However you'll need to merge any changes into your local branches. If you're on a branch that's tracking a remote branch on Github, then
git pull
will first do a fetch, and then merge in the tracked branch
opacity
on parent element sets it for the whole sub DOM treeYou can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity
works I'm afraid.
What you can do is to have two sibling elements in one container and set transparent one's positioning:
<div id="container">
<div id="transparent"></div>
<div id="content"></div>
</div>
then you have to set transparent position: absolute/relative
so its content sibling will be rendered over it.
rgba
can do background transparency of coloured backgroundsrgba
colour setting on element's background-color
will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba
. That works as well.
But be advised that rgba
may not be supported by your required browsers.
But if you're after some kind of masking the whole page, this is usually done by adding a separate div
with this set of styles:
position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);
Then when you display the content it should have a higher z-index
. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.
SELECT *
FROM events
WHERE start <= '2013-07-22' OR end >= '2013-06-13'
Adding to the answer given by @insomniac. You can create a Map
to put the parameter for RequestBody
including image.
Code for Interface
public interface ApiInterface {
@Multipart
@POST("/api/Accounts/editaccount")
Call<User> editUser (@Header("Authorization") String authorization, @PartMap Map<String, RequestBody> map);
}
Code for Java class
File file = new File(imageUri.getPath());
RequestBody fbody = RequestBody.create(MediaType.parse("image/*"), file);
RequestBody name = RequestBody.create(MediaType.parse("text/plain"), firstNameField.getText().toString());
RequestBody id = RequestBody.create(MediaType.parse("text/plain"), AZUtils.getUserId(this));
Map<String, RequestBody> map = new HashMap<>();
map.put("file\"; filename=\"pp.png\" ", fbody);
map.put("FirstName", name);
map.put("Id", id);
Call<User> call = client.editUser(AZUtils.getToken(this), map);
call.enqueue(new Callback<User>() {
@Override
public void onResponse(retrofit.Response<User> response, Retrofit retrofit)
{
AZUtils.printObject(response.body());
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
});
I was in need to decode URL in a Bash script. So I decide to use PHP in this way:
$ cat url-decode.sh
#!/bin/bash
URL='url=https%3a%2f%2f1%2fecp%2f'
/usr/bin/php -r '$arg1 = $argv[1];echo rawurldecode($arg1);' "$URL"
Sample output:
$ ./url-decode.sh
url=https://1/ecp/
if (android.os.Build.VERSION.SDK_INT >= 21) {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}
Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.
Try find / -iname '*numpy*'
DataTable dr_art_line_2 = ds.Tables["QuantityInIssueUnit"];
for (int i = 0; i < dr_art_line_2.Rows.Count; i++)
{
QuantityInIssueUnit_value = Convert.ToInt32(dr_art_line_2.Rows[i]["columnname"]);
//Similarly for QuantityInIssueUnit_uom.
}
In simple way you can go with explode($delimiter, $string)
;
But in a broad way, with Manual Programming :
$string = "ab,cdefg,xyx,ht623";
$resultArr = [];
$strLength = strlen($string);
$delimiter = ',';
$j = 0;
$tmp = '';
for ($i = 0; $i < $strLength; $i++) {
if($delimiter === $string[$i]) {
$j++;
$tmp = '';
continue;
}
$tmp .= $string[$i];
$resultArr[$j] = $tmp;
}
Outpou : print_r($resultArr);
Array
(
[0] => ab
[1] => cdefg
[2] => xyx
[3] => ht623
)
You can do it by making the background into a pattern:
<defs>
<pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
<image href="wall.jpg" x="0" y="0" width="100" height="100" />
</pattern>
</defs>
Adjust the width and height according to your image, then reference it from the path like this:
<path d="M5,50
l0,100 l100,0 l0,-100 l-100,0
M215,100
a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
M265,50
l50,100 l-100,0 l50,-100
z"
fill="url(#img1)" />
I would go with xml and xpath:
dir C:\Projects\project_*\project*.config -recurse | foreach-object{
$wc = [xml](Get-Content $_.fullname)
$wc.SelectNodes("//add[@key='Environment'][@value='Dev']") | Foreach-Object {$_.value = 'Demo'}
$wc.Save($_.fullname)
}
var div = document.createElement("div");_x000D_
div.style.width = "100px";_x000D_
div.style.height = "100px";_x000D_
div.style.background = "red";_x000D_
div.style.color = "white";_x000D_
div.innerHTML = "Hello";_x000D_
_x000D_
document.getElementById("main").appendChild(div);
_x000D_
<body>_x000D_
<div id="main"></div>_x000D_
</body>
_x000D_
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
document.getElementById("main").appendChild(div);
OR
document.body.appendChild(div);
Use parent reference instead of document.body
.
Look at placing your radio buttons in a GroupBox.
As suggested by @andreas-hultgren in this answer and according to the npm docs:
If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.
However, for webapp development, Yeoman (a scaffolding tool that installs a peer-reviewed, pre-written package.json file amongst other things) places all packages in devDependencies and nothing in dependencies, so it appears that the use of --save-dev
is a safe bet in webapp development, at least.
Use not
, for example:
return not myval
Rather than changing owners, which might lock out other local users, or –some day– your own ruby server/deployment-things... running under a different user...
I would rather simply extend rights of that particular folder to... well, everybody:
cd /var/lib
sudo chmod -R a+w gems/
(I did encounter your error as well. So this is fairly verified.)
sh
files are unix (linux) shell executables files, they are the equivalent (but much more powerful) of bat
files on windows.
So you need to run it from a linux console, just typing its name the same you do with bat files on windows.
Here is some code (it's actually not Timsort as I originally thought, but it does work well) that does the trick without any boxing/unboxing. In my tests, it works 3-4 times faster than using Collections.sort with a List wrapper around the array.
// This code has been contributed by 29AjayKumar
// from: https://www.geeksforgeeks.org/sort/
static final int sortIntArrayWithComparator_RUN = 32;
// this function sorts array from left index to
// to right index which is of size atmost RUN
static void sortIntArrayWithComparator_insertionSort(int[] arr, IntComparator comparator, int left, int right) {
for (int i = left + 1; i <= right; i++)
{
int temp = arr[i];
int j = i - 1;
while (j >= left && comparator.compare(arr[j], temp) > 0)
{
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
// merge function merges the sorted runs
static void sortIntArrayWithComparator_merge(int[] arr, IntComparator comparator, int l, int m, int r) {
// original array is broken in two parts
// left and right array
int len1 = m - l + 1, len2 = r - m;
int[] left = new int[len1];
int[] right = new int[len2];
for (int x = 0; x < len1; x++)
{
left[x] = arr[l + x];
}
for (int x = 0; x < len2; x++)
{
right[x] = arr[m + 1 + x];
}
int i = 0;
int j = 0;
int k = l;
// after comparing, we merge those two array
// in larger sub array
while (i < len1 && j < len2)
{
if (comparator.compare(left[i], right[j]) <= 0)
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}
// copy remaining elements of left, if any
while (i < len1)
{
arr[k] = left[i];
k++;
i++;
}
// copy remaining element of right, if any
while (j < len2)
{
arr[k] = right[j];
k++;
j++;
}
}
// iterative sort function to sort the
// array[0...n-1] (similar to merge sort)
static void sortIntArrayWithComparator(int[] arr, IntComparator comparator) { sortIntArrayWithComparator(arr, lIntArray(arr), comparator); }
static void sortIntArrayWithComparator(int[] arr, int n, IntComparator comparator) {
// Sort individual subarrays of size RUN
for (int i = 0; i < n; i += sortIntArrayWithComparator_RUN)
{
sortIntArrayWithComparator_insertionSort(arr, comparator, i, Math.min((i + 31), (n - 1)));
}
// start merging from size RUN (or 32). It will merge
// to form size 64, then 128, 256 and so on ....
for (int size = sortIntArrayWithComparator_RUN; size < n; size = 2 * size)
{
// pick starting point of left sub array. We
// are going to merge arr[left..left+size-1]
// and arr[left+size, left+2*size-1]
// After every merge, we increase left by 2*size
for (int left = 0; left < n; left += 2 * size)
{
// find ending point of left sub array
// mid+1 is starting point of right sub array
int mid = Math.min(left + size - 1, n - 1);
int right = Math.min(left + 2 * size - 1, n - 1);
// merge sub array arr[left.....mid] &
// arr[mid+1....right]
sortIntArrayWithComparator_merge(arr, comparator, left, mid, right);
}
}
}
static int lIntArray(int[] a) {
return a == null ? 0 : a.length;
}
static interface IntComparator {
int compare(int a, int b);
}
For users who just want to put Background, Icon-Image and Text in one Button
from different files: Set on a Button
background, drawableTop/Bottom/Rigth/Left and padding attributes.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/home_btn_test"
android:drawableTop="@drawable/home_icon_test"
android:textColor="#FFFFFF"
android:id="@+id/ButtonTest"
android:paddingTop="32sp"
android:drawablePadding="-15sp"
android:text="this is text"></Button>
For more sophisticated arrangement you also can use RelativeLayout
(or any other layout) and make it clickable.
Tutorial: Great tutorial that covers both cases: http://izvornikod.com/Blog/tabid/82/EntryId/8/Creating-Android-button-with-image-and-text-using-relative-layout.aspx
One thing which seems like no one else mentioned: let's say you have a vertical LinearLayout
, so in order for the weights in layout/element/view inside it to work 100% properly - all of them must have layout_height
property (which must exist in your xml file) set to 0dp
. Seems like any other value would mess things up in some cases.
To change the stacking order for series in charts under Excel for Mac 2011:
I had a three series plot on the secondary axis, and the series I wanted on top was stuck on the bottom in defiance of the Move Up and Move Down buttons. It happened to be formatted as markers only. I inserted a line, and presto(!), I could change its order in the plot. Later I could remove the line and sometimes it could still be ordered, but sometimes not.
Note: You can play back the audio data only to the standard output device.
Currently, that is the mobile device speaker or a Bluetooth headset. You
cannot play sound files in the conversation audio during a call.
See official link
http://developer.android.com/guide/topics/media/mediaplayer.html
If you are trying to do an in-place update of text within a file, this is much easier to reason about in my mind.
grep -Rl text_to_find directory_to_search 2>/dev/null | while read line; do sed -i 's/text_to_find/replacement_text/g' $line; done
in
is the intended way to test for the existence of a key in a dict
.
d = {"key1": 10, "key2": 23}
if "key1" in d:
print("this will execute")
if "nonexistent key" in d:
print("this will not")
If you wanted a default, you can always use dict.get()
:
d = dict()
for i in range(100):
key = i % 10
d[key] = d.get(key, 0) + 1
and if you wanted to always ensure a default value for any key you can either use dict.setdefault()
repeatedly or defaultdict
from the collections
module, like so:
from collections import defaultdict
d = defaultdict(int)
for i in range(100):
d[i % 10] += 1
but in general, the in
keyword is the best way to do it.
The hashes are just because your column width is not enough to display the "number".
About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).
Regards
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
Create a "jump link" using the following format:
http://www.somesite.com/somepage#anchor
Where anchor is the id of the element you wish to link to on that page. Use browser development tools / view source to find the id of the element you wish to link to.
If the element doesnt have an id and you dont control that site then you cant do it.
It may be the typo if you incorrectly wrote the placeholder
word.
In my case I misspelled it as placehoder
and got the error like this:
AttributeError: 'module' object has no attribute 'placehoder'
Which specific index? If you want 'Add New' to be first on the dropdownlist you can add it though the code like this:
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server">
<asp:ListItem Text="Add New" Value="0" />
</asp:DropDownList>
If you want to add it at a different index, maybe the last then try:
ListItem lst = new ListItem ( "Add New" , "0" );
DropDownList1.Items.Insert( DropDownList1.Items.Count-1 ,lst);
Just adding to Jason's answer, the .
selector is only for classes. If you want to select something other than the element, id, or class, you need to wrap it in square brackets.
e.g.
$('element[attr=val]')
JEP 354: Switch Expressions (Preview) in JDK-13 and JEP 361: Switch Expressions (Standard) in JDK-14 will extend the switch statement so it can be used as an expression.
Now you can:
case L ->
):
The code to the right of a "case L ->" switch label is restricted to be an expression, a block, or (for convenience) a throw statement.
To yield a value from a switch expression, the
break
with value statement is dropped in favor of ayield
statement.
So the demo from the answers (1, 2) might look like this:
public static void main(String[] args) {
switch (args[0]) {
case "Monday", "Tuesday", "Wednesday" -> System.out.println("boring");
case "Thursday" -> System.out.println("getting better");
case "Friday", "Saturday", "Sunday" -> System.out.println("much better");
}
If you need to have the script keep working on python2 and 3 as I did, this might help someone
import sys
if sys.version_info[0] >= 3:
unicode = str
and can then just do for example
foo = unicode.lower(foo)
Although it is a late answer, I would say this will help you...
$query = $this->db
->select('user_id, count(user_id) AS num_of_time')
->group_by('user_id')
->order_by('num_of_time', 'desc')
->get('tablename', 10);
print_r($query->result());
You can try this it will help for you.You can't get path from WhatsApp directly.If you need an file path first copy file and send new file path. Using the code below
public static String getFilePathFromURI(Context context, Uri contentUri) {
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
File copyFile = new File(TEMP_DIR_PATH + fileName+".jpg");
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
Then IOUtils class is like below
public class IOUtils {
private static final int BUFFER_SIZE = 1024 * 2;
private IOUtils() {
// Utility class.
}
public static int copy(InputStream input, OutputStream output) throws Exception, IOException {
byte[] buffer = new byte[BUFFER_SIZE];
BufferedInputStream in = new BufferedInputStream(input, BUFFER_SIZE);
BufferedOutputStream out = new BufferedOutputStream(output, BUFFER_SIZE);
int count = 0, n = 0;
try {
while ((n = in.read(buffer, 0, BUFFER_SIZE)) != -1) {
out.write(buffer, 0, n);
count += n;
}
out.flush();
} finally {
try {
out.close();
} catch (IOException e) {
Log.e(e.getMessage(), e.toString());
}
try {
in.close();
} catch (IOException e) {
Log.e(e.getMessage(), e.toString());
}
}
return count;
}
}
Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).
<div class="container">
<div class="row">
<div class="col-3 col-md-6">
<div class="card card-block">1</div>
</div>
<div class="col-6 col-md-12 flex-md-last">
<div class="card card-block">3</div>
</div>
<div class="col-3 col-md-6 ">
<div class="card card-block">2</div>
</div>
</div>
Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.
make use of the jackson JSON processor
ObjectMapper mapper = new ObjectMapper();
Book book = mapper.readValue(request.getInputStream(),Book.class);
Those are the basic decision orders that you have in most of the programming language; it helps you to decide the flow of actions that your program is gonna do. The if is telling the compiler that you have a question, and the question is the condition between parenthesis
if (condition) {
thingsToDo()..
}
the else part is an addition to this structure to tell the compiler what to do if the condition is false
if (condition) {
thingsToDo()..
} else {
thingsToDoInOtherCase()..
}
you can combine those to form a else if which is when the first condition is false but you want to do another question before to decide what to do.
if (condition) {
thingsToDo()..
} else if (condition2) {
thingsToDoInTheSecondCase()..
}else {
thingsToDoInOtherCase()..
}
the problem occurs because of the name of column is in camel case internally it wraps it in " "(double quotes) to solve this, at the time of inserting values in table use single quotes ('')
e.g. insert into schema_name.table_name values(' ',' ',' ');
Just follow the requirements listed on the project's page: https://pypi.org/project/pgmagick/
you can simple use some div
to make a container and the display: flex;
to make the content appear side-by-side like this:
CSS
.splitscreen {
display:flex;
}
.splitscreen .left {
flex: 1;
}
.splitscreen .right {
flex: 1;
}
HTML
<div class="splitscreen">
<div class="left">
<!-- content -->
</div>
<div class="right">
<!-- content -->
</div>
</div>
using flex
you say who will use more space on the screen.
Oh man, one of my pet peeves.
inline
is more like static
or extern
than a directive telling the compiler to inline your functions. extern
, static
, inline
are linkage directives, used almost exclusively by the linker, not the compiler.
It is said that inline
hints to the compiler that you think the function should be inlined. That may have been true in 1998, but a decade later the compiler needs no such hints. Not to mention humans are usually wrong when it comes to optimizing code, so most compilers flat out ignore the 'hint'.
static
- the variable/function name cannot be used in other translation units. Linker needs to make sure it doesn't accidentally use a statically defined variable/function from another translation unit.
extern
- use this variable/function name in this translation unit but don't complain if it isn't defined. The linker will sort it out and make sure all the code that tried to use some extern symbol has its address.
inline
- this function will be defined in multiple translation units, don't worry about it. The linker needs to make sure all translation units use a single instance of the variable/function.
Note: Generally, declaring templates inline
is pointless, as they have the linkage semantics of inline
already. However, explicit specialization and instantiation of templates require inline
to be used.
Specific answers to your questions:
When should I write the keyword 'inline' for a function/method in C++?
Only when you want the function to be defined in a header. More exactly only when the function's definition can show up in multiple translation units. It's a good idea to define small (as in one liner) functions in the header file as it gives the compiler more information to work with while optimizing your code. It also increases compilation time.
When should I not write the keyword 'inline' for a function/method in C++?
Don't add inline just because you think your code will run faster if the compiler inlines it.
When will the compiler not know when to make a function/method 'inline'?
Generally, the compiler will be able to do this better than you. However, the compiler doesn't have the option to inline code if it doesn't have the function definition. In maximally optimized code usually all private
methods are inlined whether you ask for it or not.
As an aside to prevent inlining in GCC, use __attribute__(( noinline ))
, and in Visual Studio, use __declspec(noinline)
.
Does it matter if an application is multithreaded when one writes 'inline' for a function/method?
Multithreading doesn't affect inlining in any way.
You can write your query like so:
SELECT * FROM MyTable WHERE (A LIKE '%text1%' OR A LIKE '%text2%')
The %
is a wildcard, meaning that it searches for all rows where column A contains either text1 or text2
This can be used in v5.3.2 to goto a date after initialization
calendar.gotoDate( '2020-09-12' );
eg on datepicker change
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
...
initialDate: '2020-09-02',
...
});
$(".date-picker").change(function(){
var date = $(this).val();
calendar.gotoDate( date );
});
View > Quick Switch Scheme > Keymap > Eclipse
use this option for eclipse keymap or if u want to go with AndroidStudio keymap then follow below link
Click here for Official Android Studio Keymap Refference guide
you may find default keymap referrence in
AndroidStudio --> Help-->Default keymap refrence
I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.
dangerouslySetInnerHtml
to embed the <video>
code. For example:<div dangerouslySetInnerHTML={{ __html: `
<video class="video-js" playsinline autoplay loop muted>
<source src="../video_path.mp4" type="video/mp4"/>
</video>`}}
/>
Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)
The return statement only makes sense inside functions:
def foo():
while True:
return False
I know this is a very old post but this may help someone:
You can create a method, so whenever you need to pause you can type pause(1000)
or any other millisecond value:
public static void pause(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.err.format("IOException: %s%n", e);
}
}
This is inserted just above the public static void main(String[] args)
, inside the class. Then, to call on the method, type pause(ms)
but replace ms
with the number of milliseconds to pause. That way, you don't have to insert the entire try-catch statement whenever you want to pause.
I went through all of these answers and none of them worked for me unfortunately. However, I found this extremely simple way, after about an hour of searching : )
myView.layer.backgroundColor = CGColorCreateGenericRGB(0, 0, 0, 0.9);
Hope below Oracle query will work.
Select First_column,LISTAGG(second_column,',')
WITHIN GROUP (ORDER BY second_column) as Sec_column,
LISTAGG(third_column,',')
WITHIN GROUP (ORDER BY second_column) as thrd_column
FROM tablename
GROUP BY first_column
Please note that the below described service is no longer available as it was based on FLV media (Flash)
This project which utilizes the Red5, Flex and PHP for Live Video Streaming and Recording has many features
Stream Live video to the viewers
Record the streams from your cam or other video input devices to the server
Preview the recorded streams and files and thumbnail the frame which you would like to display for the video.
Upload the videos from your computer and convert them to FLV which can be streamed using Red5 .
Choose from any resolutions
Can be plugged to any script
Each website user can have a separate Directory for storing their videos and thumbnails use this link http://code.google.com/p/red5-flex-streamer/
Here is a solution that will automatically convert to tabs whenever you open a file.
Create this file: .../Packages/User/on_file_load.py
:
import sublime
import sublime_plugin
class OnFileLoadEventListener(sublime_plugin.EventListener):
def on_load_async(self, view):
view.run_command("unexpand_tabs")
NOTE. It causes the file to be in an unsaved state after opening it, even if no actual space-to-tab conversion took place... maybe some can help with a fix for that...
If you have installed Visual Studio 2012 RC, then it installed .NET 4.5 RC.
Uninstall .NET 4.5 RC, and install the version you need (4.0 for VS 2010). This should clear up any problems you are having.
This solved the same problem. There is no need to uninstall Visual Studio.
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
To quote other people:
A head is simply a reference to a commit object. Each head has a name (branch name or tag name, etc). By default, there is a head in every repository called master. A repository can contain any number of heads. At any given time, one head is selected as the “current head.” This head is aliased to HEAD, always in capitals".
Note this difference: a “head” (lowercase) refers to any one of the named heads in the repository; “HEAD” (uppercase) refers exclusively to the currently active head. This distinction is used frequently in Git documentation.
Another good source that quickly covers the inner workings of git (and therefor a better understanding of heads/HEAD) can be found here. References (ref:) or heads or branches can be considered like post-it notes stuck onto commits in the commit history. Usually they point to the tip of series of commits, but they can be moved around with git checkout
or git reset
etc.
SELECT
AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit,
BillLimit, Mode, PNotes, gtab82.memno
FROM
VCustomer AS v1
INNER JOIN
gtab82 ON gtab82.memacid = v1.AcId
WHERE (AcGrCode = '204' OR CreDebt = 'True')
AND Masked = 'false'
ORDER BY AcName
You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer
but only use it in the ON
clause for uncertain reasons. You may want to review that aspect of your code.
I got this error when had an error in Pom.
You can use:
For example:
// simple class who output his value
class ConsoleOutput
{
public:
ConsoleOutput(int value):m_value(value) { }
int Value() const { return m_value; }
private:
int m_value;
};
// functional object
class Predicat
{
public:
void operator()(ConsoleOutput const& item)
{
std::cout << item.Value() << std::endl;
}
};
void main()
{
// fill list
std::vector<ConsoleOutput> list;
list.push_back(ConsoleOutput(1));
list.push_back(ConsoleOutput(8));
// 1) using size_t
for (size_t i = 0; i < list.size(); ++i)
{
std::cout << list.at(i).Value() << std::endl;
}
// 2) iterators + distance, for std::distance only non const iterators
std::vector<ConsoleOutput>::iterator itDistance = list.begin(), endDistance = list.end();
for ( ; itDistance != endDistance; ++itDistance)
{
// int or size_t
int const position = static_cast<int>(std::distance(list.begin(), itDistance));
std::cout << list.at(position).Value() << std::endl;
}
// 3) iterators
std::vector<ConsoleOutput>::const_iterator it = list.begin(), end = list.end();
for ( ; it != end; ++it)
{
std::cout << (*it).Value() << std::endl;
}
// 4) functional objects
std::for_each(list.begin(), list.end(), Predicat());
}
Or you could use something like the following. Pay attention to "\n":
/**
* Created by mona on 3/26/16.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
public class FileExample {
public static void main (String[] args) throws java.io.IOException {
File newFile = new File("tweet.txt");
FileWriter fileWriter = new FileWriter(newFile);
fileWriter.write("Mona Jalal");
fileWriter.append("\nMona Mona");
fileWriter.close();
FileReader fileReader = new FileReader(newFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
fileReader.close();
bufferedReader.close();
}
}
For v1.19.0 for JQuery Validation I found this one line of code worked for me:
$('.field-validation-error').removeClass('field-validation-error').addClass('field-validation-valid').html('');
In effect making the field appear valid to the user but when they click submit again the validation re-fires.
The print()
function returns None
. You are trying to index None. You can not, because 'NoneType' object is not subscriptable
.
Put the [0]
inside the brackets. Now you're printing everything, and not just the first term.
Please note that you should not use any png when you are testing this , first work with jpg .
$myImage = "images/logos/mylogo.jpg"; // this is where you get your Image
$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);
A more explicit option is to project collection to an IEnumerable of KeyValuePair
and then convert it to a Dictionary.
Dictionary<int, string> dictionary = objects
.Select(x=> new KeyValuePair<int, string>(x.Id, x.Name))
.ToDictionary(x=>x.Key, x=>x.Value);
I think the $emit
function works better for what I think you're asking for. It keeps your component separated from the Vue instance so that it is reusable in many contexts.
// Child component
<template>
<div id="app">
<test @click="$emit('test-click')"></test>
</div>
</template>
Use it in HTML
// Parent component
<test @test-click="testFunction">
int()
only works for strings that look like integers; it will fail for strings that look like floats. Use float()
instead.
Here are some functions I created for working with fullscreen in the browser.
They provide both enter/exit fullscreen across most major browsers.
function isFullScreen()
{
return (document.fullScreenElement && document.fullScreenElement !== null)
|| document.mozFullScreen
|| document.webkitIsFullScreen;
}
function requestFullScreen(element)
{
if (element.requestFullscreen)
element.requestFullscreen();
else if (element.msRequestFullscreen)
element.msRequestFullscreen();
else if (element.mozRequestFullScreen)
element.mozRequestFullScreen();
else if (element.webkitRequestFullscreen)
element.webkitRequestFullscreen();
}
function exitFullScreen()
{
if (document.exitFullscreen)
document.exitFullscreen();
else if (document.msExitFullscreen)
document.msExitFullscreen();
else if (document.mozCancelFullScreen)
document.mozCancelFullScreen();
else if (document.webkitExitFullscreen)
document.webkitExitFullscreen();
}
function toggleFullScreen(element)
{
if (isFullScreen())
exitFullScreen();
else
requestFullScreen(element || document.documentElement);
}
public static void Serialize(object value, Stream s)
{
using (StreamWriter writer = new StreamWriter(s))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
public static T Deserialize<T>(Stream s)
{
using (StreamReader reader = new StreamReader(s))
using (JsonTextReader jsonReader = new JsonTextReader(reader))
{
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<T>(jsonReader);
}
}
For JPA fixed using EntityManager merge() instead of persist()
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
em.merge(fieldValue);
em.getTransaction().commit();
} catch (Exception e) {
//do smthng
} finally {
em.close();
}
You could add a method to String to make it more semantic:
String.metaClass.getNotBlank = { !delegate.allWhitespace }
which let's you do:
groovy:000> foo = ''
===>
groovy:000> foo.notBlank
===> false
groovy:000> foo = 'foo'
===> foo
groovy:000> foo.notBlank
===> true
In my case, I had to do the following while running with Junit5
@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class
Here abc.class was the class that was being tested
I just created my own version using CSS. As I need to disabled, then when document is ready use jQuery to make active. So that way a user cannot click on a button until after the document is ready. So i can substitute with AJAX instead. The way I came up with, was to add a class to the anchor tag itself and remove the class when document is ready. Could re-purpose this for your needs.
CSS:
a.disabled{
pointer-events: none;
cursor: default;
}
HTML:
<a class="btn btn-info disabled">Link Text</a>
JS:
$(function(){
$('a.disabled').on('click',function(event){
event.preventDefault();
}).removeClass('disabled');
});
ArrayList<String> newlyAddedTypes=new ArrayList<String>();
.....
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test1");
newlyAddedTypes.add("test2");
if(newlyAddedTypes.contain("test"){
//called here
}
else{
}
For cases of appending to end of existing string:
string = "Sec_"
string += "C_type"
print(string)
results in
Sec_C_type