def my_func(mandatory_arg, optional_arg=100):
print(mandatory_arg, optional_arg)
http://docs.python.org/2/tutorial/controlflow.html#default-argument-values
I find this more readable than using **kwargs
.
To determine if an argument was passed at all, I use a custom utility object as the default value:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
...
I have tended in the past to work on my functions in two stages. The first stage would be to treat them as fairly normal SQL queries and make sure that I am getting the right results out of it. After I am confident that it is performing as desired, then I would convert it into a UDF.
Base64 encoding converts three 8-bit bytes (0-255) into four 6-bit bytes (0-63 aka base64). Each of the four bytes indexes an ASCII string which represents the final output as four 8-bit ASCII characters. The indexed string is typically 'A-Za-z0-9+/' with '=' used as padding. This is why encoded data is 4/3 longer.
Base64 decoding is the inverse process. And as one would expect, the decoded data is 3/4 as long.
While base64 encoding can encode plain text, its real benefit is encoding non-printable characters which may be interpreted by transmitting systems as control characters.
I suggest the original poster render $z as bytes with each bit having meaning to the application. Rendering non-printable characters as text typically invokes Unicode which produces glyphs based on your system's localization.
Base64decode("the answer to life the universe and everything") = 00101010
getting username in MAC terminal is easy...
I generally use whoami
in terminal...
For example, in this case, I needed that to install Tomcat Server...
There have been a few different implementations. There is a flash solution and some iframe/frame solutions for IE. Check out this
BTW: There are plenty of valid reasons to disable (or at least prevent 1 step) a back button -- look at gmail as an example which implements the hash solution discussed in the above article.
Google "how ajax broke the back button" and you'll find plenty of articles on user testing and the validity of disabling the back button.
Create a small function and use it anywhere
public SqlConnection con = "Your connection string";
public void gridviewUpdate()
{
con.Open();
string select = "SELECT * from table_name";
SqlDataAdapter da = new SqlDataAdapter(select, con);
DataSet ds = new DataSet();
da.Fill(ds, "table_name");
datagridview.DataSource = ds;
datagridview.DataMember = "table_name";
con.Close();
}
In Java 8 :
int[] arr = {1,2,3};
IntStream.of(arr).boxed().collect(Collectors.toList());
Unfortunately, no. In 2013, there is no way to do it with pure CSS.
Update: thanks to showdev for linking to the obsolete spec of CSS3 Hyperlinks, and yes, no browser has implemented it. So the answer still stands valid.
The OP is using Windows, and a much easier way to use GTest today is with vcpkg+cmake.
Install vcpkg as per https://github.com/microsoft/vcpkg , and make sure you can run vcpkg
from the cmd line. Take note of the vcpkg installation folder, eg. C:\bin\programs\vcpkg
.
Install gtest using vcpkg install gtest
: this will download, compile, and install GTest.
Use a CmakeLists.txt as below: note we can use targets instead of including folders.
cmake_minimum_required(VERSION 3.15)
project(sample CXX)
enable_testing()
find_package(GTest REQUIRED)
add_executable(test1 test.cpp source.cpp)
target_link_libraries(test1 GTest::GTest GTest::Main)
add_test(test-1 test1)
Run cmake with: (edit the vcpkg folder if necessary, and make sure the path to the vcpkg.cmake toolchain file is correct)
cmake -B build -DCMAKE_TOOLCHAIN_FILE=C:\bin\programs\vcpkg\scripts\buildsystems\vcpkg.cmake
and build using cmake --build build
as usual.
Note that, vcpkg will also copy the required gtest(d).dll/gtest(d)_main.dll from the install folder to the Debug/Release folders.
Test with cd build & ctest
.
If you wrote it like this then it would matter :
for(i=0; i<5; i=j++) {
printf("%d",i);
}
Would iterate once more than if written like this :
for(i=0; i<5; i=++j) {
printf("%d",i);
}
HtmlAgilityPack uses XPath syntax, and though many argues that it is poorly documented, I had no trouble using it with help from this XPath documentation: https://www.w3schools.com/xml/xpath_syntax.asp
To parse
<h2>
<a href="">Jack</a>
</h2>
<ul>
<li class="tel">
<a href="">81 75 53 60</a>
</li>
</ul>
<h2>
<a href="">Roy</a>
</h2>
<ul>
<li class="tel">
<a href="">44 52 16 87</a>
</li>
</ul>
I did this:
string url = "http://website.com";
var Webget = new HtmlWeb();
var doc = Webget.Load(url);
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//h2//a"))
{
names.Add(node.ChildNodes[0].InnerHtml);
}
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//li[@class='tel']//a"))
{
phones.Add(node.ChildNodes[0].InnerHtml);
}
NOTE: See @SDP's answer for a clean, built-in solution
I fixed it as follows:
make sure you include application.js before the other app dependent js files get included by changing the include order as follows:
// in application.js - make sure `require_self` comes before `require_tree .`
//= require_self
//= require_tree .
Define a global function that handles the binding in application.js
// application.js
window.onLoad = function(callback) {
// binds ready event and turbolink page:load event
$(document).ready(callback);
$(document).on('page:load',callback);
};
Now you can bind stuff like:
// in coffee script:
onLoad ->
$('a.clickable').click =>
alert('link clicked!');
// equivalent in javascript:
onLoad(function() {
$('a.clickable').click(function() {
alert('link clicked');
});
This is working for IE/Netscape/Chrome :
function ClearAuthentication(LogOffPage)
{
var IsInternetExplorer = false;
try
{
var agt=navigator.userAgent.toLowerCase();
if (agt.indexOf("msie") != -1) { IsInternetExplorer = true; }
}
catch(e)
{
IsInternetExplorer = false;
};
if (IsInternetExplorer)
{
// Logoff Internet Explorer
document.execCommand("ClearAuthenticationCache");
window.location = LogOffPage;
}
else
{
// Logoff every other browsers
$.ajax({
username: 'unknown',
password: 'WrongPassword',
url: './cgi-bin/PrimoCgi',
type: 'GET',
beforeSend: function(xhr)
{
xhr.setRequestHeader("Authorization", "Basic AAAAAAAAAAAAAAAAAAA=");
},
error: function(err)
{
window.location = LogOffPage;
}
});
}
}
$(document).ready(function ()
{
$('#Btn1').click(function ()
{
// Call Clear Authentication
ClearAuthentication("force_logout.html");
});
});
Write below code in your MainActivity.java file instead of your code.
public class MainActivity extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtn1 = (Button) findViewById(R.id.mBtn1);
mBtn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
Log.i("clicks","You Clicked B1");
Intent i=new Intent(MainActivity.this, MainActivity2.class);
startActivity(i);
}
}
And Declare MainActivity2 into your Androidmanifest.xml file using below code.
<activity
android:name=".MainActivity2"
android:label="@string/title_activity_main">
</activity>
$('.tag1, .tag2').on('click', function() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
});
or
function dothing() {
if ($(this).hasClass('clickedTag')){
// code here
} else {
// and here
}
}
$('.tag1, .tag2').on('click', dothing);
or
$('[class^=tag]').on('click', dothing);
You can implement Drag&Drop in WinForms and WPF.
You should add mousemove event:
private void YourElementControl_MouseMove(object sender, MouseEventArgs e)
{
...
if (e.Button == MouseButtons.Left)
{
DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);
}
...
}
You should add DragDrop event:
private void YourElementControl_DragDrop(object sender, DragEventArgs e)
{
...
foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))
{
File.Copy(path, DirPath + Path.GetFileName(path));
}
...
}
An answer above almost solved it for me but it does not correctly create a parsed CSV.
Here's my version:
sqlcmd -S myurl.com -d MyAzureDB -E -s, -W -i mytsql.sql | findstr /V /C:"-" /B > parsed_correctly.csv
Someone saying that sqlcmd
is outdated in favor of some PowerShell alternative is forgetting that sqlcmd
isn't just for Windows. I'm on Linux (and when on Windows I avoid PS anyway).
Having said all that, I do find bcp
easier.
You could do any of the following
Set each style property individually:
$("#voltaic_holder").css("position", "relative");
Set multiple style properties at once:
$("#voltaic_holder").css({"position":"relative", "top":"-75px"});
Remove a specific style:
$("#voltaic_holder").css({"top": ""});
// or
$("#voltaic_holder").css("top", "");
Remove the entire style attribute:
$("#voltaic_holder").removeAttr("style")
If you want to go the other way round (associate FILE* with existing file descriptor), use fdopen() :
FDOPEN(P)
NAME
fdopen - associate a stream with a file descriptor
SYNOPSIS
#include <stdio.h>
FILE *fdopen(int fildes, const char *mode);
html
<input id="something" onkeyup="key_up(this)" type="text">
script
function key_up(e){
var enterKey = 13; //Key Code for Enter Key
if (e.which == enterKey){
//Do you work here
}
}
Next time, Please try providing some code.
Since Django 1.8 released, you can use from_db classmethod to cache old value of remote_image. Then in save method you can compare old and new value of field to check if the value has changed.
@classmethod
def from_db(cls, db, field_names, values):
new = super(Alias, cls).from_db(db, field_names, values)
# cache value went from the base
new._loaded_remote_image = values[field_names.index('remote_image')]
return new
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
if (self._state.adding and self.remote_image) or \
(not self._state.adding and self._loaded_remote_image != self.remote_image):
# If it is first save and there is no cached remote_image but there is new one,
# or the value of remote_image has changed - do your stuff!
Swift 4, I have used Enum for handling UserDefaults.
This is just a sample code. You can customize it as per your requirements.
For Storing, Retrieving, Removing. In this way just add a key for your UserDefaults key to the enum. Handle values while getting and storing according to dataType and your requirements.
enum UserDefaultsConstant : String {
case AuthToken, FcmToken
static let defaults = UserDefaults.standard
//Store
func setValue(value : Any) {
switch self {
case .AuthToken,.FcmToken:
if let _ = value as? String {
UserDefaults.standard.set(value, forKey: self.rawValue)
}
break
}
UserDefaults.standard.synchronize()
}
//Retrieve
func getValue() -> Any? {
switch self {
case .AuthToken:
if(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) != nil) {
return "Bearer "+(UserDefaults.standard.value(forKey: UserDefaultsConstant.AuthToken.rawValue) as! String)
}
else {
return ""
}
case .FcmToken:
if(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) != nil) {
print(UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue))
return (UserDefaults.standard.value(forKey: UserDefaultsConstant.FcmToken.rawValue) as! String)
}
else {
return ""
}
}
}
//Remove
func removeValue() {
UserDefaults.standard.removeObject(forKey: self.rawValue)
UserDefaults.standard.synchronize()
}
}
For storing a value in userdefaults,
if let authToken = resp.data?.token {
UserDefaultsConstant.AuthToken.setValue(value: authToken)
}
For retrieving a value from userdefaults,
//As AuthToken value is a string
(UserDefaultsConstant.AuthToken.getValue() as! String)
See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Select-Object Size,FreeSpace
$disk.Size
$disk.FreeSpace
To extract the values only and assign them to a variable:
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName remotecomputer -Filter "DeviceID='C:'" |
Foreach-Object {$_.Size,$_.FreeSpace}
another solution using dplyr is:
df <- ## your data ##
df <- df %>%
mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))
This may or may not work for your purposes, but you can extend jScrollPane to fire other functionality before it does its scrolling. I've only just tested this a little bit, but I can confirm that you can jump in and prevent the scrolling entirely. All I did was:
<script type="text/javascript" src="script/jquery.jscrollpane.js"></script>
positionDragY(destY, animate)
functionFire up events.html, and you'll see a normally scrolling box which due to your coding intervention won't scroll.
You can control the entire browser's scrollbars this way (see fullpage_scroll.html).
So, presumably the next step is to add a call to some other function that goes off and does your anchoring magic, then decides whether to continue with the scroll or not. You've also got API calls to set scrollTop and scrollLeft.
If you want more help, post where you get up to!
Hope this has helped.
@ModelAttribute
refers to a property of the Model object (the M in MVC ;)
so let's say we have a form with a form backing object that is called "Person"
Then you can have Spring MVC supply this object to a Controller method by using the @ModelAttribute
annotation:
public String processForm(@ModelAttribute("person") Person person){
person.getStuff();
}
On the other hand the annotation is used to define objects which should be part of a Model. So if you want to have a Person object referenced in the Model you can use the following method:
@ModelAttribute("person")
public Person getPerson(){
return new Person();
}
This annotated method will allow access to the Person object in your View, since it gets automatically added to the Models by Spring.
I want to display .jpg image in an Qt UI
The simpliest way is to use QLabel for this:
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
QLabel label("<img src='image.jpg' />");
label.show();
return a.exec();
}
You can bind the json to a POJO using MappingJacksonHttpMessageConverter
. Thus your controller signature can read :-
public ResponseEntity<Boolean> saveData(@RequestBody RequestDTO req)
Where RequestDTO needs to be a bean appropriately annotated to work with jackson serializing/deserializing. Your *-servlet.xml file should have the Jackson message converter registered in RequestMappingHandler as follows :-
<list >
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
Use This And Call This In OnCreate Method In Which Activity You Want
public void popupMessage(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("No Internet Connection. Check Your Wifi Or enter code hereMobile Data.");
alertDialogBuilder.setIcon(R.drawable.ic_no_internet);
alertDialogBuilder.setTitle("Connection Failed");
alertDialogBuilder.setNegativeButton("ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d("internet","Ok btn pressed");
finishAffinity();
System.exit(0);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
There is no quick function access to getting/setting cookies, so I came up with the following hack:
var http = require('http');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var cookies = parseCookies(request);
// To Write a Cookie
response.writeHead(200, {
'Set-Cookie': 'mycookie=test',
'Content-Type': 'text/plain'
});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
This will store all cookies into the cookies object, and you need to set cookies when you write the head.
Be aware that a value of 1 equals 100% in Excel's interpretation. If you enter 5.66 and you want to show 5.66%, then AxGryndr's hack with the formatting will work, but it is a display format only and does not represent the true numeric value. If you want to use that percentage in further calculations, these calculations will return the wrong result unless you divide by 100 at calculation time.
The consistent and less error-prone way is to enter 0.0566 and format the number with the built-in percentage format. That way, you can easily calculate 5.6% of A1 by just multiplying A1 with the value.
The good news is that you don't need to go through the rigmarole of entering 0.0566 and then formatting as percent. You can simply type
5.66%
into the cell, including the percentage symbol, and Excel will take care of the rest and store the number correctly as 0.0566 if formatted as General.
This issue maybe due to common user do not have privilege to access packages py file.
1. root user can run 'pip list'
2. other common user cannot run 'pip list'
[~]$ pip list
Traceback (most recent call last):
File "/usr/bin/pip", line 7, in <module>
from pip._internal import main
ImportError: No module named pip._internal
Check pip py file privilege.
[root@]# ll /usr/lib/python2.7/site-packages/pip/
?? 24
-rw------- 1 root root 24 6? 7 16:57 __init__.py
-rw------- 1 root root 163 6? 7 16:57 __init__.pyc
-rw------- 1 root root 629 6? 7 16:57 __main__.py
-rw------- 1 root root 510 6? 7 16:57 __main__.pyc
drwx------ 8 root root 4096 6? 7 16:57 _internal
drwx------ 18 root root 4096 6? 7 16:57 _vendor
solution : root user login and run
chmod -R 755 /usr/lib/python2.7
fix this issue.
when a developer use an initializer block, the Java Compiler copies the initializer into each constructor of the current class.
Example:
the following code:
class MyClass {
private int myField = 3;
{
myField = myField + 2;
//myField is worth 5 for all instance
}
public MyClass() {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
is equivalent to:
class MyClass {
private int myField = 3;
public MyClass() {
myField = myField + 2;
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
}
public MyClass(int _myParam) {
myField = myField + 2;
if (_myParam > 0) {
myField = myField * 4;
//myField is worth 20 for all instance initialized with this construtor
//if _myParam is greater than 0
} else {
myField = myField + 5;
//myField is worth 10 for all instance initialized with this construtor
//if _myParam is lower than 0 or if _myParam is worth 0
}
}
public void setMyField(int _myField) {
myField = _myField;
}
public int getMyField() {
return myField;
}
}
public class MainClass{
public static void main(String[] args) {
MyClass myFirstInstance_ = new MyClass();
System.out.println(myFirstInstance_.getMyField());//20
MyClass mySecondInstance_ = new MyClass(1);
System.out.println(mySecondInstance_.getMyField());//20
MyClass myThirdInstance_ = new MyClass(-1);
System.out.println(myThirdInstance_.getMyField());//10
}
}
I hope my example is understood by developers.
This is not answering the problem but if anyone comes to this question when they stumble upon this exception of no suitable message converter found, here is my problem and solution.
In Spring 4.0.9, we were able to send this
JSONObject jsonCredential = new JSONObject();
jsonCredential.put(APPLICATION_CREDENTIALS, data);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
ResponseEntity<String> res = restTemplate.exchange(myRestUrl), HttpMethod.POST,request, String.class);
In Spring 4.3.5 release, we starting seeing errors with the message that converter was not found.
The way Convertors work is that if you have it in your classpath, they get registered.
Jackson-asl was still in classpath but was not being recognized by spring. We replaced Jackson-asl with faster-xml jackson core.
Once we added I could see the converter being registered.
The description of the getString() method says the following:
the column value; if the value is SQL NULL, the value returned is null
That means your problem is not that the String value is null, rather some other object is, perhaps your ResultSet or maybe you closed the connection or something like this. Provide the stack trace, that would help.
the same solution as Basit .. but the version 3.0 doesn't work for me try this .. it works for me to integrate struts 2.x
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>blabla</display-name>
...
</web-app>
Due to having some downtime at work, I decided to test the speeds of the different methods posted here.
These are the four methods I used.
static void Print1(string[] toPrint)
{
foreach(string s in toPrint)
{
Console.Write(s);
}
}
static void Print2(string[] toPrint)
{
toPrint.ToList().ForEach(Console.Write);
}
static void Print3(string[] toPrint)
{
Console.WriteLine(string.Join("", toPrint));
}
static void Print4(string[] toPrint)
{
Array.ForEach(toPrint, Console.Write);
}
The results are as follows:
Strings per trial: 10000
Number of Trials: 100
Total Time Taken to complete: 00:01:20.5004836
Print1 Average: 484.37ms
Print2 Average: 246.29ms
Print3 Average: 70.57ms
Print4 Average: 233.81ms
So Print3 is the fastest, because it only has one call to the Console.WriteLine
which seems to be the main bottleneck for the speed of printing out an array. Print4 is slightly faster than Print2 and Print1 is the slowest of them all.
I think that Print4 is probably the most versatile of the 4 I tested, even though Print3 is faster.
If I made any errors, feel free to let me know / fix them on your own!
EDIT: I'm adding the generated IL below
g__Print10_0://Print1
IL_0000: ldarg.0
IL_0001: stloc.0
IL_0002: ldc.i4.0
IL_0003: stloc.1
IL_0004: br.s IL_0012
IL_0006: ldloc.0
IL_0007: ldloc.1
IL_0008: ldelem.ref
IL_0009: call System.Console.Write
IL_000E: ldloc.1
IL_000F: ldc.i4.1
IL_0010: add
IL_0011: stloc.1
IL_0012: ldloc.1
IL_0013: ldloc.0
IL_0014: ldlen
IL_0015: conv.i4
IL_0016: blt.s IL_0006
IL_0018: ret
g__Print20_1://Print2
IL_0000: ldarg.0
IL_0001: call System.Linq.Enumerable.ToList<String>
IL_0006: ldnull
IL_0007: ldftn System.Console.Write
IL_000D: newobj System.Action<System.String>..ctor
IL_0012: callvirt System.Collections.Generic.List<System.String>.ForEach
IL_0017: ret
g__Print30_2://Print3
IL_0000: ldstr ""
IL_0005: ldarg.0
IL_0006: call System.String.Join
IL_000B: call System.Console.WriteLine
IL_0010: ret
g__Print40_3://Print4
IL_0000: ldarg.0
IL_0001: ldnull
IL_0002: ldftn System.Console.Write
IL_0008: newobj System.Action<System.String>..ctor
IL_000D: call System.Array.ForEach<String>
IL_0012: ret
You can use boost::posix_time::time_duration
to get the time range. E.g like this
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock
, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock
has milisecond resolution, not microsecond.
An example which is a little dependent on the hardware.
int main(int argc, char* argv[])
{
boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
boost::posix_time::time_duration diff = t2 - t1;
std::cout << diff.total_milliseconds() << std::endl;
boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration msdiff = mst2 - mst1;
std::cout << msdiff.total_milliseconds() << std::endl;
return 0;
}
On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.
p = {1,2,3} is wrong.
You can never use this:
int * p;
p = {1,2,3};
loop is right
int *p,i;
p = malloc(3*sizeof(int));
for(i = 0; i<3; ++i)
p[i] = i;
I use this:
@var.respond_to?(:keys)
It works for Hash and ActiveSupport::HashWithIndifferentAccess.
Using the form designer:
You can set also the tool tip programatically using the following call:
this.toolTip1.SetToolTip(this.targetControl, "My Tool Tip");
for mysql 'text':
@Column(columnDefinition = "TEXT")
private String description;
for mysql 'longtext':
@Lob
private String description;
add the following section and change :
Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all
change directory to your directory path like c:\wamp\www\projectfolder
make sure you make the same in httpd.conf for all directory like first directory:
Options Indexes FollowSymLinks AllowOverride All Order allow,deny Allow from all
second directory:
<Directory "c:/wamp/www/">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.0/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride all
#
# Controls who can get stuff from this server.
#
# onlineoffline tag - don't remove
Order Deny,Allow
Allow from all
</Directory>
<Directory "icons">
Options Indexes MultiViews
AllowOverride None
Order allow,deny
Allow from all
</Directory>
In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:
selectedIndex = 1 // Displays 2nd tab. The index starts from 0.
In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
if segue.identifier == "SegueToYourTabBarController" {
if let destVC = segue.destination as? YourTabBarController {
destVC.selectedIndex = 0
}
}
I am using this way of setting tab with Xcode 10 and Swift 4.2.
Read this thread R - boolean operators && and ||.
Basically, the &
is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. &&
is not, returning a single logical.
Replace your domain with domainname.com
, it's working with me .
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domainname\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.domainname.com/$1 [R,L]
Just a clarification on the answer given by Bkkbrad.
I tried this suggestion and it did not work for me.
For example,
split('aa|bb','\\|')
produced:
["","a","a","|","b","b",""]
But,
split('aa|bb','[|]')
produced the desired result:
["aa","bb"]
Including the metacharacter '|' inside the square brackets causes it to be interpreted literally, as intended, rather than as a metacharacter.
For elaboration of this behaviour of regexp, see: http://www.regular-expressions.info/charclass.html
Here's how I solved it, with nullable double extension method.
public static bool NearlyEquals(this double? value1, double? value2, double unimportantDifference = 0.0001)
{
if (value1 != value2)
{
if(value1 == null || value2 == null)
return false;
return Math.Abs(value1.Value - value2.Value) < unimportantDifference;
}
return true;
}
...
double? value1 = 100;
value1.NearlyEquals(100.01); // will return false
value1.NearlyEquals(100.000001); // will return true
value1.NearlyEquals(100.01, 0.1); // will return true
This is a variant of the list comprehension answer given by @psun.
By switching the output value, you can actually extract the matching pattern from the list comprehension (something not possible with the any()
approach by @Lauritz-v-Thaulow)
extensionsToCheck = ['.pdf', '.doc', '.xls']
url_string = 'http://.../foo.doc'
print [extension for extension in extensionsToCheck if(extension in url_string)]
['.doc']`
You can furthermore insert a regular expression if you want to collect additional information once the matched pattern is known (this could be useful when the list of allowed patterns is too long to write into a single regex pattern)
print [re.search(r'(\w+)'+extension, url_string).group(0) for extension in extensionsToCheck if(extension in url_string)]
['foo.doc']
If it is a local file, you have to wrap it in htmlspecialchars like so:
$myfile = htmlspecialchars(file_get_contents($file_name));
Then it works
For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:
"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<sheets>
<sheet name="MySheet1" sheetId="1" r:id="rId1" />
<sheet name="MySheet2" sheetId="2" r:id="rId2" />
</sheets>
</workbook>
The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.
<?xml version="1.0" encoding="UTF-8" ?>
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
<sheetData>
<row r="1">
<c r="A1">
<v>100</v>
</c>
</row>
</sheetData>
</worksheet>
"
Detection of cell encodings:
This worked for me (I am using Postgres) in Groovy:
@RestResource(path="namespaceAndNameAndRawStateContainsMostRecentVersion", rel="namespaceAndNameAndRawStateContainsMostRecentVersion")
@Query(nativeQuery=true,
countQuery="""
SELECT COUNT(1)
FROM
(
SELECT
ROW_NUMBER() OVER (
PARTITION BY name, provider_id, state
ORDER BY version DESC) version_partition,
*
FROM mydb.mytable
WHERE
(name ILIKE ('%' || :name || '%') OR (:name = '')) AND
(namespace ILIKE ('%' || :namespace || '%') OR (:namespace = '')) AND
(state = :state OR (:state = ''))
) t
WHERE version_partition = 1
""",
value="""
SELECT id, version, state, name, internal_name, namespace, provider_id, config, create_date, update_date
FROM
(
SELECT
ROW_NUMBER() OVER (
PARTITION BY name, provider_id, state
ORDER BY version DESC) version_partition,
*
FROM mydb.mytable
WHERE
(name ILIKE ('%' || :name || '%') OR (:name = '')) AND
(namespace ILIKE ('%' || :namespace || '%') OR (:namespace = '')) AND
(state = :state OR (:state = ''))
) t
WHERE version_partition = 1
/*#{#pageable}*/
""")
public Page<Entity> findByNamespaceContainsAndNameContainsAndRawStateContainsMostRecentVersion(@Param("namespace")String namespace, @Param("name")String name, @Param("state")String state, Pageable pageable)
The key here was to use: /*#{#pageable}*/
It allows me to do sorting and pagination. You can test it by using something like this: http://localhost:8080/api/v1/entities/search/namespaceAndNameAndRawStateContainsMostRecentVersion?namespace=&name=&state=published&page=0&size=3&sort=name,desc
Watch out for this issue: Spring Pageable does not translate @Column name
You can also assign a new value to a tf.Variable
without adding an operation to the graph: tf.Variable.load(value, session)
. This function can also save you adding placeholders when assigning a value from outside the graph and it is useful in case the graph is finalized.
import tensorflow as tf
x = tf.Variable(0)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(x)) # Prints 0.
x.load(1, sess)
print(sess.run(x)) # Prints 1.
Update: This is depricated in TF2 as eager execution is default and graphs are no longer exposed in the user-facing API.
The ObjectiveC equivalent is:
myView.translatesAutoresizingMaskIntoConstraints = NO;
[[myView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor] setActive:YES];
[[myView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor] setActive:YES];
Sed has up to nine remembered patterns but you need to use escaped parentheses to remember portions of the regular expression.
See here for examples and more detail
Simply use
var xmlString = '<?xml version="1.0" ?><root />';
var xml = jQuery.parseXML(xml);
It's jQuery.parseXML, so no need to worry about cross-browser tricks. Use jQuery as like HTML, it's using the native XML engine.
This is a nice example: The Repository Pattern Example in C#
Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:
runscript
from django-extensions
python manage.py runscript scripty.py
A sample script.py
to test it out:
from django.contrib.auth.models import User
print(User.objects.values())
Mentioned at: http://django-extensions.readthedocs.io/en/latest/command_extensions.html and documented at:
python manage.py runscript --help
Tested on Django 1.9.6, django-extensions 1.6.7.
To add to what the others are saying, A and B can be function calls as well that return boolean values. If A returns false then B would never be called.
if (A() && B()) {
// if A() returns false then B() is never called...
}
The main reason why the error has been generated is because there is already an existing value of 1
for the column ID
in which you define it as PRIMARY KEY
(values are unique) in the table you are inserting.
Why not set the column ID
as AUTO_INCREMENT
?
CREATE TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
`ID` INT(11) NOT NULL AUTO_INCREMENT,
`viale` VARCHAR(45) NULL ,
.....
and when you are inserting record, you can now skip the column ID
INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...)
VALUES ('Viale Cogel ', '120', ...)
Have you tried using the DataTable.Select(filterExpression, sortExpression) method?
JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.
var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
//red
textBox.style.backgroundColor = "#FF0000";
}
else
{
//green
textBox.style.backgroundColor = "#00FF00";
}
The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application
<script type="text/javascript">
var options={
format: 'mm/dd/yyyy',
todayHighlight: true,
autoclose: true,
};
$('#datetimepicker').datepicker(options);
</script>
Consider the following link to minify Javascript/CSS files: https://github.com/mrclay/minify
Tell Apache to deliver HTML with GZip - this generally reduces the response size by about 70%. (If you use Apache, the module configuring gzip depends on your version: Apache 1.3 uses mod_gzip while Apache 2.x uses mod_deflate.)
Accept-Encoding: gzip, deflate
Content-Encoding: gzip
Use the following snippet to remove white-spaces from the HTML with the help ob_start's buffer:
<?php
function sanitize_output($buffer) {
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\</s', // strip whitespaces before tags, except space
'/(\s)+/s', // shorten multiple whitespace sequences
'/<!--(.|\s)*?-->/' // Remove HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
ob_start("sanitize_output");
?>
Data view is good Feature of data table . We can filter the data table as per our requirements using data view . Below Functions is After binding data table to list box data source then filter by text box control . ( this condition you can change as per your needs .Contains(txtSearch.Text.Trim()) )
Private Sub BindClients()
okcl = 0
sql = "Select * from Client Order By cname"
Dim dacli As New SqlClient.SqlDataAdapter
Dim cmd As New SqlClient.SqlCommand()
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
dacli.SelectCommand = cmd
dacli.SelectCommand.Connection = Me.sqlcn
Dim dtcli As New DataTable
dacli.Fill(dtcli)
dacli.Fill(dataTableClients)
lstboxc.DataSource = dataTableClients
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dtcli.Rows.Count > 0 Then
ccode = dtcli.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
Private Sub FilterClients()
Dim query As EnumerableRowCollection(Of DataRow) = From dataTableClients In
dataTableClients.AsEnumerable() Where dataTableClients.Field(Of String)
("cname").Contains(txtSearch.Text.Trim()) Order By dataTableClients.Field(Of
String)("cname") Select dataTableClients
Dim dataView As DataView = query.AsDataView()
lstboxc.DataSource = dataView
lstboxc.DisplayMember = "cname"
lstboxc.ValueMember = "ccode"
okcl = 1
If dataTableClients.Rows.Count > 0 Then
ccode = dataTableClients.Rows(0)("ccode")
Call ClientDispData1()
End If
End Sub
In Python we can use the __str__()
method.
We can override it in our class like this:
class User:
firstName = ''
lastName = ''
...
def __str__(self):
return self.firstName + " " + self.lastName
and when running
print(user)
it will call the function __str__(self)
and print the firstName and lastName
If you want to compare to a string literal you need to put it in (single) quotes:
<xsl:if test="Count != 'N/A'">
Don't use grep. Download Silver Searcher or ripgrep. They're both outstanding, and way faster than grep or ack with tons of options.
Equals comparison:
((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))
Not Equal To comparison: Just negate the Equals comparison above.
NOT ((f1 IS NULL AND f2 IS NULL) OR (f1 IS NOT NULL AND f2 IS NOT NULL AND f1 = f2))
Is it verbose? Yes, it is. However it's efficient since it doesn't call any function. The idea is to use short circuit in predicates to make sure the equal operator (=) is used only with non-null values, otherwise null would propagate up in the expression tree.
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
Also check that your server isn't setting secure cookies on a non http request. Just found out that my ajax request was getting a php session with "secure" set. Because I was not on https it was not sending back the session cookie and my session was getting reset on each ajax request.
Keep in mind that a PDOStatement
is Traversable
. Given a query:
$query = $dbh->query('
SELECT
*
FROM
test
');
It can be iterated over:
$it = new IteratorIterator($query);
echo '<p>', iterator_count($it), ' items</p>';
// Have to run the query again unfortunately
$query->execute();
foreach ($query as $row) {
echo '<p>', $row['title'], '</p>';
}
Or you can do something like this:
$it = new IteratorIterator($query);
$it->rewind();
if ($it->valid()) {
do {
$row = $it->current();
echo '<p>', $row['title'], '</p>';
$it->next();
} while ($it->valid());
} else {
echo '<p>No results</p>';
}
Mine was completely different with Spring Boot! For me it was not due to setting collection property.
In my tests I was trying to create an entity and was getting this error for another collection that was unused!
After so much trying I just added a @Transactional
on the test method and it solved it. Don't no the reason though.
If you came here (just like me) to find the solution for integer value, here is the answer:
CAST(9/2 AS UNSIGNED)
returns 5
So this is the way I had to do it because i still wanted a JavaScript date object to manipulate as a date and unfortunantly alot of these answers require you to go to a string.
//First i had a string called stringDateVar that i needed to convert to Date
var newDate = new Date(stringDateVar)
//output: 2019-01-07T04:00:00.000Z
//I needed it 2019-01-07T00:00:00.000Z because i had other logic that was dependent on that
var correctDate = new Date(newDate.setUTCHours(0))
//This will output 2019-01-07T00:00:00.000Z on everything which allows scalability
Read it in by row and then transpose it in the command line. If you're using Unix, install csvtool and follow the directions in: https://unix.stackexchange.com/a/314482/186237
I was facing the same issue, I resolved this by replacing dependencies in App level Build.gradle file
"""
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'androidx.multidex:multidex:2.0.0'
testImplementation 'junit:junit:4.12'
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
BY
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation platform('com.google.firebase:firebase-bom:26.1.1')
implementation 'com.google.firebase:firebase-analytics'
implementation 'androidx.multidex:multidex:2.0.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.androidx.support.test:runner:1.1.0'
androidTestImplementation 'com.androidx.support.test.espresso:espresso-core:3.1.0'
This resolves my issue.
Well, no answers but at least one more test to make. Open Terminal and run this command: "ps-Ael | grep Z". If you get two entries, one "(clang)" and the other your app or company name, you're hosed - reboot.
If you are a developer, enter a short bug and tell Apple how absolutely annoying having to reboot is, and mention they can dup this bug to "rdar://10401934" which I just entered.
David
Add the following style in your res/values/styles.xml
file (if you don’t have one, create it.) Here’s a complete file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.Transparent" parent="android:Theme">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowIsFloating">true</item>
<item name="android:backgroundDimEnabled">false</item>
</style>
</resources>
(The value @color/transparent
is the color value #00000000
which I put in the res/values/color.xml
file. You can also use @android:color/transparent
in later Android versions.)
Then apply the style to your activity, for example:
<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
...
</activity>
http://www.useragentstring.com/
Visit that page, it'll give you a good explanation of each element of your user agent.
Mozilla:
MozillaProductSlice. Claims to be a Mozilla based user agent, which is only true for Gecko browsers like Firefox and Netscape. For all other user agents it means 'Mozilla-compatible'. In modern browsers, this is only used for historical reasons. It has no real meaning anymore
I wanted to replicate Unix/Linux's cp -r
as closely as possible. I came up with the following:
xcopy /e /k /h /i srcdir destdir
Flag explanation:
/e
Copies directories and subdirectories, including empty ones.
/k
Copies attributes. Normal Xcopy will reset read-only attributes.
/h
Copies hidden and system files also.
/i
If destination does not exist and copying more than one file, assume destination is a directory.
I made the following into a batch file (cpr.bat
) so that I didn't have to remember the flags:
xcopy /e /k /h /i %*
Usage: cpr srcdir destdir
You might also want to use the following flags, but I didn't:
/q
Quiet. Do not display file names while copying.
/b
Copies the Symbolic Link itself versus the target of the link. (requires UAC admin)
/o
Copies directory and file ACLs. (requires UAC admin)
You can squash (join) commits with an Interactive Rebase. There is a pretty nice YouTube video which shows how to do this on the command line or with SmartGit:
If you are already a SmartGit user then you can select all your outgoing commits (by holding down the Ctrl key) and open the context menu (right click) to squash your commits.
It's very comfortable:
There is also a very nice tutorial from Atlassian which shows how it works:
Statements represent an action or command e.g print statements, assignment statements.
print 'hello', x = 1
Expression is a combination of variables, operations and values that yields a result value.
5 * 5 # yields 25
Lastly, expression statements
print 5*5
There are a set of available properties to all Maven projects.
From Introduction to the POM:
project.basedir
: The directory that the current project resides in.
This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml
file. If your POM is located inside /path/to/project/pom.xml
then this property will evaluate to /path/to/project
.
Some properties are also inherited from the Super POM, which is the case for project.build.directory
. It is the value inside the <project><build><directory>
element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory
, it is:
The directory where all files generated by the build are placed. The default value is
target
.
This is the directory that will hold every generated file by the build.
public static String cap1stChar(String userIdea)
{
char[] stringArray = userIdea.toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
return userIdea = new String(stringArray);
}
timer.cancel(); //Terminates this timer,discarding any currently scheduled tasks.
timer.purge(); // Removes all cancelled tasks from this timer's task queue.
<form>
<label for="company">
<span>Company Name</span>
<input type="text" id="company" />
</label>
<label for="contact">
<span>Contact Name</span>
<input type="text" id="contact" />
</label>
</form>
label { width: 200px; float: left; margin: 0 20px 0 0; }
span { display: block; margin: 0 0 3px; font-size: 1.2em; font-weight: bold; }
input { width: 200px; border: 1px solid #000; padding: 5px; }
Illustrated at http://jsfiddle.net/H3y8j/
The session is a server side thing, you cannot access it using jQuery.
You can write an Http handler (that will share the sessionid if any) and return the value from there using $.ajax
.
Try re-installing the packages.
In the NuGet Package Manager Console enter the following command:
Update-Package -Reinstall -ProjectName Your.Project.Name
If you want to re-install packages and restore references for the whole solution omit the -ProjectName
parameter.
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
Try this:
$("#myselect :selected").text();
For an ASP.NET dropdown you can use the following selector:
$("[id*='MyDropDownId'] :selected")
I thought it might be worth submitting a counter-example to the general consensus on this page that "instanceof" is not expensive enough to worry about. I found I had some code in an inner loop that (in some historic attempt at optimization) did
if (!(seq instanceof SingleItem)) {
seq = seq.head();
}
where calling head() on a SingleItem returns the value unchanged. Replacing the code by
seq = seq.head();
gives me a speed-up from 269ms to 169ms, despite the fact that there are some quite heavy things happening in the loop, like string-to-double conversion. It's possible of course that the speed-up is more due to eliminating the conditional branch than to eliminating the instanceof operator itself; but I thought it worth mentioning.
commons-logging-1.1.1.jar or jcl-over-slf4j-1.7.6.jar al
If you are using maven, use the below code.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${slf4j.version}</version>
</dependency>
The second pipe was interpreted by this web site when submitted... You need two backslashes at the beginning. So make sure to use System.IO.Directory.GetFiles(@"\\.\pipe\").
Note that I have seen this function call throw an 'illegal characters in path.' exception when one of the pipes on my machine had invalid characters. PipleList.exe worked ok though, so it seems like a bug in MS's .net code.
All you need to do instal install package libxml2-dev for example:
sudo apt-get install libxml2-dev
On CentOS/RHEL:
sudo yum install libxml2-devel
Cory is correct
@ If you're using Eclipse PDT, this is done by opening up the PHP explorer view
I just spent about half an hour looking for the little arrow, until I actually looked up what the 'PHP Explorer' view is. Here is a screenshot:
In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int
if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.
To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-*
flags if possible.
Instead of stdlib.h, you should try:
#include <string.h>
That's where strcpy
and strncpy
are defined, at least according to the strcpy
(2) man page.
The exit
function is defined in stdlib.h, though, so I don't know what's going on there.
I ran into the same issue but the accepted solution did not work for me. Instead the solution was to modify the framework's install name.
The error in the original post is:
dyld: Library not loaded: /Library/Frameworks/TestMacFramework.framework/Versions/A/TestMacFramework
Referenced from: /Users/samharman/Library/Developer/Xcode/DerivedData/TestMacContainer-dzabuelobzfknafuhmgooqhqrgzl/Build/Products/Debug/TestMacContainer.app/Contents/MacOS/TestMacContainer
Reason: image not found
Note the first path after Library not loaded. The framework is being loaded from an absolute path. This path comes from the framework's install name (sometimes called rpath), which can be examined using:
otool -D MyFramework.framework/MyFramework
When a framework is embedded into an app this path should be relative and of this form: @rpath/MyFramework.framework/MyFramework. If your framework's install name is an absolute path it may not be loaded at runtime and an error similar to the one above will be produced.
The solution is to modify the install name:
install_name_tool -id "@rpath/MyFramework.framework/MyFramework" MyFramework.framework/MyFramework
With this change I no longer get the error
If you want to use it as a date instead of a varchar
again afterwards, don't forget to convert it back:
select convert(datetime,CONVERT(char(10), GetDate(),126))
Descending order using underscore can be done by multiplying the return value by -1.
//Ascending Order:
_.sortBy([2, 3, 1], function(num){
return num;
}); // [1, 2, 3]
//Descending Order:
_.sortBy([2, 3, 1], function(num){
return num * -1;
}); // [3, 2, 1]
If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.
//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){
return s.charCodeAt() * -1;
});
For JavaScript the best and simplest answer would seem to be /.\*/
.
As suggested by others /(.*?)/
would work as well but /.\*/
is simpler. The ()
inside the pattern are not needed, as far as I can see nor the ending ?
to match absolutely anything (including empty strings)
NON-SOLUTIONS:
/[\s\S]/
does NOT match empty strings so it's not the solution.
/[\s\S]\*/
DOES match also empty strings. But it has a problem: If you use it in your code then you can't comment out such code because the */
is interpreted as end-of-comment.
/([\s\S]\*)/
works and does not have the comment-problem. But it is longer and more complicated to understand than /.*/
.
change dependencies from compile to Implementation in build.gradle file
How to import a commons-library into netbeans.
Evaluate the error message in NetBeans:
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass()
and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.
To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.
You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging
. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.
You're going to want to download the commons-logging-1.1.3-bin.zip
or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.
Download that zip. Unzip it. Search around for things that end in .jar
. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.
The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.
This one is easy to use on the terminal:
$ echo '1\n2\n3\n' | while read -r; do echo $REPLY; done
1
2
3
For retrieving the path you can use a function <?php $path = get_home_path(); ?>
. I do not want to just repeat what had been already said here, but I want to add one more thing:
If you are using windows server, which is rare case for WordPress installation, but still happens sometimes, you might face a problem with the path output. It might miss a "\" somewhere and you will get an error if you will be using such a path. So when outputting make sure to sanitize the path:
<?php
$path = get_home_path();
$path = wp_normalize_path ($path);
// now $path is ready to be used :)
?>
Create a new 640x480 image and fill it with purple (red+blue):
cv::Mat mat(480, 640, CV_8UC3, cv::Scalar(255,0,255));
Note:
For Pip 8.1.2 you can use pip download -r requ.txt
to download packages to your local machine.
You can use the MultilineLabel component in the Jide Open Source Components.
Div tags are easy to spot for me. Just download the file, scan it or so with netbeans, then continue debugging it. Or you can use the Google chrome developer kit, and view the page source. I'm a bit of a weird developer, I don't always use the "best" stuff. But it works for me.
I'll link you with some developer stuff I use
http://www.coffeecup.com/free-editor/
Those are just a few of the good ones out there. I'm open to more suggestions to this list :D
Happy programming
-skycoder
METHOD 1 ( Recommanded )
Library YouTubeExtractor
Add into your gradle file
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
And dependencies
compile 'com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
Add this small code and you done. Demo HERE
public class MainActivity extends AppCompatActivity {
private static final String YOUTUBE_ID = "ea4-5mrpGfE";
private final YouTubeExtractor mExtractor = YouTubeExtractor.create();
private Callback<YouTubeExtractionResult> mExtractionCallback = new Callback<YouTubeExtractionResult>() {
@Override
public void onResponse(Call<YouTubeExtractionResult> call, Response<YouTubeExtractionResult> response) {
bindVideoResult(response.body());
}
@Override
public void onFailure(Call<YouTubeExtractionResult> call, Throwable t) {
onError(t);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// For android youtube extractor library com.github.Commit451.YouTubeExtractor:youtubeextractor:2.1.0'
mExtractor.extract(YOUTUBE_ID).enqueue(mExtractionCallback);
}
private void onError(Throwable t) {
t.printStackTrace();
Toast.makeText(MainActivity.this, "It failed to extract. So sad", Toast.LENGTH_SHORT).show();
}
private void bindVideoResult(YouTubeExtractionResult result) {
// Here you can get download url link
Log.d("OnSuccess", "Got a result with the best url: " + result.getBestAvailableQualityVideoUri());
Toast.makeText(this, "result : " + result.getSd360VideoUri(), Toast.LENGTH_SHORT).show();
}
}
You can get download link in bindVideoResult() method.
METHOD 2
Using this library android-youtubeExtractor
Add into gradle file
repositories {
maven { url "https://jitpack.io" }
}
compile 'com.github.HaarigerHarald:android-youtubeExtractor:master-SNAPSHOT'
Here is the code for getting download url.
String youtubeLink = "http://youtube.com/watch?v=xxxx";
YouTubeUriExtractor ytEx = new YouTubeUriExtractor(this) {
@Override
public void onUrisAvailable(String videoId, String videoTitle, SparseArray<YtFile> ytFiles) {
if (ytFiles != null) {
int itag = 22;
// Here you can get download url
String downloadUrl = ytFiles.get(itag).getUrl();
}
}
};
ytEx.execute(youtubeLink);
It is worked for me
table {
width: 100%;
table-layout: fixed;
}
td {
text-overflow: ellipsis;
white-space: nowrap;
}
check it
const mq = window.matchMedia( "(min-width: 500px)" );
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
You can combine attribute selectors this way:
$("[attr1=val][attr2=val]")...
so that an element has to satisfy both conditions. Of course you can use this for more than two. Also, don't do [type=checkbox]
. jQuery has a selector for that, namely :checkbox
so the end result is:
$("input:checkbox[name=ProductCode]")...
Attribute selectors are slow however so the recommended approach is to use ID and class selectors where possible. You could change your markup to:
<input type="checkbox" class="ProductCode" name="ProductCode"value="396P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="401P4">
<input type="checkbox" class="ProductCode" name="ProductCode"value="F460129">
allowing you to use the much faster selector of:
$("input.ProductCode")...
Using @Dan 's approach, you can create JOINs. Just use a different @variable for each sub query.
SELECT current_row.row, current_row.id, previous_row.row, previous_row.id
FROM (
SELECT @rownum:=@rownum+1 row, a.*
FROM articles a, (SELECT @rownum:=0) r
ORDER BY date, id
) as current_row
LEFT JOIN (
SELECT @rownum2:=@rownum2+1 row, a.*
FROM articles a, (SELECT @rownum2:=0) r
ORDER BY date, id
) as previous_row ON
(current_row.id = previous_row.id) AND (current_row.row = previous_row.row - 1)
You can choose the number of clusters by visually inspecting your data points, but you will soon realize that there is a lot of ambiguity in this process for all except the simplest data sets. This is not always bad, because you are doing unsupervised learning and there's some inherent subjectivity in the labeling process. Here, having previous experience with that particular problem or something similar will help you choose the right value.
If you want some hint about the number of clusters that you should use, you can apply the Elbow method:
First of all, compute the sum of squared error (SSE) for some values of k (for example 2, 4, 6, 8, etc.). The SSE is defined as the sum of the squared distance between each member of the cluster and its centroid. Mathematically:
SSE=?Ki=1?x?cidist(x,ci)2
If you plot k against the SSE, you will see that the error decreases as k gets larger; this is because when the number of clusters increases, they should be smaller, so distortion is also smaller. The idea of the elbow method is to choose the k at which the SSE decreases abruptly. This produces an "elbow effect" in the graph, as you can see in the following picture:
In this case, k=6 is the value that the Elbow method has selected. Take into account that the Elbow method is an heuristic and, as such, it may or may not work well in your particular case. Sometimes, there are more than one elbow, or no elbow at all. In those situations you usually end up calculating the best k by evaluating how well k-means performs in the context of the particular clustering problem you are trying to solve.
First thing that comes into my mind:
read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"
output is, unsurprisingly
1|2|3
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
I tried majority of the solutions provided in this answer blog, however none of them worked, I had this ssl certificant error
as I try to install python packages.
I succeed by following command:
python -m pip install PACKAGENAME --trusted-host=pypi.python.org --trusted-host=pypi.org --trusted-host=files.pythonhosted.org
You could create a trigger to delete the referenced rows in before deleting the job.
DELIMITER $$
CREATE TRIGGER before_jobs_delete
BEFORE DELETE ON jobs
FOR EACH ROW
BEGIN
delete from advertisers where advertiser_id=OLD.advertiser_id;
END$$
DELIMITER ;
You're on the right track. Now you just need to extract the desired group, as follows:
final Pattern pattern = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
final Matcher matcher = pattern.matcher("<tag>String I want to extract</tag>");
matcher.find();
System.out.println(matcher.group(1)); // Prints String I want to extract
If you want to extract multiple hits, try this:
public static void main(String[] args) {
final String str = "<tag>apple</tag><b>hello</b><tag>orange</tag><tag>pear</tag>";
System.out.println(Arrays.toString(getTagValues(str).toArray())); // Prints [apple, orange, pear]
}
private static final Pattern TAG_REGEX = Pattern.compile("<tag>(.+?)</tag>", Pattern.DOTALL);
private static List<String> getTagValues(final String str) {
final List<String> tagValues = new ArrayList<String>();
final Matcher matcher = TAG_REGEX.matcher(str);
while (matcher.find()) {
tagValues.add(matcher.group(1));
}
return tagValues;
}
However, I agree that regular expressions are not the best answer here. I'd use XPath to find elements I'm interested in. See The Java XPath API for more info.
Combining some answers here you can use something like the following.
class BaseActivity extends SherlockFragmentActivity
{
// Backwards compatible recreate().
@Override
public void recreate()
{
if (android.os.Build.VERSION.SDK_INT >= 11)
{
super.recreate();
}
else
{
startActivity(getIntent());
finish();
}
}
}
I tested it a bit, and there are some problems:
startActivity(...); finish();
just exist the app and doesn't restart the activity.super.recreate()
doesn't actually act the same way as totally recreating the activity. It is equivalent to rotating the device so if you have any Fragment
s with setRetainInstance(true)
they won't be recreated; merely paused and resumed.So currently I don't believe there is an acceptable solution.
Apps can’t be deleted if they are part of a Game Center group, in an app bundle, or currently displayed on a store. You’ll want to remove the app from sale or from the group if you want to delete it.
Source: iTunes Connect Developer Guide - Transferring and Deleting Apps
Somehow using Raja's approach worked for me only once, after a reboot, it seems gone.
To make it persistent across Mac OS reboot, I added this line into my ~/.zshrc
since I'm using zsh:
export PATH=/Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin:$PATH
then
source ~/.zshrc
now, I could just do
code .
even after I reboot my Mac.
You can do it like this:
I have a folder named utilities and inside that I have a file named _variables.scss
in that file i declare variables like so:
$black: #000;
$white: #fff;
then I have the style.scss file in which i import all of my other scss files like this:
// Utilities
@import "utilities/variables";
// Base Rules
@import "base/normalize";
@import "base/global";
then, within any of the files I have imported, I should be able to access the variables I have declared.
Just make sure you import the variable file before any of the others you would like to use it in.
This is an easier way to do it. Hope this helps...
<script type="text/javascript">
$(document).ready(function () {
$("#preview").toggle(function() {
$("#div1").hide();
$("#div2").show();
}, function() {
$("#div1").show();
$("#div2").hide();
});
});
<div id="div1">
This is preview Div1. This is preview Div1.
</div>
<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>
<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
Links:
http://www.w3schools.com/jquery/default.asp (W3Schools)
http://thenewboston.org/list.php?cat=32 (Video Tutorials)
http://andreehansson.se/the-basics-of-jquery/ (Basic Tutorial)
For me to sort this issue I had to go to Build, Execution, Deployment -> Build Tools -> Maven -> Importing and set JDK for import to JAVA_HOME! Then Reload all maven projects from the maven settings. All imports now work!!
You have to edit the eclipse.ini file to have an entry similar to this:
C:\Java\JDK\1.5\bin\javaw.exe (your location of java executable)
-vmargs
-Xms64m (based on you memory requirements)
-Xmx1028m
Also remember that in eclipse.ini, anything meant for Eclipse should be before the -vmargs
line and anything for JVM should be after the -vmargs
line.
Build system independent method
make SHELL='sh -x'
is another option. Sample Makefile
:
a:
@echo a
Output:
+ echo a
a
This sets the special SHELL
variable for make
, and -x
tells sh
to print the expanded line before executing it.
One advantage over -n
is that is actually runs the commands. I have found that for some projects (e.g. Linux kernel) that -n
may stop running much earlier than usual probably because of dependency problems.
One downside of this method is that you have to ensure that the shell that will be used is sh
, which is the default one used by Make as they are POSIX, but could be changed with the SHELL
make variable.
Doing sh -v
would be cool as well, but Dash 0.5.7 (Ubuntu 14.04 sh
) ignores for -c
commands (which seems to be how make
uses it) so it doesn't do anything.
make -p
will also interest you, which prints the values of set variables.
CMake generated Makefiles always support VERBOSE=1
As in:
mkdir build
cd build
cmake ..
make VERBOSE=1
Dedicated question at: Using CMake with GNU Make: How can I see the exact commands?
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
local::lib will help you. It will convince "make install" (and "Build install") to install to a directory you can write to, and it will tell perl
how to get at those modules.
In general, if you want to use a module that is in a blib/ directory, you want to say perl -Mblib ...
where ...
is how you would normally invoke your script.
| is a bitwise operator. || is a logical operator.
One will take two bits and or them.
One will determine truth (this OR that) If this is true or that is true, then the answer is true.
Oh, and dang people answer these questions fast.
no, there is no way to make array length dynamic in java. you can use ArrayList
or other List
implementations instead.
You could try checking to see if this method returns a null:
if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.
should means: At least one of these clauses must match, like logical OR.
Basically they are used like logical operators AND and OR. See this.
Now in a bool query:
must means: Clauses that must match for the document to be included.
should means: If these clauses match, they increase the _score
; otherwise, they have no effect. They are simply used to refine the relevance score for each document.
Yes you can use multiple filters inside must
.
DateTime.UtcNow.ToString("s")
Returns something like 2008-04-10T06:30:00
UtcNow
obviously returns a UTC time so there is no harm in:
string.Concat(DateTime.UtcNow.ToString("s"), "Z")
Since Java 15, you can use a non-static string method called String::formatted(Object... args)
Example:
String foo = "foo";
String bar = "bar";
String str = "First %s, then %s".formatted(foo, bar);
Output:
"First foo, then bar"
You can use either HttpClient
or RestSharp
. Since I do not know what your code is, here is an example using HttpClient
:
using (var client = new HttpClient())
{
// This would be the like http://www.uber.com
client.BaseAddress = new Uri("Base Address/URL Address");
// serialize your json using newtonsoft json serializer then add it to the StringContent
var content = new StringContent(YourJson, Encoding.UTF8, "application/json")
// method address would be like api/callUber:SomePort for example
var result = await client.PostAsync("Method Address", content);
string resultContent = await result.Content.ReadAsStringAsync();
}
If you need to run a full repair, use the repairpath
option. Point it to a disk with more available space.
For example, on my Mac I've used:
mongod --config /usr/local/etc/mongod.conf --repair --repairpath /Volumes/X/mongo_repair
Update: Per MongoDB Core Server Ticket 4266, you may need to add --nojournal
to avoid an error:
mongod --config /usr/local/etc/mongod.conf --repair --repairpath /Volumes/X/mongo_repair --nojournal
Here is an example which answers the question of returning the parameters of a class. Moreover, it still respects the chain of inheritance, i.e. only the parameters of the class itself are returned. The function get_params
is added as a simple example, but other functionalities can be added thanks to the inspect module.
import inspect
class Parent:
@classmethod
def get_params(my_class):
return list(inspect.signature(my_class).parameters.keys())
class OtherParent:
def __init__(self, a, b, c):
pass
class Child(Parent, OtherParent):
def __init__(self, x, y, z):
pass
print(Child.get_params())
>>['x', 'y', 'z']
You add your ActionListener
twice to button
. So correct your code for button2
to
JButton button2 = new JButton("hello agin2");
panel.add(button2);
button2.addActionListener (new Action2());//note the button2 here instead of button
Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater
You have to seed it. Seeding it with the time is a good idea:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
You get the same sequence because rand()
is automatically seeded with the a value of 1 if you do not call srand()
.
Due to comments
rand()
will return a number between 0 and RAND_MAX
(defined in the standard library). Using the modulo operator (%
) gives the remainder of the division rand() / 100
. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand() % 1000
.
i have tried with craeting a new object without deleting the coulmns in Vue.js.
let data =this.selectedContactsDto[];
//selectedContactsDto[] = object with list of array objects created in my project
console.log(data); let newDataObj= data.map(({groupsList,customFields,firstname, ...item }) => item); console.log("newDataObj",newDataObj);
Suppose you want to give attributes to an instance which was previously not written in code.
The setattr()
does just that.
It takes the instance of the class self
and key and value to set.
class Example:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if #available(iOS 10, *) {
//Notifications get posted to the function (delegate): func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void)"
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else {
//Display Error.. Handle Error.. etc..
return
}
if granted {
//Do stuff here..
//Register for RemoteNotifications. Your Remote Notifications can display alerts now :)
DispatchQueue.main.async {
application.registerForRemoteNotifications()
}
}
else {
//Handle user denying permissions..
}
}
//Register for remote notifications.. If permission above is NOT granted, all notifications are delivered silently to AppDelegate.
application.registerForRemoteNotifications()
}
else {
let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
application.registerForRemoteNotifications()
}
return true
}
I found this arrow(start, end)
function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.
Yo can try this:
SELECT CURDATE();
If you check the following:
SELECT NOW(); SELECT DATE(NOW()); SELECT DATE_FORMAT(NOW(),'%Y-%m-%d');
You can see that it takes a long time.
Nothing else on this page worked. This finally worked for me. Showing no untracked, or commited files.
git add -A
git reset --hard
If you're using typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
This function should handle multidimensional arrays along with multiple elements with the same name.
I've been using it for a couple years so far:
jQuery.fn.serializeJSON=function() {
var json = {};
jQuery.map(jQuery(this).serializeArray(), function(n, i) {
var _ = n.name.indexOf('[');
if (_ > -1) {
var o = json;
_name = n.name.replace(/\]/gi, '').split('[');
for (var i=0, len=_name.length; i<len; i++) {
if (i == len-1) {
if (o[_name[i]]) {
if (typeof o[_name[i]] == 'string') {
o[_name[i]] = [o[_name[i]]];
}
o[_name[i]].push(n.value);
}
else o[_name[i]] = n.value || '';
}
else o = o[_name[i]] = o[_name[i]] || {};
}
}
else {
if (json[n.name] !== undefined) {
if (!json[n.name].push) {
json[n.name] = [json[n.name]];
}
json[n.name].push(n.value || '');
}
else json[n.name] = n.value || '';
}
});
return json;
};
[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.
Roughly (untested):
app.get('/users/:email/messages/unread', function(req, res, next) {
var firstItem=true, query=MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
query.each(function(docs) {
// Start the JSON array or separate the next element.
res.write(firstItem ? (firstItem=false,'[') : ',');
res.write(JSON.stringify({ msgId: msg.fileName }));
});
res.end(']'); // End the JSON array and response.
});
Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:
// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));
You need to use join method of Thread
object in the end of the script.
t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
Thus the main thread will wait till t1
, t2
and t3
finish execution.
The anaconda functions are not exported by default, it can be done by using the following command:
$ source ~/anaconda3/etc/profile.d/conda.sh $ conda activate my_env
order[] is undefined that's why
Just define order[1]...[n] to = some value
this should fix it
With some of the answers here for disabling Google Chrome automatic updates, I've come up with a solution that uses specific group policy settings and also a PowerShell startup script to rename the GoogleUpdate.exe, disable the correlated services, and disable the correlated Task Scheduler tasks.
I'm posting as an answer in case someone else needs an all-in-one solution that can easily be expanded on (or toned down some) if needed and potentially save them some time.
## -- Rename the Google Update executable file
$Chrome = "${env:ProgramFiles(x86)}\Google\Update\GoogleUpdate.exe";
If(Test-Path($Chrome)){Rename-Item -Path $Chrome -NewName "Old_GoogleUpdate.exe.old" -Force};
$Chrome = "$env:ProgramFiles\Google\Update\GoogleUpdate.exe";
If(Test-Path($Chrome)){Rename-Item -Path $Chrome -NewName "Old_GoogleUpdate.exe.old" -Force};
## -- Stop and disable the Google Update services that run to update Chrome
$GUpdateServices = (Get-Service | ?{$_.DisplayName -match "Google Update Service"}).Name;
$GUpdateServices | % {
$status = (Get-Service -Name $_).Status;
If($status -ne "Stopped"){Stop-Service $_ -Force};
$sType = (Get-Service -Name $_).StartType;
If($sType -ne "Disabled"){Set-Service $_ -StartupType Disabled};
};
## -- Disable Chrome Update Scheduled Tasks
$GUdateTasks = (Get-ScheduledTask -TaskPath "\" -TaskName "*GoogleUpdateTask*");
$GUdateTasks | % {If($_.State -ne "Disabled"){Disable-ScheduledTask -TaskName $_.TaskName}};
Be sure the Software Restriction policy blocks EXE file types at a minimum for these specific folder locations but the defaults should work fine if you leave as-is.
Set Chrome Browser policies on managed PCs
its works for me that if you dont want to use alt attribute if image break then you can use this piece of code and set accordingly.
<h1>
<a>
<object data="~/img/Logo.jpg" type="image/png">
Your Custom Text Here
</object>
</a>
</h1>
It's A Script Write Copy then write in your script file and change your requered field and get out put
DECLARE @Sdate DATETIME, @Edate DATETIME, @Timediff VARCHAR(100)
SELECT @Sdate = '02/12/2014 08:40:18.000',@Edate='02/13/2014 09:52:48.000'
SET @Timediff=DATEDIFF(s, @Sdate, @Edate)
SELECT CONVERT(VARCHAR(5),@Timediff/3600)+':'+convert(varchar(5),@Timediff%3600/60)+':'+convert(varchar(5),@Timediff%60) AS TimeDiff
Here's another version, and it's arguably a bit simpler.
multipetal <- function(df, n) {
varname <- paste("petal", n, sep=".")
df<-mutate_(df, .dots=setNames(paste0("Petal.Width*",n), varname))
df
}
for(i in 2:5) {
iris <- multipetal(df=iris, n=i)
}
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species petal.2 petal.3 petal.4 petal.5
1 5.1 3.5 1.4 0.2 setosa 0.4 0.6 0.8 1
2 4.9 3.0 1.4 0.2 setosa 0.4 0.6 0.8 1
3 4.7 3.2 1.3 0.2 setosa 0.4 0.6 0.8 1
4 4.6 3.1 1.5 0.2 setosa 0.4 0.6 0.8 1
5 5.0 3.6 1.4 0.2 setosa 0.4 0.6 0.8 1
6 5.4 3.9 1.7 0.4 setosa 0.8 1.2 1.6 2
req.params
contains route parameters (in the path portion of the URL), and req.query
contains the URL query parameters (after the ?
in the URL).
You can also use req.param(name)
to look up a parameter in both places (as well as req.body
), but this method is now deprecated.
The following is needed:
Source: http://www.msdigest.net/2012/03/how-to-connect-to-office-365-with-powershell/
Then Follow this one if you're running a 64bits computer: I’m running a x64 OS currently (Win8 Pro).
Copy the folder MSOnline from (1) –> (2) as seen here
1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules(MSOnline)
2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules(MSOnline)
Source: http://blog.clauskonrad.net/2013/06/powershell-and-c-cant-load-msonline.html
Hope this is better and can save some people's time
Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"
@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;
Doing something with each child looks like:
this.customComponentChildren.forEach((child) => { child.stuff = 'y' })
There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild
Just 2 simple steps to solve your issue
First of all check AppendDataBoundItems property and make it assign false
Secondly clear all the items using property .clear()
{
ddl1.Items.Clear();
ddl1.datasource = sql1;
ddl1.DataBind();
}
The first answer is a very good one. In order to get to the Expert level, you should do a PhD with some of the Experts themselves.
I suggest you to visit the Haskell page: http://haskell.org. There you have a lot of material, and a lot of references to the most up-to-date stuff in Haskell, approved by the Haskell community.
Generally
static: no need to create object we can directly call using
ClassName.methodname()
Non Static: we need to create a object like
ClassName obj=new ClassName()
obj.methodname();
Another way would be to use reduce function and have a new array to be the accumulator. If there is already a thing
with the same name in the accumulator array then don't add it there.
let list = things.thing;
list = list.reduce((accumulator, thing) => {
if (!accumulator.filter((duplicate) => thing.name === duplicate.name)[0]) {
accumulator.push(thing);
}
return accumulator;
}, []);
thing.things = list;
I'm adding this answer, because I couldn't find nice, readable es6 solution (I use babel to handle arrow functions) that's compatible with Internet Explorer 11. The problem is IE11 doesn't have Map.values()
or Set.values()
without polyfill. For the same reason I used filter()[0]
to get first element instead of find()
.
joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right()
with a call to set_ticks_position('both')
. A revised example:
from matplotlib import pyplot as plt
f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()
The result is a plot with ticks on both sides, but tick labels on the right.
Obviously that os.chdir('..') is the right answer here. But just FYI, if in the future you come across situation when you have to extensively manipulate directories and paths, here is a great package (Unipath) which lets you treat them as Python objects: https://pypi.python.org/pypi/Unipath
so that you could do something like this:
>>> from unipath import Path
>>> p = Path("/usr/lib/python2.5/gopherlib.py")
>>> p.parent
Path("/usr/lib/python2.5")
>>> p.name
Path("gopherlib.py")
>>> p.ext
'.py'
Those steps should be able to be shortened down to:
hg pull
hg update -r MY_BRANCH -C
The -C
flag tells the update command to discard all local changes before updating.
However, this might still leave untracked files in your repository. It sounds like you want to get rid of those as well, so I would use the purge
extension for that:
hg pull
hg update -r MY_BRANCH -C
hg purge
In any case, there is no single one command you can ask Mercurial to perform that will do everything you want here, except if you change the process to that "full clone" method that you say you can't do.
msgbox "This is the first line" & vbcrlf & "and this is the second line"
or in .NET msgbox "This is the first line" & Environment.NewLine & "and this is the second line"
It can be done in two steps for Ubuntu 14.04 with Xampp 1.8.3-5
Step 1:- Change DocumentRoot
and Directory
path in /opt/lampp/etc/httpd.conf
from
DocumentRoot "/opt/lampp/htdocs"
and Directory "/opt/lampp/htdocs"
to
DocumentRoot "/home/user/Desktop/js"
and Directory "/home/user/Desktop/js"
Step 2:- Change the rights of folder (in path and its parent folders to 777) eg via
sudo chmod -R 777 /home/user/Desktop/js
Actually Shay levy's answer is almost correct but i got an weird issue as i mentioned in his comment column. So i split the command into two lines and it works fine.
$Ipaddress= Read-Host "Enter the IP address:"
$Port= Read-host "Enter the port number to access:"
$t = New-Object Net.Sockets.TcpClient
$t.Connect($Ipaddress,$Port)
if($t.Connected)
{
"Port $Port is operational"
}
else
{
"Port $Port is closed, You may need to contact your IT team to open it. "
}
get current activity from parent, then using this code
getActivity().getSupportFragmentManager()
-Wall
and -Werror
compiler options can cause it, please check if those are used in compiler settings.
When you use @DataJpaTest you need to load classes using @Import explicitly. It wouldn't load you for auto.
If you want to open Google Maps in a browser:
http://maps.google.com/?q=<lat>,<lng>
To open the Google Maps app on an iOS mobile device, use the Google Maps URL Scheme:
comgooglemaps://?q=<lat>,<lng>
To open the Google Maps app on Android, use the geo: intent:
geo:<lat>,<lng>?z=<zoom>
It can be solved by placing @EnableAutoConfiguration on spring boot application main class.
Here is how to integrate CSS star rating into an HTML form without using javascript (only html and css):
CSS:
.txt-center {
text-align: center;
}
.hide {
display: none;
}
.clear {
float: none;
clear: both;
}
.rating {
width: 90px;
unicode-bidi: bidi-override;
direction: rtl;
text-align: center;
position: relative;
}
.rating > label {
float: right;
display: inline;
padding: 0;
margin: 0;
position: relative;
width: 1.1em;
cursor: pointer;
color: #000;
}
.rating > label:hover,
.rating > label:hover ~ label,
.rating > input.radio-btn:checked ~ label {
color: transparent;
}
.rating > label:hover:before,
.rating > label:hover ~ label:before,
.rating > input.radio-btn:checked ~ label:before,
.rating > input.radio-btn:checked ~ label:before {
content: "\2605";
position: absolute;
left: 0;
color: #FFD700;
}
HTML:
<div class="txt-center">
<form>
<div class="rating">
<input id="star5" name="star" type="radio" value="5" class="radio-btn hide" />
<label for="star5">?</label>
<input id="star4" name="star" type="radio" value="4" class="radio-btn hide" />
<label for="star4">?</label>
<input id="star3" name="star" type="radio" value="3" class="radio-btn hide" />
<label for="star3">?</label>
<input id="star2" name="star" type="radio" value="2" class="radio-btn hide" />
<label for="star2">?</label>
<input id="star1" name="star" type="radio" value="1" class="radio-btn hide" />
<label for="star1">?</label>
<div class="clear"></div>
</div>
</form>
</div>
Please check the demo
This question is almost three years old, but anyway...
If you're using GNU make, this is easy to do. The only problem is that make
will interpret non-option arguments in the command line as targets. The solution is to turn them into do-nothing targets, so make
won't complain:
# If the first argument is "run"...
ifeq (run,$(firstword $(MAKECMDGOALS)))
# use the rest as arguments for "run"
RUN_ARGS := $(wordlist 2,$(words $(MAKECMDGOALS)),$(MAKECMDGOALS))
# ...and turn them into do-nothing targets
$(eval $(RUN_ARGS):;@:)
endif
prog: # ...
# ...
.PHONY: run
run : prog
@echo prog $(RUN_ARGS)
Running this gives:
$ make run foo bar baz
prog foo bar baz
For any of you calling back to the same server for your IFRAME, pass this simple header inside the IFRAME page:
Content-Security-Policy: frame-ancestors 'self'
Or, add this to your web server's CSP configuration.
>>> numpy.array([[1, 2], [3, 4]])
array([[1, 2], [3, 4]])
#change-avatar-file
is a file input
#change-avatar-file
is a img tag (the target of jcrop)
The "key" is FR.onloadend Event
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
$('#change-avatar-file').change(function(){
var currentImg;
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
$('#avatar-change-img').attr( "src", e.target.result );
currentImg = e.target.result;
};
FR.readAsDataURL( this.files[0] );
FR.onloadend = function(e){
//console.log( $('#avatar-change-img').attr( "src"));
var jcrop_api;
$('#avatar-change-img').Jcrop({
bgFade: true,
bgOpacity: .2,
setSelect: [ 60, 70, 540, 330 ]
},function(){
jcrop_api = this;
});
}
}
});
In your edit action, store the requesting url in the session hash, which is available across multiple requests:
session[:return_to] ||= request.referer
Then redirect to it in your update action, after a successful save:
redirect_to session.delete(:return_to)
You will not be able to do that. You can download apps again to the same userid account on different devices, but you cannot transfer those licenses to other userids.
There is no way to do this programatically - I don't think you can do that practically (except for trying to call customer support at the Play Store).
As explained in the openpub documentations,
pthread_exit()
will exit the thread that calls it.
In your case since the main calls it, main thread will terminate whereas your spawned threads will continue to execute. This is mostly used in cases where the main thread is only required to spawn threads and leave the threads to do their job
pthread_join
will suspend execution of the thread that has called it unless the target thread terminates
This is useful in cases when you want to wait for thread/s to terminate before further processing in main thread.
Of course.
That is normal and sane behaviour.
Instead of closing and re-opening, you could rewind
the file.
You can use ObjectMapper.convertValue()
, either value by value or even for the whole list. But you need to know the type to convert to:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
// or:
List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { });
this is functionally same as if you did:
byte[] json = mapper.writeValueAsBytes(singleObject);
POJO pojo = mapper.readValue(json, POJO.class);
but avoids actual serialization of data as JSON, instead using an in-memory event sequence as the intermediate step.
Specify crossAxisAlignment: CrossAxisAlignment.start
in your column
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
One way would be with sed
. For example:
echo $name | sed -e 's?http://www\.??'
Normally the sed
regular expressions are delimited by `/', but you can use '?' since you're searching for '/'. Here's another bash trick. @DigitalTrauma's answer reminded me that I ought to suggest it. It's similar:
echo ${name#http://www.}
(DigitalTrauma also gets credit for reminding me that the "http://" needs to be handled.)
To Increase Maximum heap: Click to open your Android Studio, look at below pictures. Step by step. ANDROID STUDIO v2.1.2
Click to navigate to Settings from the Configure or GO TO FILE SETTINGS at the top of Android Studio.
check also the android compilers from the link to confirm if it also change if not increase to the same size you modify from the compiler link.
Note: You can increase the size base on your memory capacity and remember this setting is base on Android Studio v2.1.2
Hashing algorithms are usually cryptographic in nature, but the principal difference is that encryption is reversible through decryption, and hashing is not.
An encryption function typically takes input and produces encrypted output that is the same, or slightly larger size.
A hashing function takes input and produces a typically smaller output, typically of a fixed size as well.
While it isn't possible to take a hashed result and "dehash" it to get back the original input, you can typically brute-force your way to something that produces the same hash.
In other words, if a authentication scheme takes a password, hashes it, and compares it to a hashed version of the requires password, it might not be required that you actually know the original password, only its hash, and you can brute-force your way to something that will match, even if it's a different password.
Hashing functions are typically created to minimize the chance of collisions and make it hard to just calculate something that will produce the same hash as something else.
Every answer requires changing of the import statements.
If you want to be able to use:
import {a} from './my-module' // a === 1
import * as myModule from './my-module' // myModule.a === 1
as in the question, and in your my-module
you have everything that you need to export in one object (which can be useful e.g. if you want to validate the exported values with Joi or JSON Schema) then your my-module
would have to be either:
let values = { a: 1, b: 2, c: 3 }
let {a, b, c} = values;
export {a, b, c};
Or:
let values = { a: 1, b: 2, c: 3 }
export let {a, b, c} = values;
Not pretty, but it compiles to what you need.
See: Babel example