To see a more complete list you can run:
show session status;
or
show global status;
See this link to better understand the usage.
If you want to know details about the database you can run:
status;
I'd recommend raising the connection timeout time before getting the output stream, like so:
urlConnection.setConnectTimeout(1000);
Where 1000 is in milliseconds (1000 milliseconds = 1 second).
For Windows: Filemon from SysInternals will show you what files are being accessed.
Remember to set your filters so you are not overwhelmed by the chatty file system traffic.
Added: Filemon does not work with newer Windows versions, so you might have to use Process Monitor.
When you test with device you want to add your PC ip address.
in pc run in cmd Ipconfig
in ubuntu run terminal ifconfig
Then use "http://your_pc_ip_address:8080/register"
insted of using "http://10.0.2.2:8080/register"
in my pc = 192.168.1.3
and also add internet permission to Manifest
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
you need check your all connection. Then try to close it one by one. it maybe caused by one of your connection.
I have similar case, the root cause come from my monitoring server. So when I closed it, it works.
you can use LocalRegistry such as:
Registry rgsty = LocateRegistry.createRegistry(1888);
rgsty.rebind("hello", hello);
The following piece of code allows us to get the status of the network on our Android device
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView mtv=findViewById(R.id.textv);
ConnectivityManager connectivityManager=
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(((Network)connectivityManager.getActiveNetwork())!=null)
mtv.setText("true");
else
mtv.setText("fasle");
}
}
}
Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?
No, it means that if no data arrives within 2000ms a SocketTimeoutException
will be thrown.
What does it mean timeout expire?
It means the 2000ms (in your case) elapses without any data arriving.
What is the option which must be enabled prior to blocking operation?
There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.
Infinite Timeout menas that the socket does't read anymore?
What a strange suggestion. It means that if no data ever arrives you will block in the read forever.
I'm using Mongoose to connect to mongodb. Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});
Store connection string in web.config
It is a good practice to store the connection string for your application in a config file rather than as a hard coded string in your code. The way to do this differs between .NET 2.0 and .NET 3.5 (and above). This article cover both. https://www.connectionstrings.com/store-connection-string-in-webconfig/
Two steps:
set up user with wildcard:
create user 'root'@'%' identified by 'some_characters';
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'
IDENTIFIED BY PASSWORD 'some_characters'
WITH GRANT OPTION
vim /etc/my.cnf
add the following:
bind-address=0.0.0.0
restart server, you should not have any problem connecting to it.
Connect to a non-routable IP address, such as 10.255.255.1.
when you have Failed to connect to remote VM Connection refused error, restart your eclipse
As Paul Turner answered Socket.Connected
cannot be used in this situation. You need to poll connection every time to see if connection is still active. This is code I used:
bool SocketConnected(Socket s)
{
bool part1 = s.Poll(1000, SelectMode.SelectRead);
bool part2 = (s.Available == 0);
if (part1 && part2)
return false;
else
return true;
}
It works like this:
s.Poll
returns true if
s.Available
returns number of bytes available for readingHad the same issue, but executing the queries alone will not help. To fix this I did the following,
Today I fallen this kind of problem in live server and i solved the problem changing this line
$db['default']['db_debug'] = TRUE;
to
$db['default']['db_debug'] = FALSE;
Please check to see if you are connected to the network if this is a domain member PC. Also, make sure you are not on a dual home PC as your routes may be incorrect due to network metrics. I had this issue when I could not connect to the domain the SQL windows authentication switched to the local PC account but registered it as a SQL authentication. Once I disabled my wireless adapter and rebooted, the Windows integration switched back to the domain account and authenticated fine. I had already set up Mixed mode as you had already done as well so the previous posts do not apply.
I was using my OpenWRT enhanced device as a repeater (which adds virtual ethernet and wireless lan capabilities) and found that the /sys/class/net/eth0 carrier and opstate values were unreliable. I played around with /sys/class/net/eth0.1 and /sys/class/net/eth0.2 as well with (at least to my finding) no reliable way to detect that something was physically plugged in and talking on any of the ethernet ports. I figured out a bit crude but seemingly reliable way to detect if anything had been plugged in since the last reboot/poweron state at least (which worked exactly as I needed it to in my case).
ifconfig eth0 | grep -o 'RX packets:[0-9]*' | grep -o '[0-9]*'
You'll get a 0 if nothing has been plugged in and something > 0 if anything has been plugged in (even if it was plugged in and since removed) since the last power on or reboot cycle.
Hope this helps somebody out at least!
Use this to get an accurate count for each connection pool (assuming each user/host process uses the same connection string)
SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName, hostname, hostprocess
FROM
sys.sysprocesses with (nolock)
WHERE
dbid > 0
GROUP BY
dbid, loginame, hostname, hostprocess
Create the user with a password :
http://www.postgresql.org/docs/current/static/sql-createuser.html
CREATE USER name [ [ WITH ] option [ ... ] ]
where option can be:
SUPERUSER | NOSUPERUSER
| CREATEDB | NOCREATEDB
| CREATEROLE | NOCREATEROLE
| CREATEUSER | NOCREATEUSER
| INHERIT | NOINHERIT
| LOGIN | NOLOGIN
| REPLICATION | NOREPLICATION
| CONNECTION LIMIT connlimit
| [ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password'
| VALID UNTIL 'timestamp'
| IN ROLE role_name [, ...]
| IN GROUP role_name [, ...]
| ROLE role_name [, ...]
| ADMIN role_name [, ...]
| USER role_name [, ...]
| SYSID uid
Then grant the user rights on a specific database :
http://www.postgresql.org/docs/current/static/sql-grant.html
Example :
grant all privileges on database db_name to someuser;
Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.
As above mentioned, there is no special command to do it. However, if all those connection are inactive, using 'flush tables;' is able to release all those connection which are not active.
First of all find the python process ID using this command
ps -fA | grep python
You will get a pid number by naming of your python process on second column
Then kill the process using this command
kill -9 pid
I had the same problem with a freshly installed copy of Chrome.
If nothing works, and your Use a proxy server your LAN
setting is unchecked, check it and then uncheck it . Believe it or not it might work. I don't know if I should consider it a bug or not.
HTTP HEAD requests must be treated slightly differently because response.getEntity() is null. Instead, you must capture the HttpContext passed into HttpClient.execute() and retrieve the connection parameter to close it (in HttpComponents 4.1.X anyway).
HttpRequest httpRqst = new HttpHead( uri );
HttpContext httpContext = httpFactory.createContext();
HttpResponse httpResp = httpClient.execute( httpRqst, httpContext );
...
// Close when finished
HttpEntity entity = httpResp.getEntity();
if( null != entity )
// Handles standard 'GET' case
EntityUtils.consume( entity );
else {
ConnectionReleaseTrigger conn =
(ConnectionReleaseTrigger) httpContext.getAttribute( ExecutionContext.HTTP_CONNECTION );
// Handles 'HEAD' where entity is not returned
if( null != conn )
conn.releaseConnection();
}
HttpComponents 4.2.X added a releaseConnection() to HttpRequestBase to make this easier.
One difference we can note in Windows is:
If you use Runtime.getRuntime().exec("rmiregistry 1024");
you can see rmiregistry.exe process will run in your Task Manager
whereas if you use Registry registry = LocateRegistry.createRegistry(1024);
you can not see the process running in Task Manager,
I think Java handles it in a different way.
and this is my server.policy file
Before running the the application, make sure that you killed all your existing javaw.exe and rmiregistry.exe corresponds to your rmi programs which are already running.
The following code works for me by using Registry.LocateRegistry()
or
Runtime.getRuntime.exec("");
// Standard extensions get all permissions by default
grant {
permission java.security.AllPermission;
};
VM argument
-Djava.rmi.server.codebase=file:\C:\Users\Durai\workspace\RMI2\src\
Code:
package server;
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class HelloServer
{
public static void main (String[] argv)
{
try {
if(System.getSecurityManager()==null){
System.setProperty("java.security.policy","C:\\Users\\Durai\\workspace\\RMI\\src\\server\\server.policy");
System.setSecurityManager(new RMISecurityManager());
}
Runtime.getRuntime().exec("rmiregistry 1024");
// Registry registry = LocateRegistry.createRegistry(1024);
// registry.rebind ("Hello", new Hello ("Hello,From Roseindia.net pvt ltd!"));
//Process process = Runtime.getRuntime().exec("C:\\Users\\Durai\\workspace\\RMI\\src\\server\\rmi_registry_start.bat");
Naming.rebind ("//localhost:1024/Hello",new Hello ("Hello,From Roseindia.net pvt ltd!"));
System.out.println ("Server is connected and ready for operation.");
}
catch (Exception e) {
System.out.println ("Server not connected: " + e);
e.printStackTrace();
}
}
}
As you are creating a database from scratch, you could use:
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/?user=root&password=rootpassword");
PreparedStatement ps = connection.prepareStatement("CREATE DATABASE databasename");
int result = ps.executeUpdate();
Here is an identical scenario.
I faced this issue after using Vast cleanup. Basically mysql instance starts on PC startup and it is active in background all the time even when not in use.
Mistakenly I've stopped it
Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)
Solution which worked for me:
type in mysql command line client. As soon as you open you will be prompted with password
-> mysql -u root -p -h 127.0.0.1 -P 3306
and finally it works even when you switch back to workbench.
Complementing the response of @Adrià Cidre
you can do:
status=$(ssh -o BatchMode=yes -o ConnectTimeout=5 user@host echo ok 2>&1)
if [[ $status == ok ]] ; then
echo auth ok, do something
elif [[ $status == "Permission denied"* ]] ; then
echo no_auth
else
echo other_error
fi
In my case the site that I'm connecting to has upgraded to TLS 1.2. As a result I had to install .net 4.5.2 on my web server in order to support it.
JointJS/Rappid supports this use case with its Kitchensink example which supports dragging and dropping of elements, and repositioning of connections. It has many examples.
This answer is based off of Vainbhav Jain's answer.
Multiple clients can connect to the same port (say 80) on the server because on the server side, after creating a socket and binding (setting local IP and port) listen is called on the socket which tells the OS to accept incoming connections.
When a client tries to connect to server on port 80, the accept call is invoked on the server socket. This creates a new socket for the client trying to connect and similarly new sockets will be created for subsequent clients using same port 80.
Words in italics are system calls.
Ref
It is properly written over here
If you download the .msi file then install it and if you download the zip file then extract it.
Set up the MongoDB environment.
MongoDB requires a data directory to store all data. MongoDB’s default data directory path is \data\db. Create this folder using the following commands from a Command Prompt:
md \data\db
You can specify an alternate path for data files using the --dbpath option to mongod.exe, for example:
C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data
If your path includes spaces, enclose the entire path in double quotes, for example:
C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"
You may also specify the dbpath in a configuration file.
Start MongoDB.
To start MongoDB, run mongod.exe. For example, from the Command Prompt:
C:\mongodb\bin\mongod.exe
Connect to MongoDB.
To connect to MongoDB through the mongo.exe shell, open another Command Prompt.
C:\mongodb\bin\mongo.exe
Just for the record, I tried translating Dirk's answer into code :-P
temp <- tempfile()
download.file("http://www.newcl.org/data/zipfiles/a1.zip",temp)
con <- unz(temp, "a1.dat")
data <- matrix(scan(con),ncol=4,byrow=TRUE)
unlink(temp)
This worked for me:
string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
+ ";Extended Properties=\"Excel 12.0 Xml;HDR=YES\"";
I'm querying an XLSX file so don't worry about any of the other stuff in the connection string but the Data Source.
So my answer is:
HttpContext.Current.Server.MapPath("\\myPath\\myFile.db")
While many are taking the approach to stop/disable IIS, it may be helpful to know that you can simply modify the XAMPP port, which has been answered here. This is the route I had to take as I need both running.
You can also check the .IsConnected property of the socket if you were to poll.
- What is the difference between connection and read timeout for sockets?
The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read
call, a read timeout error will be raised.
- What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?
It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt()
call may also do the trick ... not sure.)
- What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?
It means that a call to read
on the socket stream may block for ever. Once again there is no infinite loop, but the read
can be unblocked by a Thread.interrupt()
call, closing the socket, and (of course) the other end sending data or closing the connection.
1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.
The error 2002 means that MySQL can't connect to local database server through the socket file (e.g. /tmp/mysql.sock
).
To find out where is your socket file, run:
mysql_config --socket
then double check that your application uses the right Unix socket file or connect through the TCP/IP port instead.
Then double check if your PHP has the right MySQL socket set-up:
php -i | grep mysql.default_socket
and make sure that file exists.
Test the socket:
mysql --socket=/var/mysql/mysql.sock
If the Unix socket is wrong or does not exist, you may symlink it, for example:
ln -vs /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock
or correct your configuration file (e.g. php.ini
).
To test the PDO connection directly from PHP, you may run:
php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');"
Check also the configuration between Apache and CLI (command-line interface), as the configuration can be differ.
It might be that the server is running, but you are trying to connect using a TCP/IP port, named pipe, or Unix socket file different from the one on which the server is listening. To correct that you need to invoke a client program (e.g. specifying
--port
option) to indicate the proper port number, or the proper named pipe or Unix socket file (e.g.--socket
option).
See: Troubleshooting Problems Connecting to MySQL
Other utils/commands which can help to track the problem:
mysql --socket=$(php -r 'echo ini_get("mysql.default_socket");')
netstat -ln | grep mysql
php -r "phpinfo();" | grep mysql
php -i | grep mysql
xdebug.show_exception_trace=1
in your xdebug.ini
sudo dtruss -fn mysqld
, on Linux debug with strace
stat $(mysql_config --socket)
and if you've enough free space (df -h
).net.core.somaxconn
.Without ping
#!/bin/bash
wget -q --spider http://google.com
if [ $? -eq 0 ]; then
echo "Online"
else
echo "Offline"
fi
-q : Silence mode
--spider : don't get, just check page availability
$? : shell return code
0 : shell "All OK" code
Without wget
#!/bin/bash
echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Online"
else
echo "Offline"
fi
The port is available here: java.rmi.registry.Registry.REGISTRY_PORT
(1099)
I resolved this issue for all devices(including Nexus 5, Samsung Galaxy Nexus 6 edge+, Samsung S10, Samsung Note II etc.). I think this will help you to handle device dependant issues.
Here I am adding two types of codes,
Java Code(for Native Android):
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.ViewConfiguration;
import android.view.WindowManager;
public class DeviceSpec {
private int resourceID = -1;
private Display display = null;
private DisplayMetrics displayMetrics = null;
private DisplayMetrics realDisplayMetrics = null;
private Resources resources = null;
private WindowManager windowManager = null;
public double GetNavigationBarHeight(Context context) {
try {
windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
display = windowManager.getDefaultDisplay();
displayMetrics = new DisplayMetrics();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
realDisplayMetrics = new DisplayMetrics();
display.getMetrics(displayMetrics);
display.getRealMetrics(realDisplayMetrics);
if(displayMetrics.heightPixels != realDisplayMetrics.heightPixels) {
resources = context.getResources();
return GetNavigationBarSize(context);
}
}
else {
resources = context.getResources();
resourceID = resources.getIdentifier("config_showNavigationBar", "bool", "android");
if (resourceID > 0 && resources.getBoolean(resourceID))
return GetNavigationBarSize(context);
}
}
catch (Exception e){
e.printStackTrace();
}
return 0;
}
private double GetNavigationBarSize(Context context) {
resourceID = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceID > 0 && ViewConfiguration.get(context).hasPermanentMenuKey())
return (resources.getDimensionPixelSize(resourceID) / displayMetrics.density);
return 0;
}
}
And C# code(for Xamarin Forms/Android)
int resourceId = -1;
IWindowManager windowManager = null;
Display defaultDisplay = null;
DisplayMetrics displayMatrics = null;
DisplayMetrics realMatrics = null;
Resources resources = null;
public double NavigationBarHeight
{
get
{
try
{
windowManager = Forms.Context.GetSystemService(Context.WindowService).JavaCast<IWindowManager>();
defaultDisplay = windowManager.DefaultDisplay;
displayMatrics = new DisplayMetrics();
if (Build.VERSION.SdkInt >= BuildVersionCodes.JellyBeanMr2)
{
realMatrics = new DisplayMetrics();
defaultDisplay.GetMetrics(displayMatrics);
defaultDisplay.GetRealMetrics(realMatrics);
if (displayMatrics.HeightPixels != realMatrics.HeightPixels)
{
resources = Forms.Context.Resources;
return GetHeightOfNivigationBar();
}
}
else {
resources = Forms.Context.Resources;
resourceId = resources.GetIdentifier("config_showNavigationBar", "bool", "android");
if (resourceId > 0 && resources.GetBoolean(resourceId))
return GetHeightOfNivigationBar();
}
}
catch (Exception e) { }
return 0;
}
}
private double GetHeightOfNivigationBar()
{
resourceId = resources.GetIdentifier("navigation_bar_height", "dimen", "android");
if (!ViewConfiguration.Get(Forms.Context).HasPermanentMenuKey && resourceId > 0)
{
return resources.GetDimensionPixelSize(resourceId) / displayMatrics.Density;
}
return 0;
}
The filter option filters only the first level subkey below ansible_facts
Fibonacci sequence generator using the yield keyword.
function* fibbonaci(){
var a = -1, b = 1, c;
while(1){
c = a + b;
a = b;
b = c;
yield c;
}
}
var fibonacciGenerator = fibbonaci();
fibonacciGenerator.next().value; // 0
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 2
The simplest approach would be to use any of these class utilities that Bootstrap provides:
<div class="position-fixed">...</div>
<div class="position-sticky">...</div>
<div class="fixed-top">...</div>
<div class="fixed-bottom">...</div>
<div class="sticky-top">...</div>
I solved this issue to update .htaccess
file inside your workspace (like C:\xampp\htdocs\Nayan\.htaccess
in my case).
Just update or add this
php_value max_execution_time 300
line before# END WordPress
. Then save the file and try to install again.
If the error occurs again, you can maximize the value from 300
to 600
.
you can remove this alert by doing following:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity(' ')"
/>
just set the custom message to one blank space
Please note only 2 basic data structure can be accessed via index.
O(1)
time complexity to achieve get(int index)
operation.O(n)
time complexity to achieve get(int index)
operation.In Java, ArrayList
is implemented using Array data structure.
While Set data structure usually can be implemented via HashTable/HashMap or BalancedTree data structure, for fast detecting whether an element exists and add non-existing element, usually a well implemented Set can achieve O(1)
time complexity contains
operation. In Java, HashSet
is the most common used implementation of Set, it is implemented by calling HashMap
API, and HashMap
is implemented using separate chaining with linked lists (a combination of Array and LinkedList).
Since Set can be implemented via different data structure, there is no get(int index)
method for it.
You can also just enter the website and:
The same limitation applies here: the folder must contain at least one file inside it.
This is what Sun-Oracle documentation says:
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Typically, iterators are used to access elements of a container in linear fashion; however, with "random access iterators", it is possible to access any element in the same fashion as operator[]
.
To access arbitrary elements in a vector vec
, you can use the following:
vec.begin() // 1st
vec.begin()+1 // 2nd
// ...
vec.begin()+(i-1) // ith
// ...
vec.begin()+(vec.size()-1) // last
The following is an example of a typical access pattern (earlier versions of C++):
int sum = 0;
using Iter = std::vector<int>::const_iterator;
for (Iter it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
The advantage of using iterator is that you can apply the same pattern with other containers:
sum = 0;
for (Iter it = lst.begin(); it!=lst.end(); ++it) {
sum += *it;
}
For this reason, it is really easy to create template code that will work the same regardless of the container type. Another advantage of iterators is that it doesn't assume the data is resident in memory; for example, one could create a forward iterator that can read data from an input stream, or that simply generates data on the fly (e.g. a range or random number generator).
Another option using std::for_each
and lambdas:
sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int i) { sum += i; });
Since C++11 you can use auto
to avoid specifying a very long, complicated type name of the iterator as seen before (or even more complex):
sum = 0;
for (auto it = vec.begin(); it!=vec.end(); ++it) {
sum += *it;
}
And, in addition, there is a simpler for-each variant:
sum = 0;
for (auto value : vec) {
sum += value;
}
And finally there is also std::accumulate
where you have to be careful whether you are adding integer or floating point numbers.
The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation
<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />
I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:
<p>
Hello {
<span>World</span>
}!
</p>
or
<p>
Hello {}
<span>World</span>
{} again!
</p>
Each of these produces clean html without additional
or other extraneous markup. It creates fewer text nodes than using {' '}
, and allows using of html entities where {' hello & goodbye '}
does not.
Thank you WiredPrairie!
Just to expand on your answer a bit, here is a complete example of defining a constants class.
// CYConstants.ts
class CYConstants {
public static get NOT_FOUND(): number { return -1; }
public static get EMPTY_STRING(): string { return ""; }
}
export = CYConstants;
To use
// main.ts
import CYConstants = require("./CYConstants");
console.log(CYConstants.NOT_FOUND); // Prints -1
console.log(CYConstants.EMPTY_STRING); // Prints "" (Nothing!)
Why not just have a Year
property, which is perfectly fine?
Interfaces don't contain fields because fields represent a specific implementation of data representation, and exposing them would break encapsulation. Thus having an interface with a field would effectively be coding to an implementation instead of an interface, which is a curious paradox for an interface to have!
For instance, part of your Year
specification might require that it be invalid for ICar
implementers to allow assignment to a Year
which is later than the current year + 1 or before 1900. There's no way to say that if you had exposed Year
fields -- far better to use properties instead to do the work here.
Boost Test Library is a very good choice especially if you're already using Boost.
// TODO: Include your class to test here.
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(MyTestCase)
{
// To simplify this example test, let's suppose we'll test 'float'.
// Some test are stupid, but all should pass.
float x = 9.5f;
BOOST_CHECK(x != 0.0f);
BOOST_CHECK_EQUAL((int)x, 9);
BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%
}
It supports:
PS: I wrote an article about it that may help you getting started: C++ Unit Testing Framework: A Boost Test Tutorial
function updateURL(url_params) {
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + url_params;
window.history.replaceState({path:newurl},'',newurl);
}
}
function setActiveTab(tab) {
$('.nav-tabs li').removeClass('active');
$('.tab-content .tab-pane').removeClass('active');
$('a[href="#tab-' + tab + '"]').closest('li').addClass('active');
$('#tab-' + tab).addClass('active');
}
// Set active tab
$url_params = new URLSearchParams(window.location.search);
// Get active tab and remember it
$('a[data-toggle="tab"]')
.on('click', function() {
$href = $(this).attr('href')
$active_tab = $href.replace('#tab-', '');
$url_params.set('tab', $active_tab);
updateURL($url_params.toString());
});
if ($url_params.has('tab')) {
$tab = $url_params.get('tab');
$tab = '#tab-' + $tab;
$myTab = JSON.stringify($tab);
$thisTab = $('.nav-tabs a[href=' + $myTab +']');
$('.nav-tabs a[href=' + $myTab +']').tab('show');
}
Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.
You can use numpy.recfromcsv(filename)
: the types of each column will be automatically determined (as if you use np.genfromtxt()
with dtype=None
), and by default delimiter=","
. It's basically a shortcut for np.genfromtxt(filename, delimiter=",", dtype=None)
that Pierre GM pointed at in his answer.
If it's really important that you have the correct date and time; it's best to have a service on your server (which you of course have running in UTC) that returns the time. You can then create a new Date on the client and compare the values and if necessary adjust all dates with the offset from the server time.
Why do this? I've had bug reports that was hard to reproduce because I could not find the error messages in the server log, until I noticed that the bug report was mailed two days after I'd received it. You can probably trust the browser to correctly handle time-zone conversion when being sent a UTC timestamp, but you obviously cannot trust the users to have their system clock correctly set. (If the users have their timezone incorrectly set too, there is not really any solution; other than printing the current server time in "local" time)
getFileName() method of java.nio.file.Path used to return the name of the file or directory pointed by this path object.
Path getFileName()
For reference:
https://www.geeksforgeeks.org/path-getfilename-method-in-java-with-examples/
Use a temp table to insert the range of values, then select the min/max of the temp table from within a stored procedure or UDF. This is a basic construct, so feel free to revise as needed.
For example:
CREATE PROCEDURE GetMinSpeed() AS
BEGIN
CREATE TABLE #speed (Driver NVARCHAR(10), SPEED INT);
'
' Insert any number of data you need to sort and pull from
'
INSERT INTO #speed (N'Petty', 165)
INSERT INTO #speed (N'Earnhardt', 172)
INSERT INTO #speed (N'Patrick', 174)
SELECT MIN(SPEED) FROM #speed
DROP TABLE #speed
END
Create an XML file named border.xml in the drawable folder and put the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
Then add a background to your linear layout like this:
android:background="@drawable/border"
EDIT :
This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:
ALSO
tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :
Finally its works perfectly with all APIs
EDIT 2 :
It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="0dp" android:right="0dp" android:top="0dp"
android:bottom="-10dp">
<shape android:shape="rectangle">
<stroke android:width="10dp" android:color="#B22222" />
</shape>
</item>
</layer-list>
hope this help .
So, let me give you sample code:
<div class="news">
Blah, blah, blah. I'm hidden.
</div>
<a class="trigger">Hide/Show News</a>
The link will be the trigger to show the div when clicked. So your Javascript will be:
$('.trigger').click(function() {
$('.news').toggle();
});
You're almost always better off letting jQuery handle the styling for hiding and showing elements.
Edit: I see people above are recommending using .show
and .hide
for this. .toggle
allows you to do both with just one effect. So that's cool.
EOF is a special out-of-band signal which means the end of input. It's not a character (though in the old DOS days, 0x1B acted like EOF), but rather a signal from the OS that the input has ended.
On Windows, you can "input" an EOF by pressing Ctrl+Z
at the command prompt. This signals the terminal to close the input stream, which presents an EOF to the running program. Note that on other OSes or terminal emulators, EOF is usually signalled using Ctrl+D
.
As for your issue with Sublime Text 2, it seems that stdin
is not connected to the terminal when running a program within Sublime, and so consequently programs start off connected to an empty file (probably nul
or /dev/null
). See also Python 3.1 and Sublime Text 2 error.
Not for the questioner, but for all others, which are interested: See: How to define Typescript Map of key value pair. where key is a number and value is an array of objects
The solution is therefore:
let yourVar: Map<YourKeyType, YourValueType>;
// now you can use it:
yourVar = new Map<YourKeyType, YourValueType>();
yourVar[YourKeyType] = <YourValueType> yourValue;
Cheers!
There's no need to manually set the colors. Instead, specify a grayscale colormap...
import numpy as np
import matplotlib.pyplot as plt
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
# Plot...
plt.scatter(x, y, c=y, s=500)
plt.gray()
plt.show()
Or, if you'd prefer a wider range of colormaps, you can also specify the cmap
kwarg to scatter
. To use the reversed version of any of these, just specify the "_r
" version of any of them. E.g. gray_r
instead of gray
. There are several different grayscale colormaps pre-made (e.g. gray
, gist_yarg
, binary
, etc).
import matplotlib.pyplot as plt
import numpy as np
# Generate data...
x = np.random.random(10)
y = np.random.random(10)
plt.scatter(x, y, c=y, s=500, cmap='gray')
plt.show()
Just Small change to what Gary W mentioned, adding 'SELECT':
IF (SELECT CURSOR_STATUS('global','myCursor')) >= -1
BEGIN
DEALLOCATE myCursor
END
http://social.msdn.microsoft.com/Forums/en/sqlgetstarted/thread/eb268010-75fd-4c04-9fe8-0bc33ccf9357
I'm using this command:
export BEFORE_DATETIME=$(date --date='10 weeks ago' +"%Y-%m-%dT%H:%M:%S.%NZ")
docker images -q | while read IMAGE_ID; do
export IMAGE_CTIME=$(docker inspect --format='{{.Created}}' --type=image ${IMAGE_ID})
if [[ "${BEFORE_DATETIME}" > "${IMAGE_CTIME}" ]]; then
echo "Removing ${IMAGE_ID}, ${BEFORE_DATETIME} is earlier then ${IMAGE_CTIME}"
docker rmi -f ${IMAGE_ID};
fi;
done
This will remove all images whose creation time is greater than 10 weeks ago.
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
And another expansion:
# create dummy matrix
set.seed(10)
m <- matrix(round(runif(25, 1, 5)), 5)
d <- as.data.frame(m)
If you want to assign new column names you can do following on data.frame
:
# an identical effect can be achieved with colnames()
names(d) <- LETTERS[1:5]
> d
A B C D E
1 3 2 4 3 4
2 2 2 3 1 3
3 3 2 1 2 4
4 4 3 3 3 2
5 1 3 2 4 3
If you, however run previous command on matrix
, you'll mess things up:
names(m) <- LETTERS[1:5]
> m
[,1] [,2] [,3] [,4] [,5]
[1,] 3 2 4 3 4
[2,] 2 2 3 1 3
[3,] 3 2 1 2 4
[4,] 4 3 3 3 2
[5,] 1 3 2 4 3
attr(,"names")
[1] "A" "B" "C" "D" "E" NA NA NA NA NA NA NA NA NA NA NA NA NA NA
[20] NA NA NA NA NA NA
Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames()
.
So there...
The SQL Server Maximums are disclosed http://msdn.microsoft.com/en-us/library/ms143432.aspx (this is the 2008 version)
A SQL Query can be a varchar(max) but is shown as limited to 65,536 * Network Packet size, but even then what is most likely to trip you up is the 2100 parameters per query. If SQL chooses to parameterize the literal values in the in clause, I would think you would hit that limit first, but I havn't tested it.
Edit : Test it, even under forced parameteriztion it survived - I knocked up a quick test and had it executing with 30k items within the In clause. (SQL Server 2005)
At 100k items, it took some time then dropped with:
Msg 8623, Level 16, State 1, Line 1 The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for extremely complex queries or queries that reference a very large number of tables or partitions. Please simplify the query. If you believe you have received this message in error, contact Customer Support Services for more information.
So 30k is possible, but just because you can do it - does not mean you should :)
Edit : Continued due to additional question.
50k worked, but 60k dropped out, so somewhere in there on my test rig btw.
In terms of how to do that join of the values without using a large in clause, personally I would create a temp table, insert the values into that temp table, index it and then use it in a join, giving it the best opportunities to optimse the joins. (Generating the index on the temp table will create stats for it, which will help the optimiser as a general rule, although 1000 GUIDs will not exactly find stats too useful.)
If your url looks something like this:
somesite.com/something/123
Where '123' is a parameter named 'id' (url like /something/:id), try with:
this.$route.params.id
Also, the comment tag
<comment></comment>
is only supported in IE 8 and below, so if that's exactly what you're trying to target, you could wrap them in comment tag. They're the same as
<!--[if lte IE 8]><![endif]-->
In which lte means "less than or equal to".
See: Conditional Comments.
In Windows, open cmd and find the location of PYTHON_HOME using where python
. Now add this location to your environment variable PATH using:
set PATH=%PATH%;<PYTHON_HOME>\Scripts
Or refer to this.
In Linux, open a terminal and find the location of PYTHON_HOME using which python
. Now add the PYTHON_HOME/Scripts
to the PATH variable using:
PATH=$PATH:<PYTHON_HOME>\Scripts
export PATH
I came here looking for making an input that's actually multiple lines. Turns out I didn't want an input, I wanted a textarea. You can set height or line-height as other answers specify, but it'll still just be one line of a textbox. If you want actual multiple lines, use a textarea instead. The following is an example of a 3-row textarea with a width of 500px (should be a good part of the page, not necessary to set this and will have to change it based on your requirements).
<textarea name="roleExplanation" style="width: 500px" rows="3">This role is for facility managers and holds the highest permissions in the application.</textarea>
Via css. Put this inside the <head>
tag.
<style type="text/css" media="screen">
table{
border-collapse:collapse;
border:1px solid #FF0000;
}
table td{
border:1px solid #FF0000;
}
</style>
Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
$.fn.delay = function(time, callback){
// Empty function:
jQuery.fx.step.delay = function(){};
// Return meaningless animation, (will be added to queue)
return this.animate({delay:1}, time, callback);
}
From http://james.padolsey.com/javascript/jquery-delay-plugin/
(Allows chaining of methods)
Update 2010-2011:
zumalifeguard's solution (upvoted) is simpler than the original one, as it doesn't need anymore a shell wrapper script.
As I explain in "How can I set up an editor to work with Git on Windows?", I prefer a wrapper, as it is easier to try and switch editors, or change the path of one editor, without having to register said change with a git config
again.
But that is just me.
Additional information: the following solution works with Cygwin, while the zuamlifeguard's solution does not.
Original answer.
The following:
C:\prog\git>git config --global core.editor C:/prog/git/npp.sh
C:/prog/git/npp.sh:
#!/bin/sh
"c:/Program Files/Notepad++/notepad++.exe" -multiInst "$*"
does work. Those commands are interpreted as shell script, hence the idea to wrap any windows set of commands in a sh
script.
(As Franky comments: "Remember to save your .sh
file with Unix style line endings or receive mysterious error messages!")
More details on the SO question How can I set up an editor to work with Git on Windows?
Note the '-multiInst
' option, for ensuring a new instance of notepad++ for each call from Git.
Note also that, if you are using Git on Cygwin (and want to use Notepad++ from Cygwin), then scphantm explains in "using Notepad++ for Git inside Cygwin" that you must be aware that:
git
is passing it acygwin
path andnpp
doesn't know what to do with it
So the script in that case would be:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar -nosession -noPlugin "$(cygpath -w "$*")"
Multiple lines for readability:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -notabbar \
-nosession -noPlugin "$(cygpath -w "$*")"
With "$(cygpath -w "$*")"
being the important part here.
Val commented (and then deleted) that you should not use -notabbar
option:
It makes no good to disable the tab during rebase, but makes a lot of harm to general Notepad usability since
-notab
becomes the default setting and you mustSettings>Preferences>General>TabBar> Hide>uncheck
every time you start notepad after rebase. This is hell. You recommended the hell.
So use rather:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession -noPlugin "$(cygpath -w "$*")"
That is:
#!/bin/sh
"C:/Program Files (x86)/Notepad++/notepad++.exe" -multiInst -nosession \
-noPlugin "$(cygpath -w "$*")"
If you want to place the script 'npp.sh
' in a path with spaces (as in
'c:\program files\...
',), you have three options:
Either try to quote the path (single or double quotes), as in:
git config --global core.editor 'C:/program files/git/npp.sh'
or try the shortname notation (not fool-proofed):
git config --global core.editor C:/progra~1/git/npp.sh
or (my favorite) place 'npp.sh
' in a directory part of your %PATH%
environment variable. You would not have then to specify any path for the script.
git config --global core.editor npp.sh
Steiny reports in the comments having to do:
git config --global core.editor '"C:/Program Files (x86)/Git/scripts/npp.sh"'
SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());
Example.
SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE());
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes.
(This answer only applies to C# not C++, sorry I misread the original question)
I've got through DLL hell like this before. My final solution was to store the unmanaged DLLs in the managed DLL as binary resources, and extract them to a temporary folder when the program launches and delete them when it gets disposed.
This should be part of the .NET or pinvoke infrastructure, since it is so useful.... It makes your managed DLL easy to manage, both using Xcopy or as a Project reference in a bigger Visual Studio solution. Once you do this, you don't have to worry about post-build events.
UPDATE:
I posted code here in another answer https://stackoverflow.com/a/11038376/364818
I'll try to provide a comprehensive answer here. Much of the points appear in other answers, but I found each answer incomplete, and some incorrect.
First and foremost, objectForKey:
is an NSDictionary
method, while valueForKey:
is a KVC protocol method required of any KVC complaint class - including NSDictionary.
Furthermore, as @dreamlax wrote, documentation hints that NSDictionary
implements its valueForKey:
method USING its objectForKey:
implementation. In other words - [NSDictionary valueForKey:]
calls on [NSDictionary objectForKey:]
.
This implies, that valueForKey:
can never be faster than objectForKey:
(on the same input key) although thorough testing I've done imply about 5% to 15% difference, over billions of random access to a huge NSDictionary. In normal situations - the difference is negligible.
Next: KVC protocol only works with NSString *
keys, hence valueForKey:
will only accept an NSString *
(or subclass) as key, whilst NSDictionary
can work with other kinds of objects as keys - so that the "lower level" objectForKey:
accepts any copy-able (NSCopying protocol compliant) object as key.
Last, NSDictionary's
implementation of valueForKey:
deviates from the standard behavior defined in KVC's documentation, and will NOT emit a NSUnknownKeyException
for a key it can't find - unless this is a "special" key - one that begins with '@' - which usually means an "aggregation" function key (e.g. @"@sum, @"@avg"
). Instead, it will simply return a nil when a key is not found in the NSDictionary - behaving the same as objectForKey:
Following is some test code to demonstrate and prove my notes.
- (void) dictionaryAccess {
NSLog(@"Value for Z:%@", [@{@"X":@(10), @"Y":@(20)} valueForKey:@"Z"]); // prints "Value for Z:(null)"
uint32_t testItemsCount = 1000000;
// create huge dictionary of numbers
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
// make new random key value pair:
NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
NSNumber *value = @(arc4random_uniform(testItemsCount));
[d setObject:value forKey:key];
}
// create huge set of random keys for testing.
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
NSString *key = [NSString stringWithFormat:@"K_%u",arc4random_uniform(testItemsCount)];
[keys addObject:key];
}
NSDictionary *dict = [d copy];
NSTimeInterval vtotal = 0.0, ototal = 0.0;
NSDate *start;
NSTimeInterval elapsed;
for (int i = 0; i<10; i++) {
start = [NSDate date];
for (NSString *key in keys) {
id value = [dict valueForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
vtotal+=elapsed;
NSLog (@"reading %lu values off dictionary via valueForKey took: %10.4f seconds", keys.count, elapsed);
start = [NSDate date];
for (NSString *key in keys) {
id obj = [dict objectForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
ototal+=elapsed;
NSLog (@"reading %lu objects off dictionary via objectForKey took: %10.4f seconds", keys.count, elapsed);
}
NSString *slower = (vtotal > ototal) ? @"valueForKey" : @"objectForKey";
NSString *faster = (vtotal > ototal) ? @"objectForKey" : @"valueForKey";
NSLog (@"%@ takes %3.1f percent longer then %@", slower, 100.0 * ABS(vtotal-ototal) / MAX(ototal,vtotal), faster);
}
It seems to me that you might be better off with a list rather than using orca1
, orca2
, etc, ... then it would be orca[1]
, orca[2]
, ...
Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.
orca <- list()
orca[1] <- "Hi"
orca[2] <- 59
Otherwise, assign
is just what you want.
You can use componentWillReceiveProps.
constructor(props) {
super(props);
this.state = {
productdatail: ''
};
}
componentWillReceiveProps(nextProps){
this.setState({ productdatail: nextProps.productdetailProps })
}
tl;dr: You don't have to remove the slashes, you have nested JSON, and hence have to decode the JSON twice: DEMO (note I used double slashes in the example, because the JSON is inside a JS string literal).
I assume that your actual JSON looks like
{"data":"{\n \"taskNames\" : [\n \"01 Jan\",\n \"02 Jan\",\n \"03 Jan\",\n \"04 Jan\",\n \"05 Jan\",\n \"06 Jan\",\n \"07 Jan\",\n \"08 Jan\",\n \"09 Jan\",\n \"10 Jan\",\n \"11 Jan\",\n \"12 Jan\",\n \"13 Jan\",\n \"14 Jan\",\n \"15 Jan\",\n \"16 Jan\",\n \"17 Jan\",\n \"18 Jan\",\n \"19 Jan\",\n \"20 Jan\",\n \"21 Jan\",\n \"22 Jan\",\n \"23 Jan\",\n \"24 Jan\",\n \"25 Jan\",\n \"26 Jan\",\n \"27 Jan\"]}"}
I.e. you have a top level object with one key, data
. The value of that key is a string containing JSON itself. This is usually because the server side code didn't properly create the JSON. That's why you see the \"
inside the string. This lets the parser know that "
is to be treated literally and doesn't terminate the string.
So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.
var data = JSON.parse(JSON.parse(json).data));
I had a similar issue but in my case, the solution was to dispatch the action as an async task in the main queue
DispatchQueue.main.async {
let vc = self.storyboard?.instantiateViewController(withIdentifier: myVCID) as! myVCName
self.present(vc, animated: true, completion: nil)
}
I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.
date
and datetime
objects (and time
as well) support a mini-language to specify output, and there are two ways to access it:
dt.strftime('format here')
'{:format here}'.format(dt)
f'{dt:format here}'
So your example could look like:
dt.strftime('The date is %b %d, %Y')
'The date is {:%b %d, %Y}'.format(dt)
f'The date is {dt:%b %d, %Y}'
In all three cases the output is:
The date is Feb 23, 2012
For completeness' sake: you can also directly access the attributes of the object, but then you only get the numbers:
'The date is %s/%s/%s' % (dt.month, dt.day, dt.year)
# The date is 02/23/2012
The time taken to learn the mini-language is worth it.
For reference, here are the codes used in the mini-language:
%a
Weekday as locale’s abbreviated name.%A
Weekday as locale’s full name.%w
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday.%d
Day of the month as a zero-padded decimal number.%b
Month as locale’s abbreviated name.%B
Month as locale’s full name.%m
Month as a zero-padded decimal number. 01, ..., 12%y
Year without century as a zero-padded decimal number. 00, ..., 99%Y
Year with century as a decimal number. 1970, 1988, 2001, 2013%H
Hour (24-hour clock) as a zero-padded decimal number. 00, ..., 23%I
Hour (12-hour clock) as a zero-padded decimal number. 01, ..., 12%p
Locale’s equivalent of either AM or PM.%M
Minute as a zero-padded decimal number. 00, ..., 59%S
Second as a zero-padded decimal number. 00, ..., 59%f
Microsecond as a decimal number, zero-padded on the left. 000000, ..., 999999%z
UTC offset in the form +HHMM or -HHMM (empty if naive), +0000, -0400, +1030%Z
Time zone name (empty if naive), UTC, EST, CST%j
Day of the year as a zero-padded decimal number. 001, ..., 366%U
Week number of the year (Sunday is the first) as a zero padded decimal number.%W
Week number of the year (Monday is first) as a decimal number.%c
Locale’s appropriate date and time representation.%x
Locale’s appropriate date representation.%X
Locale’s appropriate time representation.%%
A literal '%' character.It depends on what exactly you want to accomplish. Let's assume you have this structure:
<p style="width:400px;">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet.
</p>
If you want the space between the single lines to be bigger, you should increase
line-height
If you want the space at the end to be bigger, you should increase
margin-bottom
If you want the space at the end to be bigger, but have the background fill the space (or the border around the space) use
padding-bottom
Of course, there are also the corresponding values for space on the top:
padding-top
margin-top
Some examples:
<p style="line-height: 30px; width: 300px; border: 1px solid black;">
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
Space between single lines
</p>
<p style="margin-bottom: 30px; width: 300px; border: 1px solid black;">
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
Space at the bottom, outside of the border
</p>
<p style="padding-bottom: 30px; width: 300px; border: 1px solid black;">
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
Space at the bottom, inside of the border
</p>
here you can see this code in action: http://jsfiddle.net/ramsesoriginal/H7qxd/
Of course you should put your styles in a separate stylesheet, the inline code was just to show the effect.
here you have a little schematic demonstration of what which value affects:
line-height
content +
| padding-bottom
<----------------+ +
content | border-bottom
| +
| |
+-------------+<------------------+ | margin-bottom
| +
+===================+ <-------------------+ |
|
+-------------------------+ <------------------------+
No, that's the correct way to do it. This worked exactly as it should, something you can work from perhaps:
using System;
class Program {
static void Main(string[] args) {
System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
throw new Exception("Kaboom");
}
static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
Console.WriteLine(e.ExceptionObject.ToString());
Console.WriteLine("Press Enter to continue");
Console.ReadLine();
Environment.Exit(1);
}
}
Do keep in mind that you cannot catch type and file load exceptions generated by the jitter this way. They happen before your Main() method starts running. Catching those requires delaying the jitter, move the risky code into another method and apply the [MethodImpl(MethodImplOptions.NoInlining)] attribute to it.
Not only is it the preferred way, it's the only reasonable way. Because strings are immutable, in order to "remove" a char from a string you have to create a new string whenever you want a different string value.
You may be wondering why strings are immutable, given that you have to make a whole new string every time you change a character. After all, C strings are just arrays of characters and are thus mutable, and some languages that support strings more cleanly than C allow mutable strings as well. There are two reasons to have immutable strings: security/safety and performance.
Security is probably the most important reason for strings to be immutable. When strings are immutable, you can't pass a string into some library and then have that string change from under your feet when you don't expect it. You may wonder which library would change string parameters, but if you're shipping code to clients you can't control their versions of the standard library, and malicious clients may change out their standard libraries in order to break your program and find out more about its internals. Immutable objects are also easier to reason about, which is really important when you try to prove that your system is secure against particular threats. This ease of reasoning is especially important for thread safety, since immutable objects are automatically thread-safe.
Performance is surprisingly often better for immutable strings. Whenever you take a slice of a string, the Python runtime only places a view over the original string, so there is no new string allocation. Since strings are immutable, you get copy semantics without actually copying, which is a real performance win.
Eric Lippert explains more about the rationale behind immutable of strings (in C#, not Python) here.
I'm running Ubuntu Server 14.04, Ruby 2.2.1 and Rails 4.2.4 I have followed a deploy turorial from DigitalOcean and everything went well but when I go to the browser and enter the IP address of my VPS my app is loaded but without styles and javascript.
The app is running with Unicorn and Nginx. To fix this problem I entered my server using SSH with my user 'deployer' and go to my app path which is '/home/deployer/apps/blog' and run the following command:
RAILS_ENV=production bin/rake assets:precompile
Then I just restart the VPS and that's it! It works for me!
Hope it could be useful for somebody else!
The fastest way is to do a*a
or a**2
or np.square(a)
whereas np.power(a, 2)
showed to be considerably slower.
np.power()
allows you to use different exponents for each element if instead of 2
you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2
or a*a
, which become important in cases where you have small tolerances.
I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:
In [29]: a = np.random.random((1000, 1000))
In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop
In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop
In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
<div class='block1'>
<p style="float:left">text</p>
<div class='block2' style="float:right">block2</div>
<p style="float:left; clear:left">text2</p>
</div>
You can clear:both
or clear:left
depending on the exact context.
Also, you will have to play around with width
to get it to work correctly...
Just background-size: contain;
works for me:
div {
background-image: url('your-image.png');
background-size: contain;
}
_x000D_
Swift 4, 4.2 & 5
var timeZone : String = String()
override func viewDidLoad() {
super.viewDidLoad()
timeZone = getCurrentTimeZone()
print(timeZone)
}
func getCurrentTimeZone() -> String {
let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
let items = (localTimeZoneAbbreviation / 3600)
return "\(items)"
}
int fib(int x)
{
if (x < 2)
return x;
else
return (fib(x - 1) + fib(x - 2));
}
Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so:
cd /mnt/c/Program\ Files
.
I see there are so many useful answers here but still, I come across a handy and useful article out there. https://www.thesslstore.com/blog/clear-hsts-settings-chrome-firefox/
I ran into the same issue and that article helped me to what exactly it is and how to deal with that HTH :-)
In a View, in my case a SurfaceView subclass, you can set the screen on always on. I wanted the screen to stay on while this view was still drawing stuff.
public class MyCoolSurfaceView extends SurfaceView {
@Override
protected void onAttachedToWindow (){
super.onAttachedToWindow();
this.setKeepScreenOn(true);
}
@Override
protected void onDetachedFromWindow(){
super.onDetachedFromWindow();
this.setKeepScreenOn(false);
}
Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.
DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)
name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)
Try just clearing the data (not the entire table including headers):
ACell.ListObject.DataBodyRange.ClearContents
Here you've got a very detailed explanation of their differences
http://kyleschaeffer.com/development/css-font-size-em-vs-px-vs-pt-vs/
The jist of it (from source)
Pixels are fixed-size units that are used in screen media (i.e. to be read on the computer screen). Pixel stands for "picture element" and as you know, one pixel is one little "square" on your screen. Points are traditionally used in print media (anything that is to be printed on paper, etc.). One point is equal to 1/72 of an inch. Points are much like pixels, in that they are fixed-size units and cannot scale in size.
There is a library for this BarCode PHP. You just need to include a few files:
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
You can generate many types of barcodes, namely 1D or 2D. Add the required library:
require_once('class/BCGcode39.barcode.php');
Generate the colours:
// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);
After you have added all the codes, you will get this way:
Example
Since several have asked for an example here is what I was able to do to get it done
require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');
require_once('class/BCGcode128.barcode.php');
header('Content-Type: image/png');
$color_white = new BCGColor(255, 255, 255);
$code = new BCGcode128();
$code->parse('HELLO');
$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);
$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
If you want to actually create the image file so you can save it then change
$drawing = new BCGDrawing('', $color_white);
to
$drawing = new BCGDrawing('image.png', $color_white);
A particularly feisty example is when you decide to show a managed Dialog from an Activity using showDialog()
. If the user rotates the screen while the dialog is still open (we call this a "configuration change"), then the main Activity will go through all the ending lifecycle calls up untill onDestroy()
, will be recreated, and go back up through the lifecycles. What you might not expect however, is that onCreateDialog()
and onPrepareDialog()
(the methods that are called when you do showDialog()
and now again automatically to recreate the dialog - automatically since it is a managed dialog) are called between onStart()
and onResume()
. The pointe here is that the dialog does not cover the full screen and therefore leaves part of the main activity visible. It's a detail but it does matter!
In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.
The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:
<div ng-app>
<div
class="italic"
ng-class="{red: hover}"
ng-init="hover = false"
ng-mouseenter="hover = true"
ng-mouseleave="hover = false">
Test 1 2 3.
</div>
</div>
with some styling:
.red {
background-color: red;
}
.italic {
font-style: italic;
color: black;
}
See running example here: jsfiddle sample
Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.
I usually go for the visibility:hidden
trick
this is my styled button
<div id="uploadbutton" class="btn btn-success btn-block">Upload</div>
this is the input type=file button. Note the visibility:hidden
rule
<input type="file" id="upload" style="visibility:hidden;">
this is the JavaScript bit to glue them together. It works
<script>
$('#uploadbutton').click(function(){
$('input[type=file]').click();
});
</script>
you have an type error in example of code. You forget curlybracket after success
$.ajax({
type: "POST",
url: '@Url.Action("Search","Controller")',
data: "{queryString:'" + searchVal + "'}",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.d.toString());
}
})
;
To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:
You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".
If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old
git branch
to see what branch origin is currently on. To change it to another branch, you have to usegit symbolic-ref HEAD refs/heads/another-branch
.
Newer versions of vim allow a :set numberwidth=x
value, which sets the width of the line number display. I don't really use folding etc, so I wouldn't know about that though. Drawing a thin vertical line is beyond the abilities of a console application though. GVim may allow this (I don't use it, so can't comment there).
You can use LIKE
instead of =
. Without any wildcards this will have the same effect.
DECLARE @Village TABLE
(CastleType TEXT)
INSERT INTO @Village
VALUES
(
'foo'
)
SELECT *
FROM @Village
WHERE [CastleType] LIKE 'foo'
text
is deprecated. Changing to varchar(max)
will be easier to work with.
Also how large is the data likely to be? If you are going to be doing equality comparisons you will ideally want to index this column. This isn't possible if you declare the column as anything wider than 900 bytes though you can add a computed checksum
or hash
column that can be used to speed this type of query up.
Just an important note. If you have HTML comment and your uncomment doesn't work
(Maybe it's a PHP file), so don't mark all the comment but just put your cursor at the end or at the beginning of the comment (before ) and try again (Ctrl+/).
System properties are set on the Java command line using the -Dpropertyname=value
syntax. They can also be added at runtime
using System.setProperty(String key, String value)
or via the various
System.getProperties().load()
methods.
To get a specific system property you can use System.getProperty(String key)
or System.getProperty(String key, String def)
.
Environment variables are set in the OS, e.g. in Linux export HOME=/Users/myusername
or on Windows SET WINDIR=C:\Windows
etc,
and, unlike properties, may not be set at runtime.
To get a specific environment variable you can use System.getenv(String name)
.
I agree with Brandrew, the problem is most likely caused by some missing dlls that can't be found neither on the system path nor in the folder where the executable is. Try putting the following DLLs nearby the executable:
Alternatively, try loading the executable into Dependency Walker ( http://www.dependencywalker.com/ ), it should point out the missing dlls for you.
use auto and min or max width like this:
td {
max-width:50px;
width:auto;
min-width:10px;
}
Use bulk_create()
method. It's standard in Django now.
Example:
Entry.objects.bulk_create([
Entry(headline="Django 1.0 Released"),
Entry(headline="Django 1.1 Announced"),
Entry(headline="Breaking: Django is awesome")
])
Set display: table
for parent div and display: table-cell
for children divs
HTML :
<div class="container-fluid">
<div class="row justify-content-center display-as-table">
<div class="col-4 hidden-md-down" id="yellow">
XXXX<br />
XXXX<br />
XXXX<br />
XXXX<br />
XXXX<br />
XXXX<br />vv
XXXX<br />
</div>
<div class="col-10 col-sm-10 col-md-10 col-lg-8 col-xl-8" id="red">
Form Goes Here
</div>
</div>
</div>
CSS:
#yellow {
height: 100%;
background: yellow;
width: 50%;
}
#red {background: red}
.container-fluid {bacgkround: #ccc}
/* this is the part make equal height */
.display-as-table {display: table; width: 100%;}
.display-as-table > div {display: table-cell; float: none;}
>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]
First you create the branch locally:
git checkout -b your_branch
And then to create the branch remotely:
git push --set-upstream origin your_branch
Note: This works on the latests versions of git:
$ git --version
git version 2.3.0
Cheers!
You should use the substring() method of String object.
Here is an example code:
Assumption: I am assuming here that you want to retrieve the string till the first parenthesis
String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);
letsay $infile = a.csv //file needs to be imported.
class blah
{
static public function readJobsFromFile($file)
{
if (($handle = fopen($file, "r")) === FALSE)
{
echo "readJobsFromFile: Failed to open file [$file]\n";
die;
}
$header=true;
$index=0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
{
// ignore header
if ($header == true)
{
$header = false;
continue;
}
if ($data[0] == '' && $data[1] == '' ) //u have oly 2 fields
{
echo "readJobsFromFile: No more input entries\n";
break;
}
$a = trim($data[0]);
$b = trim($data[1]);
if (check_if_exists("SELECT count(*) FROM Db_table WHERE a='$a' AND b='$b'") === true)
{
$index++;
continue;
}
$sql = "INSERT INTO DB_table SET a='$a' , b='$b' ";
@mysql_query($sql) or die("readJobsFromFile: " . mysql_error());
$index++;
}
fclose($handle);
return $index; //no. of fields in database.
}
function
check_if_exists($sql)
{
$result = mysql_query($sql) or die("$sql --" . mysql_error());
if (!$result) {
$message = 'check_if_exists::Invalid query: ' . mysql_error() . "\n";
$message .= 'Query: ' . $sql;
die($message);
}
$row = mysql_fetch_assoc ($result);
$count = $row['count(*)'];
if ($count > 0)
return true;
return false;
}
$infile=a.csv;
blah::readJobsFromFile($infile);
}
hope this helps.
[root@localhost administrador]# yum search mysql | grep client
community-mysql.i686 : MySQL client programs and shared libraries
: client
community-mysql-libs.i686 : The shared libraries required for MySQL clients
root-sql-mysql.i686 : MySQL client plugin for ROOT
mariadb-libs.i686 : The shared libraries required for MariaDB/MySQL clients
[root@localhost administrador]# yum install -y community-mysql
Here is complete Solution in Swift 4 implement this in didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let isLogin = UserDefaults.standard.bool(forKey: "Islogin")
if isLogin{
self.NextViewController(storybordid: "OtherViewController")
}else{
self.NextViewController(storybordid: "LoginViewController")
}
}
write this Function any where inside Appdelegate.swift
func NextViewController(storybordid:String)
{
let storyBoard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let exampleVC = storyBoard.instantiateViewController(withIdentifier:storybordid )
// self.present(exampleVC, animated: true)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = exampleVC
self.window?.makeKeyAndVisible()
}
Using the code example below will return to you the bitmap :
BitmapFactory.decodeStream(getContentResolver().openInputStream(Uri.parse("content://com.whatsapp.provider.media/item/128752")))
After that you all know what you have to do.
you can use this module -> https://github.com/jiahut/ng.lodash
this is for lodash
so does underscore
In bootstrap you can use .text-center
to align center. also add .row
and .col-md-*
to your code.
align=
is deprecated,
Added .col-xs-*
for demo
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<div class="footer">
<div class="container">
<div class="row">
<div class="col-xs-4">
<p>Hello there</p>
</div>
<div class="col-xs-4 text-center">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="col-xs-4 text-right">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
</div>
_x000D_
For those who are reading this and want to use the new version of bootstrap (beta version), you can do the above in a simpler way, using Boostrap Flexbox utilities classes
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" />
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container footer">
<div class="d-flex justify-content-between">
<div class="p-1">
<p>Hello there</p>
</div>
<div class="p-1">
<a href="#" class="btn btn-warning" onclick="changeLook()">Re</a>
<a href="#" class="btn btn-warning" onclick="changeBack()">Rs</a>
</div>
<div class="p-1">
<a href="#"><i class="fa fa-facebook-square fa-2x"></i></a>
<a href="#"><i class="fa fa-twitter fa-2x"></i></a>
<a href="#"><i class="fa fa-google-plus fa-2x"></i></a>
</div>
</div>
</div>
_x000D_
You can also move mounted
out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.
function init() {
// Use `this` normally
}
new Vue({
methods:{
init
},
mounted(){
init.call(this)
}
})
Add set off also
SET IDENTITY_INSERT Genre ON
INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20)
SET IDENTITY_INSERT Genre OFF
I just had this problem setting up my new laptop. The issue for me was that my toolchain (CodeSourcery) is 32bit and I had not installed the 32bit libs.
sudo apt-get install ia32-libs
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
From VSCode Commande Palette select :
GitHub Pull Requests : Sign out of GitHub.
Then Sign in with your new credential.
This appears to fit what you are looking for: https://forums.oracle.com/forums/thread.jspa?threadID=2140801
Basically, you will need to use regular expressions as there appears to be nothing built into oracle for this.
I pulled out the example from the thread and converted it for your purposes. I suck at regex's, though, so that might need tweaked :)
SELECT *
FROM myTable m
WHERE NOT regexp_like(m.status,'((Done^|Finished except^|In Progress^)')
Try this:
String urle = HOST + url + value;
Then return the values from:
urle.replace(" ", "%20").trim();
Assuming you are a new starter on Android Studio, Simply you can get it done in design view XML by using
android:textStyle="bold" //to make text bold
android:textStyle="italic" //to make text italic
android:textStyle="bold|italic" //to make text bold & italic
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
namespace WebserverInteractionClassLibrary
{
public class RequestManager
{
public string LastResponse { protected set; get; }
CookieContainer cookies = new CookieContainer();
internal string GetCookieValue(Uri SiteUri,string name)
{
Cookie cookie = cookies.GetCookies(SiteUri)[name];
return (cookie == null) ? null : cookie.Value;
}
public string GetResponseContent(HttpWebResponse response)
{
if (response == null)
{
throw new ArgumentNullException("response");
}
Stream dataStream = null;
StreamReader reader = null;
string responseFromServer = null;
try
{
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
reader = new StreamReader(dataStream);
// Read the content.
responseFromServer = reader.ReadToEnd();
// Cleanup the streams and the response.
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (reader != null)
{
reader.Close();
}
if (dataStream != null)
{
dataStream.Close();
}
response.Close();
}
LastResponse = responseFromServer;
return responseFromServer;
}
public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
{
HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
return GetResponse(request);
}
public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
{
HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
return GetResponse(request);
}
public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
{
HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
return GetResponse(request);
}
public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
{
return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
}
public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
{
return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
}
internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
// Set the Method property of the request to POST.
request.Method = method;
// Set cookie container to maintain cookies
request.CookieContainer = cookies;
request.AllowAutoRedirect = allowAutoRedirect;
// If login is empty use defaul credentials
if (string.IsNullOrEmpty(login))
{
request.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else
{
request.Credentials = new NetworkCredential(login, password);
}
if (method == "POST")
{
// Convert POST data to a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(content);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
}
return request;
}
internal HttpWebResponse GetResponse(HttpWebRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)request.GetResponse();
cookies.Add(response.Cookies);
// Print the properties of each cookie.
Console.WriteLine("\nCookies: ");
foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
{
Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
}
}
catch (WebException ex)
{
Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return response;
}
}
}
Here's an easy way using jQuery.
var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();
Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.
try: toolbar.setTitle(" ");
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
Everyone here is talking about the similarities of the two. I am gonna point out the differences.
Using new Object()
allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:
var obj1 = new Object();
obj1.a = 1;
var obj2 = new Object(obj1);
obj2.a // 1
The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.
var obj = new Object(1);
typeof obj // "number"
The object created using the above method (new Object(1)
) would be converted to object type if a property is added to it.
var obj = new Object(1);
typeof obj // "number"
obj.a = 2;
typeof obj // "object"
If the object is a copy of a child class of object, we could add the property without the type conversion.
var obj = new Object("foo");
typeof obj // "object"
obj === "foo" // true
obj.a = 1;
obj === "foo" // true
obj.a // 1
var str = "foo";
str.a = 1;
str.a // undefined
Using BeautifulSoup the easiest way with less code to just get the strings, without empty lines and crap.
tag = <Parent_Tag_that_contains_the_data>
soup = BeautifulSoup(tag, 'html.parser')
for i in soup.stripped_strings:
print repr(i)
To remove the default MouseOver
behaviour on the Button
you will need to modify the ControlTemplate
. Changing your Style
definition to the following should do the trick:
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="Green"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
EDIT: It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...
del /s /q c:\where ever the file is\*
rmdir /s /q c:\where ever the file is\
mkdir c:\where ever the file is\
round(number, 1)
This is the way to convert a entity to XML File and then compress it:
private void downloadFile(EntityXML xml) {
string nameDownloadXml = "File_1.xml";
string nameDownloadZip = "File_1.zip";
var serializer = new XmlSerializer(typeof(EntityXML));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=" + nameDownloadZip);
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
var demoFile = archive.CreateEntry(nameDownloadXml);
using (var entryStream = demoFile.Open())
using (StreamWriter writer = new StreamWriter(entryStream, System.Text.Encoding.UTF8))
{
serializer.Serialize(writer, xml);
}
}
using (var fileStream = Response.OutputStream)
{
memoryStream.Seek(0, SeekOrigin.Begin);
memoryStream.CopyTo(fileStream);
}
}
Response.End();
}
With EL 2 you can do the following:
#{'this'.concat(' is').concat(' a').concat(' test!')}
Adding to above answers static methods are static dispatch means the compiler know which method will be executed at runtime as the static method can not be overridden while the class method can be a dynamic dispatch as subclass can override these.
If you want to change ng-view you'll have to use the '#'
$window.location.href= "#operation";
This little bit different idea. But it will useful to you. I have used sub query to inside the linq main query.
Problem:
Let say we have document table. Schema as follows schema : document(name,version,auther,modifieddate) composite Keys : name,version
So we need to get latest versions of all documents.
soloution
var result = (from t in Context.document
where ((from tt in Context.document where t.Name == tt.Name
orderby tt.Version descending select new {Vesion=tt.Version}).FirstOrDefault()).Vesion.Contains(t.Version)
select t).ToList();
I just wrote a blog post on saving an object's data to Binary, XML, or Json. You are correct that you must decorate your classes with the [Serializable] attribute, but only if you are using Binary serialization. You may prefer to use XML or Json serialization. Here are the functions to do it in the various formats. See my blog post for more details.
/// <summary>
/// Writes the given object instance to a binary file.
/// <para>Object type (and all child types) must be decorated with the [Serializable] attribute.</para>
/// <para>To prevent a variable from being serialized, decorate it with the [NonSerialized] attribute; cannot be applied to properties.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the binary file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the binary file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToBinaryFile<T>(string filePath, T objectToWrite, bool append = false)
{
using (Stream stream = File.Open(filePath, append ? FileMode.Append : FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
}
}
/// <summary>
/// Reads an object instance from a binary file.
/// </summary>
/// <typeparam name="T">The type of object to read from the binary file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the binary file.</returns>
public static T ReadFromBinaryFile<T>(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
return (T)binaryFormatter.Deserialize(stream);
}
}
Requires the System.Xml assembly to be included in your project.
/// <summary>
/// Writes the given object instance to an XML file.
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [XmlIgnore] attribute.</para>
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToXmlFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var serializer = new XmlSerializer(typeof(T));
writer = new StreamWriter(filePath, append);
serializer.Serialize(writer, objectToWrite);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an XML file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the XML file.</returns>
public static T ReadFromXmlFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
var serializer = new XmlSerializer(typeof(T));
reader = new StreamReader(filePath);
return (T)serializer.Deserialize(reader);
}
finally
{
if (reader != null)
reader.Close();
}
}
You must include a reference to Newtonsoft.Json assembly, which can be obtained from the Json.NET NuGet Package.
/// <summary>
/// Writes the given object instance to a Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// <para>Only Public properties and variables will be written to the file. These can be any type though, even other classes.</para>
/// <para>If there are public properties/variables that you do not want written to the file, decorate them with the [JsonIgnore] attribute.</para>
/// </summary>
/// <typeparam name="T">The type of object being written to the file.</typeparam>
/// <param name="filePath">The file path to write the object instance to.</param>
/// <param name="objectToWrite">The object instance to write to the file.</param>
/// <param name="append">If false the file will be overwritten if it already exists. If true the contents will be appended to the file.</param>
public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
TextWriter writer = null;
try
{
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
writer = new StreamWriter(filePath, append);
writer.Write(contentsToWriteToFile);
}
finally
{
if (writer != null)
writer.Close();
}
}
/// <summary>
/// Reads an object instance from an Json file.
/// <para>Object type must have a parameterless constructor.</para>
/// </summary>
/// <typeparam name="T">The type of object to read from the file.</typeparam>
/// <param name="filePath">The file path to read the object instance from.</param>
/// <returns>Returns a new instance of the object read from the Json file.</returns>
public static T ReadFromJsonFile<T>(string filePath) where T : new()
{
TextReader reader = null;
try
{
reader = new StreamReader(filePath);
var fileContents = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(fileContents);
}
finally
{
if (reader != null)
reader.Close();
}
}
// Write the contents of the variable someClass to a file.
WriteToBinaryFile<SomeClass>("C:\someClass.txt", object1);
// Read the file contents back into a variable.
SomeClass object1= ReadFromBinaryFile<SomeClass>("C:\someClass.txt");
Here is my version:
List<object> list = new List<object>(new object[]{ "test", 0, "hello", 1, "world" });
foreach(var x in list)
{
Console.WriteLine("x: {0}", x);
}
According to the RFC that introduced the operator, $a <=> $b
evaluates to:
$a == $b
$a < $b
$a > $b
which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b
will return
an integer less than, equal to, or greater than zero when
$a
is respectively less than, equal to, or greater than$b
Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort
(and the similar uasort
and uksort
).
usort
takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:
an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
The spaceship operator makes this succinct and convenient:
$things = [
[
'foo' => 5.5,
'bar' => 'abc'
],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];
// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});
// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});
More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
If you use MATLAB, any version since 2013b that is, you can make use of the function evalclusters
to find out what should the optimal k
be for a given dataset.
This function lets you choose from among 3 clustering algorithms - kmeans
, linkage
and gmdistribution
.
It also lets you choose from among 4 clustering evaluation criteria - CalinskiHarabasz
, DaviesBouldin
, gap
and silhouette
.
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str
is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str
which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
Try updating gradle dependency to 2.4. For that you need to go to
File -> Project Structure -> Project -> Gradle version
.
There you need to change from 2.2.1 to 2.4. Wait for new gradle version to be downloaded.
And you are ready to go.
Browse the repository with Firefox and inspect the element with Firebug. Under the NET tab, you can check the Header of the page. It will have something like:
Server: Apache/2.2.14 (Win32) DAV/2 SVN/1.X.X
It would appear as though this event has some clipboardData
property attached to it (it may be nested within the originalEvent
property). The clipboardData
contains an array of items and each one of those items has a getAsString()
function that you can call. This returns the string representation of what is in the item.
Those items also have a getAsFile()
function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry()
function).
For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:
$(element).bind("paste", function (e) {
e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
debugger;
// pStringRepresentation now contains the string representation of what was pasted.
// This does not include HTML or any markup. Essentially jQuery's $(element).text()
// function result.
});
});
You'll want to perform an iteration through the items, keeping a string concatenation result.
The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.
The recommended way in Python 3.5 and above is to use subprocess.run()
:
from subprocess import run
output = run("pwd", capture_output=True).stdout
In Unix CLI, it's very practical to redirect only errors to a file:
./script 2> errors.log
From your script, either use var_dump()
or equivalent as usual (both STDOUT and STDERR will receive the output), but to write only in the log file:
fwrite(STDERR, "Debug infos\n"); // Write in errors.log^
Then from another shell, for live changes:
tail -f errors.log
or simply
watch cat errors.log
Using the Random class is the way to go as suggested in the accepted answer, but here is a less straight-forward correct way of doing it if you didn't want to create a new Random object :
min + (int) (Math.random() * (max - min + 1));
There is now a php artisan view:clear
command for this task since Laravel 5.1
You can do this using jQuery's .scrollTop()
and .offset()
method
Check out my sample and this jsFiddle Demonstration
$(function() {
$(document).scrollTop( $("#header").offset().top );
});
In a nutshell, synchronization refers to two or more processes' start and end points, NOT their executions. In this example, Process A's endpoint is synchronized with Process B's start point:
SYNCHRONOUS |--------A--------| |--------B--------|
Asynchronous processes, on the other hand, do not have their start and endpoints synchronized:
ASYNCHRONOUS |--------A--------| |--------B--------|
Where Process A overlaps Process B, they're running concurrently or synchronously (dictionary definition), hence the confusion.
UPDATE: Charles Bretana improved his answer, so this answer is now just a simple (potentially oversimplified) mnemonic.
The reason you are not receiving the event is because the absolutely positioned element is not a child of the element you are wanting to "click" (blue div). The cleanest way I can think of is to put the absolute element as a child of the one you want clicked, but I'm assuming you can't do that or you wouldn't have posted this question here :)
Another option would be to register a click event handler for the absolute element and call the click handler for the blue div, causing them both to flash.
Due to the way events bubble up through the DOM I'm not sure there is a simpler answer for you, but I'm very curious if anyone else has any tricks I don't know about!
After going over some of the answers here an in another thread, here's what I ended up with:
I created a function named showAlert()
that would dynamically add an alert, with an optional type
and closeDealy
. So that you can, for example, add an alert of type danger
(i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:
showAlert("Warning message", "danger", 5000);
To achieve that, add the following Javascript function:
function showAlert(message, type, closeDelay) {
if ($("#alerts-container").length == 0) {
// alerts-container does not exist, add it
$("body")
.append( $('<div id="alerts-container" style="position: fixed;
width: 50%; left: 25%; top: 10%;">') );
}
// default to alert-info; other options include success, warning, danger
type = type || "info";
// create the alert div
var alert = $('<div class="alert alert-' + type + ' fade in">')
.append(
$('<button type="button" class="close" data-dismiss="alert">')
.append("×")
)
.append(message);
// add the alert div to top of alerts-container, use append() to add to bottom
$("#alerts-container").prepend(alert);
// if closeDelay was passed - set a timeout to close the alert
if (closeDelay)
window.setTimeout(function() { alert.alert("close") }, closeDelay);
}
static
functions are functions that are only visible to other functions in the same file (more precisely the same translation unit).
EDIT: For those who thought, that the author of the questions meant a 'class method': As the question is tagged C
he means a plain old C function. For (C++/Java/...) class methods, static
means that this method can be called on the class itself, no instance of that class necessary.
It's short hand for the ternary operator.
FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();
Or for those who don't do ternary:
if (formsAuth != null)
{
FormsAuth = formsAuth;
}
else
{
FormsAuth = new FormsAuthenticationWrapper();
}
You can use {}
arround your variable, to separate it from what's after:
echo "{$test}y"
As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.
As hinted at by this post Error in chrome: Content-Type is not allowed by Access-Control-Allow-Headers just add the additional header to your web.config like so...
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
In latest 5.13 there's a difference. You do like always...
font-family: "Font Awesome 5 Free";
content: "\f107";
But there's a difference now... Instead of use font-weight: 500; You are following this:
font-family: "Font Awesome 5 Free";
font-weight: 900;
content: "\f107";
Why is that? I figure out by finding in in .fas class, so you can figure out an updated way by looking into .fas class so you're doing the same as it has to be. Figure out if there's a font-weight and font-family. Here you go guys. That's an update answer for 5.13.
I don't think location.LatLng
is working, however this works:
results[0].geometry.location.lat(), results[0].geometry.location.lng()
Found it while exploring Get Lat Lon source code.
If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough
set /p asd="Hit enter to continue"
at the end of your script and it'll keep the window open.
Note that this'll set asd
as an environment variable, and can be replaced with anything else.
It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change
event.
You can handle the blur
event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.
function URL() {
location.href = 'http://your.url.here';
}
I faced the same issue. I had entered http://www.example.com
in the App settings. When anybody accessed my website using the full URL, Facebook Login worked fine. But if somebody typed in the URL without www
in the browser, Facebook Login failed with this error message. When I changed the App Setting to http://example.com
everything started working fine.
Because in 2nd case you adding same reference twice and HashSet
have check against this in HashMap.put()
on which HashSet
is based:
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
As you can see, equals
will be called only if hash of key being added equals to the key already present in set and references of these two are different.
Very neat trick I stumble upon trying some SQL injection, in object explorer in the search box just use your percentage characters, and this will search EVERYTHING stored procedures, functions, views, tables, schema, indexes...I tired of thinking of more :)
You have two options. First one is very easy use Remove
method it is quite effective. Second way is to use ToString
with start index and end index (MSDN documentation)
Is to do with IPv6
All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx
Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...
I wrote this awhile back. It assumes the delimiter is a comma and that the individual values aren't bigger than 127 characters. It could be modified pretty easily.
It has the benefit of not being limited to 4,000 characters.
Good luck!
ALTER Function [dbo].[SplitStr] (
@txt text
)
Returns @tmp Table
(
value varchar(127)
)
as
BEGIN
declare @str varchar(8000)
, @Beg int
, @last int
, @size int
set @size=datalength(@txt)
set @Beg=1
set @str=substring(@txt,@Beg,8000)
IF len(@str)<8000 set @Beg=@size
ELSE BEGIN
set @last=charindex(',', reverse(@str))
set @str=substring(@txt,@Beg,8000-@last)
set @Beg=@Beg+8000-@last+1
END
declare @workingString varchar(25)
, @stringindex int
while @Beg<=@size Begin
WHILE LEN(@str) > 0 BEGIN
SELECT @StringIndex = CHARINDEX(',', @str)
SELECT
@workingString = CASE
WHEN @StringIndex > 0 THEN SUBSTRING(@str, 1, @StringIndex-1)
ELSE @str
END
INSERT INTO
@tmp(value)
VALUES
(cast(rtrim(ltrim(@workingString)) as varchar(127)))
SELECT @str = CASE
WHEN CHARINDEX(',', @str) > 0 THEN SUBSTRING(@str, @StringIndex+1, LEN(@str))
ELSE ''
END
END
set @str=substring(@txt,@Beg,8000)
if @Beg=@size set @Beg=@Beg+1
else IF len(@str)<8000 set @Beg=@size
ELSE BEGIN
set @last=charindex(',', reverse(@str))
set @str=substring(@txt,@Beg,8000-@last)
set @Beg=@Beg+8000-@last+1
END
END
return
END
In my case: You need to copy the whole font-awesome folder to your project css folder and not just the font-awesome.min.css file.
I would suggest you just write a function to do what you're saying probably using drop
(to delete columns) and insert
to insert columns at a position. There isn't an existing API function to do what you're describing.
While JS is probably the way to go, it could be done with HTML and CSS only.
Here you have a fake radio button which is really a label for a real hidden radio button. By doing that, you get exactly the effect you need.
<style>
#uncheck>input { display: none }
input:checked + label { display: none }
input:not(:checked) + label + label{ display: none }
</style>
<div id='uncheck'>
<input type="radio" name='food' id="box1" />
Pizza
<label for='box1'>◎</label>
<label for='box0'>◉</label>
<input type="radio" name='food' id="box2" />
Ice cream
<label for='box2'>◎</label>
<label for='box0'>◉</label>
<input type="radio" name='food' id="box0" checked />
</div>
See it here: https://jsfiddle.net/tn70yxL8/2/
Now, that assumes you need non-selectable labels.
If you were willing to include the labels, you can technically avoid repeating the "uncheck" label by changing its text in CSS, see here: https://jsfiddle.net/7tdb6quy/2/
In 9.4.4 using the #>>
operator works for me:
select to_json('test'::text) #>> '{}';
To use with a table column:
select jsoncol #>> '{}' from mytable;
You can use the cherry-pick to get the particular bug fix commit(s)
$ git checkout branch
$ git cherry-pick bugfix
Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.
To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.
Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.
Hope it helps Rihan
you can try following
int index = 0;
WebElement baseTable = driver.findElement(By.className("table gradient myPage"));
List<WebElement> tableRows = baseTable.findElements(By.tagName("tr"));
tableRows.get(index).getText();
You can also iterate over tablerows to perform any function you want.
I usually use usort, and pass my own comparison function. In this case, it is very simple:
function compareOrder($a, $b)
{
return $a['order'] - $b['order'];
}
usort($array, 'compareOrder');
In PHP 7 using spaceship operator:
usort($array, function($a, $b) {
return $a['order'] <=> $b['order'];
});
As long as these are only "<" and ">" (and not the double quote itself) characters and you're using them in context like <input value="this" />, you're safe (while for <textarea>this one</textarea> you would be vulnerable of course). That may simplify your situation, but for anything more use one of other posted solutions.
Greg is absolutely correct. This kind of parsing cannot be done with regular expressions. I suppose it is possible to build some horrendous monstrosity that would work for many cases, but then you'll just run across something that does.
You really need to use more traditional parsing techniques. For example, its pretty simple to write a recursive decent parser to do what you need.
Oracle: Thin-style Service Name Syntax
Thin-style service names are supported only by the JDBC Thin driver. The syntax is:
@//host_name:port_number/service_name
http://docs.oracle.com/cd/B28359_01/java.111/b31224/urls.htm#BEIDHCBA
<script type="text/javascript">
$(document).ready(function() {
var asdf = $('.capsf').text();
$('.capsf').text(asdf.toLowerCase());
});
</script>
<div style="text-transform: capitalize;" class="capsf">sd GJHGJ GJHgjh gh hghhjk ku</div>
Lines starting with "rem" (from the word remarks) are comments:
rem comment here
echo "hello"
I wonder why no one added the alternative of using the function chr()
:
echo 'Hello World!' . chr(10);
or, more efficient if you're going to repeat it a million times:
define('C_NewLine', chr(10));
...
echo 'Hello World!' . C_NewLine;
This avoids the silly-looking notation of concatenating a single- and double-quoted string.
It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.
This works:
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot()
The does not:
ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot()
*Error in + geom_boxplot():
invalid argument to unary operator*
You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.
The best way to create the SQL database schema using an XSD file is a program called Altova XMLSpy, this is very simple:
Hope it helps.
SIMPLE
It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.
Example :
0x6400
translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600.
When compiler reads 0x6400
, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8
or any base ..
Hope Helped in some way.
Good day,
assets/images
folderpubspec.yaml
file.assets
or images
. You don't even need to make images
a subfolder. Whatever name you use, though, is what you will regester in the pubspec.yaml
file.assets/images
. The relative path of lake.jpg
, for example, would be assets/images/lake.jpg
.pubspec.yaml
Open the pubspec.yaml
file that is in the root of your project.
Add an assets
subsection to the flutter
section like this:
flutter:
assets:
- assets/images/lake.jpg
If you have multiple images that you want to include then you can leave off the file name and just use the directory name (include the final /
):
flutter:
assets:
- assets/images/
Get the asset in an Image widget with Image.asset('assets/images/lake.jpg')
.
The entire main.dart
file is here:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text("Image from assets"),
),
body: Image.asset('assets/images/lake.jpg'), // <--- image
),
);
}
}
When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.
Running the app now you should have something like this:
The first video here goes into a lot of detail about how to include images in your app. The second video covers more about how to adjust how they look.
It's probably caused by a local network connectivity issue (but also a DNS error is possible). Unfortunately HResult
is generic, however you can determine the exact issue catching HttpRequestException
and then inspecting InnerException
: if it's a WebException
then you can check the WebException.Status
property, for example WebExceptionStatus.NameResolutionFailure
should indicate a DNS resolution problem.
It may happen, there isn't much you can do.
What I'd suggest to always wrap that (network related) code in a loop with a try
/catch
block (as also suggested here for other fallible operations). Handle known exceptions, wait a little (say 1000 msec) and try again (for say 3 times). Only if failed all times then you can quit/report an error to your users. Very raw example like this:
private const int NumberOfRetries = 3;
private const int DelayOnRetry = 1000;
public static async Task<HttpResponseMessage> GetFromUrlAsync(string url) {
using (var client = new HttpClient()) {
for (int i=1; i <= NumberOfRetries; ++i) {
try {
return await client.GetAsync(url);
}
catch (Exception e) when (i < NumberOfRetries) {
await Task.Delay(DelayOnRetry);
}
}
}
}
That is nice question :)
When you have situation with 1 cell (A1), it is important to identify if second declared cell is not empty (sh.Range("A1").End(xlDown)
). If it is true it means your range got out of control :) Look at code below:
Dim sh As Worksheet
Set sh = ThisWorkbook.Sheets("Arkusz1")
Dim k As Long
If IsEmpty(sh.Range("A1").End(xlDown)) = True Then
k = 1
Else
k = sh.Range("A1", sh.Range("A1").End(xlDown)).Rows.Count
End If
Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences
I found that while adding
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
helps, sometimes it's a matter of your querying that determines how express handles it.
For instance, it could be that your parameters are passed in the URL rather than in the body
In such a case, you need to capture both the body and url parameters and use whichever is available (with preference for the body parameters in the case below)
app.route('/echo')
.all((req,res)=>{
let pars = (Object.keys(req.body).length > 0)?req.body:req.query;
res.send(pars);
});
This solution works for me:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py --force-reinstall
or use sudo for elevated permissions (sudo python3 get-pip.py --force-reinstall
).
Of course, you can also use python
instead of python3
;)
This will probably only affect a small percentage of people, but in my case my project was using CocoaPods and one of those pods had a sub spec with its own CocoaPods. The solution was to use full angle imports to reference any files in the sub-pods.
#import <HexColors/HexColor.h>
Rather than
#import "HexColor.h"
I have problem with this error handling approach: In case of web.config:
<customErrors mode="On"/>
The error handler is searching view Error.shtml and the control flow step in to Application_Error global.asax only after exception
System.InvalidOperationException: The view 'Error' or its master was not found or no view engine supports the searched locations. The following locations were searched: ~/Views/home/Error.aspx ~/Views/home/Error.ascx ~/Views/Shared/Error.aspx ~/Views/Shared/Error.ascx ~/Views/home/Error.cshtml ~/Views/home/Error.vbhtml ~/Views/Shared/Error.cshtml ~/Views/Shared/Error.vbhtml at System.Web.Mvc.ViewResult.FindView(ControllerContext context) ....................
So
Exception exception = Server.GetLastError();
Response.Clear();
HttpException httpException = exception as HttpException;
httpException is always null then
customErrors mode="On"
:(
It is misleading
Then <customErrors mode="Off"/>
or <customErrors mode="RemoteOnly"/>
the users see customErrors html,
Then customErrors mode="On" this code is wrong too
Another problem of this code that
Response.Redirect(String.Format("~/Error/{0}/?message={1}", action, exception.Message));
Return page with code 302 instead real error code(402,403 etc)
Use the slicing operator:
list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
list[:10]
In my case, Android Studio 3.0.1, I fixed the issue with the following two steps.
Step 1: Change Gradle plugin version in project-level build.gradle
buildscript {
repositories {
jcenter()
mavenCentral()
maven {
url 'https://maven.google.com/'
name 'Google'
}
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
Step 2: Change gradle version
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
Using apache commons..
//For midnight today
Date today = new Date();
DateUtils.truncate(today, Calendar.DATE);
//For midnight tomorrow
Date tomorrow = DateUtils.addDays(today, 1);
DateUtils.truncate(tomorrow, Calendar.DATE);
CursorAdapter Example with Sqlite
...
DatabaseHelper helper = new DatabaseHelper(this);
aListView = (ListView) findViewById(R.id.aListView);
Cursor c = helper.getAllContacts();
CustomAdapter adapter = new CustomAdapter(this, c);
aListView.setAdapter(adapter);
...
class CustomAdapter extends CursorAdapter {
// CursorAdapter will handle all the moveToFirst(), getCount() logic for you :)
public CustomAdapter(Context context, Cursor c) {
super(context, c);
}
public void bindView(View view, Context context, Cursor cursor) {
String id = cursor.getString(0);
String name = cursor.getString(1);
// Get all the values
// Use it however you need to
TextView textView = (TextView) view;
textView.setText(name);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// Inflate your view here.
TextView view = new TextView(context);
return view;
}
}
private final class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "db_name";
private static final int DATABASE_VERSION = 1;
private static final String CREATE_TABLE_TIMELINE = "CREATE TABLE IF NOT EXISTS table_name (_id INTEGER PRIMARY KEY AUTOINCREMENT, name varchar);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_TIMELINE);
db.execSQL("INSERT INTO ddd (name) VALUES ('One')");
db.execSQL("INSERT INTO ddd (name) VALUES ('Two')");
db.execSQL("INSERT INTO ddd (name) VALUES ('Three')");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getAllContacts() {
String selectQuery = "SELECT * FROM table_name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
}
logger/index.js
const colors = {
Reset : "\x1b[0m",
Bright : "\x1b[1m",
Dim : "\x1b[2m",
Underscore : "\x1b[4m",
Blink : "\x1b[5m",
Reverse : "\x1b[7m",
Hidden : "\x1b[8m",
FgBlack : "\x1b[30m",
FgRed : "\x1b[31m",
FgGreen : "\x1b[32m",
FgYellow : "\x1b[33m",
FgBlue : "\x1b[34m",
FgMagenta : "\x1b[35m",
FgCyan : "\x1b[36m",
FgWhite : "\x1b[37m",
BgBlack : "\x1b[40m",
BgRed : "\x1b[41m",
BgGreen : "\x1b[42m",
BgYellow : "\x1b[43m",
BgBlue : "\x1b[44m",
BgMagenta : "\x1b[45m",
BgCyan : "\x1b[46m",
BgWhite : "\x1b[47m",
};
module.exports = () => {
Object.keys(colors).forEach(key => {
console['log' + key] = (strg) => {
if(typeof strg === 'object') strg = JSON.stringify(strg, null, 4);
return console.log(colors[key]+strg+'\x1b[0m');
}
});
}
app.js
require('./logger')();
Then use it like:
console.logBgGreen(" grüner Hintergrund ")
You created the UIButton
is added the ViewController
, The following instance method to change UIFont
, tintColor
and TextColor
of the UIButton
Objective-C
buttonName.titleLabel.font = [UIFont fontWithName:@"LuzSans-Book" size:15];
buttonName.tintColor = [UIColor purpleColor];
[buttonName setTitleColor:[UIColor purpleColor] forState:UIControlStateNormal];
Swift
buttonName.titleLabel.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purpleColor()
buttonName.setTitleColor(UIColor.purpleColor(), forState: .Normal)
Swift3
buttonName.titleLabel?.font = UIFont(name: "LuzSans-Book", size: 15)
buttonName.tintColor = UIColor.purple
buttonName.setTitleColor(UIColor.purple, for: .normal)
A less robust approach, but it works.
a = [2, 4, 5].toString();
b = [2, 4, 5].toString();
console.log(a===b);
You Can use this -
Suppose we have a list, l = [1,2,3,4,5]
We want to delete last two items in a single statement
del l[3:]
We have output:
l = [1,2,3]
Keep it Simple
Basic Authentication use base 64 Encoding for generating cryptographic string which contains the information of username and password.
Digest Access Authentication uses the hashing methodologies to generate the cryptographic result
just do Run as Administrator.......you need to run the program in the run as administrator mode in windows
Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx
int atoi(
const char *str
);
int _wtoi(
const wchar_t *str
);
int _atoi_l(
const char *str,
_locale_t locale
);
int _wtoi_l(
const wchar_t *str,
_locale_t locale
);
CString is wchar_t string. So, if you want convert Cstring to int, you can use:
CString s;
int test = _wtoi(s)
Once you start the web installer there's an option to download media, that being the full installation package. There's even download options for what kind of package to download.
git describe
is a porcelain command, which you should avoid:
http://git-blame.blogspot.com/2013/06/checking-current-branch-programatically.html
Instead, I used:
git name-rev --tags --name-only $(git rev-parse HEAD)
This happens because you put bracket of return
on the next line. That might be a common mistake if you write js without semicolons and use a style where you put opened braces on the next line.
Interpreter thinks that you return undefined and doesn't check your next line. That's the return
operator thing.
Put your opened bracket on the same line with the return
.
/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */
_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }
That works great!
// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass
{
border: 1px solid brown;
}
https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/
The following code example written in Java will allow you to execute any command on a foreign computer through SSH from within a java program. You will need to include the com.jcraft.jsch jar file.
/*
* SSHManager
*
* @author cabbott
* @version 1.0
*/
package cabbott.net;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SSHManager
{
private static final Logger LOGGER =
Logger.getLogger(SSHManager.class.getName());
private JSch jschSSHChannel;
private String strUserName;
private String strConnectionIP;
private int intConnectionPort;
private String strPassword;
private Session sesConnection;
private int intTimeOut;
private void doCommonConstructorActions(String userName,
String password, String connectionIP, String knownHostsFileName)
{
jschSSHChannel = new JSch();
try
{
jschSSHChannel.setKnownHosts(knownHostsFileName);
}
catch(JSchException jschX)
{
logError(jschX.getMessage());
}
strUserName = userName;
strPassword = password;
strConnectionIP = connectionIP;
}
public SSHManager(String userName, String password,
String connectionIP, String knownHostsFileName)
{
doCommonConstructorActions(userName, password,
connectionIP, knownHostsFileName);
intConnectionPort = 22;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = 60000;
}
public SSHManager(String userName, String password, String connectionIP,
String knownHostsFileName, int connectionPort, int timeOutMilliseconds)
{
doCommonConstructorActions(userName, password, connectionIP,
knownHostsFileName);
intConnectionPort = connectionPort;
intTimeOut = timeOutMilliseconds;
}
public String connect()
{
String errorMessage = null;
try
{
sesConnection = jschSSHChannel.getSession(strUserName,
strConnectionIP, intConnectionPort);
sesConnection.setPassword(strPassword);
// UNCOMMENT THIS FOR TESTING PURPOSES, BUT DO NOT USE IN PRODUCTION
// sesConnection.setConfig("StrictHostKeyChecking", "no");
sesConnection.connect(intTimeOut);
}
catch(JSchException jschX)
{
errorMessage = jschX.getMessage();
}
return errorMessage;
}
private String logError(String errorMessage)
{
if(errorMessage != null)
{
LOGGER.log(Level.SEVERE, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, errorMessage});
}
return errorMessage;
}
private String logWarning(String warnMessage)
{
if(warnMessage != null)
{
LOGGER.log(Level.WARNING, "{0}:{1} - {2}",
new Object[]{strConnectionIP, intConnectionPort, warnMessage});
}
return warnMessage;
}
public String sendCommand(String command)
{
StringBuilder outputBuffer = new StringBuilder();
try
{
Channel channel = sesConnection.openChannel("exec");
((ChannelExec)channel).setCommand(command);
InputStream commandOutput = channel.getInputStream();
channel.connect();
int readByte = commandOutput.read();
while(readByte != 0xffffffff)
{
outputBuffer.append((char)readByte);
readByte = commandOutput.read();
}
channel.disconnect();
}
catch(IOException ioX)
{
logWarning(ioX.getMessage());
return null;
}
catch(JSchException jschX)
{
logWarning(jschX.getMessage());
return null;
}
return outputBuffer.toString();
}
public void close()
{
sesConnection.disconnect();
}
}
For testing.
/**
* Test of sendCommand method, of class SSHManager.
*/
@Test
public void testSendCommand()
{
System.out.println("sendCommand");
/**
* YOU MUST CHANGE THE FOLLOWING
* FILE_NAME: A FILE IN THE DIRECTORY
* USER: LOGIN USER NAME
* PASSWORD: PASSWORD FOR THAT USER
* HOST: IP ADDRESS OF THE SSH SERVER
**/
String command = "ls FILE_NAME";
String userName = "USER";
String password = "PASSWORD";
String connectionIP = "HOST";
SSHManager instance = new SSHManager(userName, password, connectionIP, "");
String errorMessage = instance.connect();
if(errorMessage != null)
{
System.out.println(errorMessage);
fail();
}
String expResult = "FILE_NAME\n";
// call sendCommand for each command and the output
//(without prompts) is returned
String result = instance.sendCommand(command);
// close only after all commands are sent
instance.close();
assertEquals(expResult, result);
}
Try This :
<input min="0" max="100" id="when_change_range" type="range">
<input type="text" id="text_for_show_range">
and in jQuery section :
$('#when_change_range').change(function(){
document.getElementById('text_for_show_range').value=$(this).val();
});
You can use int casting which allows the base specification.
int(b, 2) # Convert a binary string to a decimal int.
From my recent experience, JsonReader#setLenient
basically makes the parser very tolerant, even to allow malformed JSON data.
But for certain data retrieved from your trusted RESTful API(s), this error might be caused by trailing white spaces. In such cases, simply trim
the data would avoid the error:
String trimmed = result1.trim();
Then gson.fromJson(trimmed, T)
might work. Surely this only covers a special case, so YMMV.
Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.
Macport packages tend to be maintained by a single person.
Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.
Both package managers will ask to be regularly updated. This can take some time.
Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.
Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.
You could use gitk --all
and search for commits "touching paths" and the pathname you are interested in.
Jquery later allowed you to to find the parents with the .parents()
method.
Hence I recommend using:
var $div = $('#divid').parents('div[class^="div-a"]');
This gives all parent nodes matching the selector. To get the first parent matching the selector use:
var $div = $('#divid').parents('div[class^="div-a"]').eq(0);
For other such DOM traversal queries, check out the documentation on traversing the DOM.
Use an infinite loop:
while True:
print('Hello world!')
This certainly can apply to your start()
function as well; you can exit the loop with either break
, or use return
to exit the function altogether, which also terminates the loop:
def start():
print ("Welcome to the converter toolkit made by Alan.")
while True:
op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
if op == "1":
f1 = input ("Please enter your fahrenheit temperature: ")
f1 = int(f1)
a1 = (f1 - 32) / 1.8
a1 = str(a1)
print (a1+" celsius")
elif op == "2":
m1 = input ("Please input your the amount of meters you wish to convert: ")
m1 = int(m1)
m2 = (m1 * 100)
m2 = str(m2)
print (m2+" m")
if op == "3":
mb1 = input ("Please input the amount of megabytes you want to convert")
mb1 = int(mb1)
mb2 = (mb1 / 1024)
mb3 = (mb2 / 1024)
mb3 = str(mb3)
print (mb3+" GB")
else:
print ("Sorry, that was an invalid command!")
If you were to add an option to quit as well, that could be:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
return
for example.
If you have multiple versions as well as multiple architectures (32 bit, 64 bit) you will need to add a -32 or -64 at the end of your version.
For windows, go to cmd and type py --list and it will produce the versions you have installed. The list will look like the following:
Installed Pythons found by py Launcher for Windows
-3.7-64 *
-3.7-32
-3.6-32
The full command as an example will be:
py -3.6-32 -m pip install (package)
If you want to get more indepth, to install a specific version of a package on a specific version of python, use ==(version) after the package. As an example,
py -3.6-32 -m pip install opencv-python==4.1.0.25
"\t"
not '\t'
, php doesnt escape in single quotes
You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.
This is can done in this way:
add hash in the url of next_page : example.com#hashkey
$( document ).ready(function() {
##get hash code at next page
var hashcode = window.location.hash;
## move page to any specific position of next page(let that is div with id "hashcode")
$('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
});
My version:
div#dashmain { margin-left:150px; }
div#dashside {position:fixed; width:150px; height:100%; }
<div id="dashside"></div>
<div id="dashmain">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">Content</div>
</div>
</div>
</div>
Can you consider using Nix http://nixos.org/nix/ ?
Nix supports multi-user package management: multiple users can share a common Nix store securely, don’t need to have root privileges to install software, and can install and use different versions of a package.
Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size
without using jQuery.
$(document).ready(function() {_x000D_
$('#openFile').on('change', function(evt) {_x000D_
console.log(this.files[0].size);_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">_x000D_
<input id="openFile" name="img" type="file" />_x000D_
</form>
_x000D_
Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
>>> lst = ['abcd', 'e', 'fg', 'hijklmn', 'opq', 'r']
>>> print [lst[2*i]+lst[2*i+1] for i in range(len(lst)/2)]
['abcde', 'fghijklmn', 'opqr']
In SQL
you can not have a variable array.
However, the best alternative solution is to use a temporary table.