text:
Q: Buildbot fails when running as a daemon on mac osx 10.8 I've set up a buildslave to manage mac osx builds on a small apple computer in my room. Everything installed smoothly and before I knew it my apple server began churning away at its first few builds with no problems at all.
Seeing as everything worked flawlessly, I added the buildslave as a daemon according to this guide:
http://trac.buildbot.net/wiki/UsingLaunchd
One reboot and $ sudo launchctl start ch.pixelcloud.game.lightship later and it stopped working. I noticed it also stops working when I start the buildslave via SSH and close my SSH connection.
After some googling I figured out that programs lose some common functionality (in this case, DNS lookups) when the user who started the process logs out. I seem to have fixed this by adding 8.8.8.8 to the list of DNS servers, but now I'm running into another issue and I can't for the life of me figure out what's causing it.
This is the error output in buildbot's web interface:
git --version
in dir /Users/thecomet/buildbot/slaves/lightship/basedir/test-macosx-i686-applebloom/build (timeout 1200 secs)
watching logfiles {}
argv: ['git', '--version']
environment:
  HOME=/Users/thecomet
  LOGNAME=thecomet
  PATH=/usr/bin:/bin:/usr/sbin:/sbin
  PWD=/Users/thecomet/buildbot/slaves/lightship/basedir/test-macosx-i686-applebloom/build
  SHELL=/bin/zsh
  TMPDIR=/var/folders/zS/zSzxVZUsHyOdGytmqY0aUE+++TM/-Tmp-/
  USER=thecomet
  __CF_USER_TEXT_ENCODING=0x1F6:0:0
using PTY: False
Upon execvpe git ['git', '--version'] in environment id 4320746024
:Traceback (most recent call last):
  File "/Users/thecomet/buildbot/slaves/lightship/lightship/lib/python2.7/site-packages/twisted/internet/process.py", line 424, in _fork
environment)
  File "/Users/thecomet/buildbot/slaves/lightship/lightship/lib/python2.7/site-packages/twisted/internet/process.py", line 502, in _execChild
os.execvpe(executable, args, environment)
  File "/Users/thecomet/buildbot/slaves/lightship/lightship/bin/../lib/python2.7/os.py", line 355, in execvpe
_execvpe(file, args, env)
  File "/Users/thecomet/buildbot/slaves/lightship/lightship/bin/../lib/python2.7/os.py", line 382, in _execvpe
func(fullname, *argrest)
OSError: [Errno 2] No such file or directory
program finished with exit code 1
elapsedTime=0.012076

Slave twistd.log:
2015-06-30 01:41:03+0200 [Broker,client]  startCommand:shell [id 761]
2015-06-30 01:41:03+0200 [Broker,client] RunProcess._startCommand
2015-06-30 01:41:03+0200 [Broker,client]  git --version
2015-06-30 01:41:03+0200 [Broker,client]   in dir /Users/thecomet/buildbot/slaves/lightship/basedir/test-macosx-i686-applebloom/build (timeout 1200 secs)
2015-06-30 01:41:03+0200 [Broker,client]   watching logfiles {}
2015-06-30 01:41:03+0200 [Broker,client]   argv: ['git', '--version']
2015-06-30 01:41:03+0200 [Broker,client]  environment: {'SHELL': '/bin/zsh', '__CF_USER_TEXT_ENCODING': '0x1F6:0:0', 'PWD': '/Users/thecomet/buildbot/slaves/lightship/basedir/test-macosx-i686-applebloom/build', 'LOGNAME': 'thecomet', 'USER': 'thecomet', 'PATH': '/usr/bin:/bin:/usr/sbin:/sbin', 'HOME': '/Users/thecomet', 'TMPDIR': '/var/folders/zS/zSzxVZUsHyOdGytmqY0aUE+++TM/-Tmp-/'}
2015-06-30 01:41:03+0200 [Broker,client]   using PTY: False
2015-06-30 01:41:03+0200 [-] command finished with signal None, exit code 1, elapsedTime: 0.012076
2015-06-30 01:41:03+0200 [-] SlaveBuilder.commandComplete <buildslave.commands.shell.SlaveShellCommand instance at 0x10186c1b8>

Master twistd.log:
2015-06-30 01:41:19+0200 [-] <Build test-macosx-i686-applebloom>.startBuild
2015-06-30 01:41:19+0200 [-] [Contact] Builder <buildbot.status.builder.BuilderStatus instance at 0x7fdc28bb3368> with tags None started
2015-06-30 01:41:19+0200 [-] <RemoteShellCommand '['git', '--version']'>: RemoteCommand.run [761]
2015-06-30 01:41:19+0200 [-] command '['git', '--version']' in dir 'build'
2015-06-30 01:41:19+0200 [Broker,42,(ip removed)] <RemoteShellCommand '['git', '--version']'> rc=1
2015-06-30 01:41:19+0200 [-] Source step failed while running command <RemoteShellCommand '['git', '--version']'>
2015-06-30 01:41:19+0200 [-] releaseLocks(<buildbot.steps.source.git.Git object at 0x7fdbf56f2810>): []

I can confirm the directory exists. Why am I getting this error?
Here is the $ uname -a of the buildslave in case it's relevant:
Darwin applebloom 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:33:36 PDT 2011; root:xnu-1504.15.3~1/RELEASE_I386 i386

I'm using Buildslave version 0.8.12 and Twisted version 15.2.1.


text:
Q: Python- timestamps of packets using DPKT I am using dpkt library to get timestamp of packets and need to convert it into seconds. Below is my code to get packet timestamp:
f = open('test.pcap')
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
      print "timestamp:",ts

I have 2 questions here:
1. Is the timestamp in milliseconds as I am not able to confirm this from   documentation?
2.  If it is in milliseconds... good way to convert to seconds is ts/1000.0 ?

A: Look, seconds, milliseconds and nanoseconds are units of time duration. Right?
While,
A timestamp is the instant of time at which a packet is sent or received. Usually, in Wireshark, the time stamp consists of the date (in days since 1.1.1970) and the time of day (in nanoseconds since midnight).
Now after clarifying the difference, the following one-line code (using dpkt tool and python) can convert a
print ('Timestamp: ', str(datetime.datetime.utcfromtimestamp(ts)))

Timestamp:  2019-09-05 08:59:34.269526
Am I clear?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Redirecting to a controller in SpringMvc I have a class which has multiple controller in it and from one of the controller i want to call another controller which is in different class and when the particular controller is called that controller will create the view.
my codes are
class one // class from which controller will be called
    @Controller
@RequestMapping(value="/register")
public class PatientController {
@RequestMapping(value="/demo1", method=RequestMethod.GET)
public String demo1(){
    System.out.println("Demo1 method.....");
    return "redirect:user/dashboard";
}
}

Class second // controller of this class to be called
@Controller
        @RequestMapping("/user")
    public class UserDasboardController {
    @RequestMapping(value="/dashboard", method=RequestMethod.GET)
        public String get(ModelMap model){

            return "userdashboard";// returning view
        }

    }

after the first controller is called gives url as ".../register/user/dashboard"
however it should give  url as"..../user/dashboard".
please suggest how can I achieve this.
Or there is any other way of doing same thing.

A: when using redirect for the same controller file we can use this as
return "redirect: controllerName"

if you want to call the controller of another class you have to call it as using / before it so that will be as
"redirect:/firstController/yourSubController"

Hope this helps.

A: Another solution is: MvcUriComponentsBuilder MvcUriComponentsBuilder docs
There are some great methods like: fromMethod(), fromController() and more.
You can receive proper redirection path to another method/controller automatically.
Example - redirect to another controller:
final UriComponentsBuilder uriComponents = MvcUriComponentsBuilder.fromController(WheredoYouWantToRedirectController.class);
final String path = uriComponents.build().getPath();

return REDIRECT_PREFIX+path;

In the same way you may work with redirection to methods.
MvcUriComponentsBuilder helps to reduce errors connected with redirections.
Please check documentation for more info.


text:
Q: toUTF8String and local reference http://www.icu-project.org/apiref/icu4c/classicu_1_1UnicodeString.html#a05777d826515a20a0b2bb8f4108f9348
StringClass & toUTF8String (StringClass &result) const
Convert the UnicodeString to UTF-8 and append the result to a standard string.
Parameters: result
A standard string (or a compatible object)
to which the UTF-8 version of the string is appended.
Returns:
The string object.
// My own function.
string toStdString(const UnicodeString& a_str)
{
    string str;
    a_str.toUTF8String(str);
    return (str);
}
int main (void)
{
    string a = toStdString("a");
    string b = toStdString("b");

    cout << "a:" << a << endl; // a
    cout << "b:" << b << endl; // b

    const char* a1 = toStdString("a").c_str();
    const char* b1 = toStdString("b").c_str();

    cout << "a1:" << a1 << endl; // b !!! Problem: Why not "a"?
    cout << "b1:" << b1 << endl; // b

    const char* a2 = a.c_str();
    const char* b2 = b.c_str();

    cout << "a2:" << a2 << endl; // a
    cout << "b2:" << b2 << endl; // b

    return (0);
}

A: The function toStdString returns a temporary, which goes away if you don't store it somewhere.
In this statement
const char* a1 = toStdString("a").c_str();

you store a pointer into this temporary object. At the end of the statement, this temporary string is destroyed again and the pointer points nowhere.
Trying to use the pointer later results in undefined behaviour and anything could happen, including displaying some other string.

A: It has nothing to do with ICU, but rather that you are storing a pointer to a temporary object. When you call
const char* a1 = toStdString("a").c_str();

The toStdString returns a string object, then you call c_str on int, which returns a temporary pointer to its contents. After the string object is destroyed, the pointer is invalid and should not be used. In your case, the next call to c_str probably returned the exact same pointer to a temporary object, overwriting the previous one.


text:
Q: Havesting mysql queries with node I just started with Node.js and I am stuck at how to harvest the result of a database query with node.
If we considering how this work in PHP we have something like:
(after setting the connection $connection)
$query="select field_x from Table where field='something'";
$result=@ mysqli_query($connection, $query);
if(mysqli_num_rows($result)>0)
{
   $row=@ mysqli_fetch_array($result);
}
$data='';
if(isset($row['field_x']))
{
   // query result is HARVESTED
   $data=$row['field_x'];
}

and if the result of the query is not null, $data (=$row['field_x']) can be used every where in the code out of the query block.
Is there a very simple and straight forward way (analogous to PHP way) to do this in node.
Basically I would like to define an arrray/variable with global scope and pass it to the connection-query block and put in that array/variable the result of the query, something like:
var Array=[]; // global scope
var mysql = require('mysql');
var connection = mysql.createConnection({some_stuff});

connection.connect();
var queryString = 'SELECT field_x FROM Table';
connection.query(queryString, function(err, rows, fields) {
if (err) throw err;

for (var i in rows) {
    Array.push(rows[i].field_x));
}
});

connection.end();

Any suggestion/advice?
Regards.

A: It looks like you're ending the connection before the query is done running & responding.  Try putting connection.end() inside the callback.

A: I am feeling a bit silly answering my own question... Anyway.
My question is about if there is a similar approach as in PHP to harvest data from a database.
The thing is that since PHP is not asynchronous, querying a database takes place in the normal executing flow, which means that one has to wait till the database server responses before executing the next line of code.
In the asynchronous world of node.js, querying a database involves callbacks, these callbacks are out of the synchronous execution flow.
Therefore, in this case, trying to implement an analogous of the PHP code will fail because any reference to the array where the result of the database query means to be set, happens synchronously while querying the database is an asynchronous task, which mean that it will be execute at some point after the synchronous flow has finish execution.


text:
Q: Could not find com.android.tools.build:gradle:3.0.1. while trying to build tensorflow lite demo app I am getting this error.
I am trying to build Tensorflow lite demo app but it is not working.
Could not find com.android.tools.build:gradle:3.0.1.
Searched in the following locations:
    https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.pom
https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.1/gradle-3.0.1.jar
Required by:
    project :
Open File
This is my build,gradle file:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "android.example.com.tflitecamerademo"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

        // Remove this block.
        jackOptions {
            enabled true
        }
    }
    lintOptions {
        abortOnError false
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    aaptOptions {
        noCompress "tflite"
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories {
    maven {
        url 'https://google.bintray.com/tensorflow'
    }
    google()
    maven {
        url 'https://maven.google.com/'
        name 'Google'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:support-annotations:25.3.1'
    compile 'com.android.support:support-v13:25.2.0'

    compile 'org.tensorflow:tensorflow-lite:+'

    testCompile 'junit:junit:4.12'
}

buildscript {
    repositories {
        google()
        jcenter()
        mavenLocal()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.0.1'
        }
    }
}

A: Please try to change the classpath dependencies as following
dependencies {
    classpath 'com.android.tools.build:gradle:2.3.3'}

and also please refer to this link
Thank you.


text:
Q: Function to store strings as ints I have a fixed 32 bits in which to store as much DNA as possible. The amount of space required to store 1 character of DNA ('A', 'C', 'G' or 'T') is 2 bits (00, 01, 10, 11, as there are only 4 combinations).
To store up to 2 characters, (so, A, C, G, T, AA, AC, ..., GG) there are 20 possible combinations, which we can work out with the function ((4**(x+1))-2)/(4-1), where x is the maximum length of DNA we want to store. 16 characters of DNA would therefore have 5,726,623,060 combinations, however in 32 bits I can only store up to 4,294,967,296 numbers (2**32).
So long story short, in 32 bits the maximum amount of variable-length DNA one can store is 15 letters (1,431,655,764 combinations).
So, next step is to make a function which takes up to 15 letters of DNA as a string, and turns it into a number. It doesn't matter which number ('A' could be 0, it could be 1, it could be 1332904, it really doesn't matter) so long as we can reverse the function and get the number back to 'A' later.
I started to solve this by making a dictionary of key, value pairs containing 1,431,655,764 elements, but quickly ran out of RAM. This is why I need a translation function from string to int.

A: Here is my suggestion.
If storing your letters takes 2 to 30 bits, you have at least 2 bits left to help you to deduce the length. Always add a 1 after the bits representing your characters, and pad the rest with zeroes. That way, if you look for the last 1 in your bit pattern, it will always be just after the end of your string.
E.g.
A  -> 00 (meaning 'A') followed by 1 (meaning 'end') followed by 29 zeroes
   -> 00100000000000000000000000000000
C  -> 01 (meaning 'C') followed by 1 (meaning 'end') followed by 29 zeroes
   -> 01100000000000000000000000000000
G  -> 10 (meaning 'G') followed by 1 (meaning 'end') followed by 29 zeroes
   -> 10100000000000000000000000000000
T  -> 11 (meaning 'T') followed by 1 (meaning 'end') followed by 29 zeroes
   -> 11100000000000000000000000000000
AA -> 0000 (meaning 'AA') followed by 1, followed by 27 zeroes
   -> 00001000000000000000000000000000
...
AAAAAAAAAAAAAAA
   -> 000000000000000000000000000000 (meaning the 'A's) followed by 1, followed by 1 zero
   -> 00000000000000000000000000000010

That ought to unambiguously represent your string and allow you up to 15 characters in 32 bits.

A: Given a static ordering, you can refer to each individual permutation as a single number representing its order in the sequence. Then rather than building the dictionary you can convert it on the other side.
import itertools

def build_sequence(length):
    return itertools.product("ACTG", repeat=length)

def encode(sequence: str):
    seq = build_sequence(len(str))
    t_seq = list(sequence)  # to compare to seq
    for idx, s in enumerate(seq):
        if s == t_seq:
            return idx

def decode(e_sequence):
    max_length = math.ceil(math.log(e_sequence, 4))
    # max_length is the character count of ATCGs that e_sequence contains,
    #   since each sequence has 4**length elements
    seq = build_sequence(max_length)
    for _ in range(e_sequence):
        # skipping these is like indexing a list
        next(seq)
    return next(seq)

You can then pack that number into a smaller type and send it over the wire, unpack it again, and decode it.
import struct

packed = struct.pack("I", encode(some_sequence))
#  send it? I'm not sure what you're doing with it

rcvd_pack = b'SUUU'
unpacked = struct.unpack("I", rcvd_pack)
# becomes a tuple of the value
enc_seq = unpacked[0]

result = decode(enc_seq)

This should let you build 16 character sequences and pack them in 32 bits of data.

A: Using Khelwood's info, I solved it with the following code:
b = {'A':0b00,'C':0b01,'G':0b10,'T':0b11}
t = {'00':'A','01':'C','10':'G','11':'T'}

def binarize(string):
    result = 0
    for char in (string + 'G').ljust(16,'A'): result = (result << 2) + d[char]
    return result

def textualize(value):
    result = ''
    for twobits in [ format(value, '032b')[i:i+2] for i in range(0,32,2) ]:
        result += t[twobits]
    return result.rstrip('A')[:-1]

>>> binarize('TTTTTTTTTTTTTTT')
    4294967294

>>> textualize(4294967294)
    u'TTTTTTTTTTTTTTT'

I'm sure there is a more efficient way of doing all this, which I think I will need to do as i'll be encoding and decoding billions of times, but for now it at least works :)


text:
Q: Why are the json fields returned from Autodesk Forge API for displayName different for "included" and "data" fields? When querying a model (item) via the Autodesk Data Management Forge API:
GET projects/:project_id/folders/:folder_id/search
the returned data.attributes.displayName is sometimes different than the included.attributes.displayName for the same id.  Can you explain what the difference is between "included" and "data" and which would be the one to use to get the current value of the name that is displayed in the A360 Project.
Example with the names changed and pertinent data only:
{
    "jsonapi": {
        "version": "1.0"
    },
    "links": {
    },
    "data": [
        {
            "type": "versions",
            "id": "urn:adsk.wipprod:fs.file:vf.00UeaES1TmW67ZUDMfSn1A?version=3",
            "attributes": {
                "name": "56750_A.rvt",
                "displayName": "56750_A.rvt",
                }
            }
        }
    ],
    "included": [
        {
            "type": "items",
            "id": "urn:adsk.wipprod:dm.lineage:00UeaES1TmW67ZUDMfSn1A",
            "attributes": {
                "displayName": "343435_A.rvt",

            }
        }
    ]
}


text:
Q: Событие при прокрутке конца списка select Доброго времени суток.
Вот наткнулся на такую задачу,как определить конец списка select при прокрутке?
А именно я хочу реализовать такую штуку. У меня имеется список
<select class="select_listUser" name="user_list[]" multiple="">
<option value="0">Text_1</option>
<option value="0">Text_2</option>
<option value="0">Text_3</option>
<option value="0">Text_4</option>
<option value="0">Text_5</option>
<option value="0">Text_6</option>
</select>

Хочу чтобы при прокрутке списка до конца срабатывал обработчик,который будет добавлять в конец списка еще несколько option.

Не получается  получить конец списка.
Заранее спасибо.
A: Как-то так работает в chrome, последний элемент - $t.children().last();
$('.select_listUser').scroll(function(e){
    var $t=$(this);
    if ($t.height()+$t.scrollTop()-$t.prop('scrollHeight')>0) return;
    add_rand_opt($t);
});

function add_rand_opt($t) {
    $('<option>',{text: Math.random()}).val(Math.random()).appendTo($t);
}

http://jsfiddle.net/oceog/bYs3d/


text:
Q: Oscillator circuit with TL071 opAmp for amateur very short range AM radio I stumbled upon this nice video and thought I'd try to reproduce the experiment. Basically the video shows how to build an AM transmitter circuit using an opamp, some resistors and a capacitor. This is the circuit schematics for the oscillator that should generate the carrier wave:

simulate this circuit – Schematic created using CircuitLab
The carrier wave should be at the OUT node right? My problem is that I do not understand how can this circuit oscillate since it is getting constant voltages as input and the video does not say anything about any function generator. My guess is that instead of 9 Volts in the voltage divider I should use a function generator with the carrier wave (possibly a 9V sine wave). Am I right or did I miss some component/key concept? Also by simulating the circuit with the potentiometer set to 0 on LTspice I get no oscillation at the OUT node but just a constant voltage (as expected) of 3.6V.
EDIT: the circuit should work in the 300kHz - 1.2MHz range

A:
the video shows how to build an AM transmitter circuit using an opamp,
  some resistors and a capacitor.

It's a relaxation oscillator and here's a simplified version using a schmitt trigger: -

However, as a carrier wave it's poor because it's basically a square wave and not a sinewave. If you are going to transmit (illegally or not) don't use a square wave as an oscillator because you'll broadcast your transmission at the fundamental frequency of the carrier (say) 1 MHz and every odd harmonic up into hundreds of MHz i.e. you become a polluter.
Anyway, back to your question, When the inverter output changes state from zero to one, it charges the capacitor up (via the resistor) until the cap voltage triggers the upper limit in the schmitt trigger. This forces the output to zero and the capacitor discharges via the resistor. Back to square one and the process repeats.
If you can follow the above circuit operation then you should be able to figure out that your circuit is identical in nature.
Hint: inside my circuit hides R1, R2 and R4 and, because they are hidden internally, there is no need to show the non-inverting input.


text:
Q: Install and open package through adb I can install an apk through adb without any issue.
But after I install it, I want to OPEN that package through adb. I want to send an Intent to the package that opens the MAIN or LAUNCHER activity just how the launcher would.
But adb seems to always want to me include an activity name in my intent.
How do I get around this?
Can I scan an apk for all the package names? For the main one?
Is there a way to open it through adb without an Activity name?

A: With aapt you can find the launchable activity, for example:
$ aapt dump badging file.apk | grep package
package: name='com.triposo.droidguide.world' versionCode='161' versionName='2.1'

$ aapt dump badging file.apk | grep launchable
launchable-activity: name='com.triposo.droidguide.world.SplashActivity'  label='' icon=''

To specify an intent when you launch an activity, you can use a MonkeyRunner script and MonkeyDevice.startActivity:
from com.android.monkeyrunner import MonkeyRunner
device = MonkeyRunner.waitForConnection()
package = 'com.triposo.droidguide.world'
launchable_activity = 'com.triposo.droidguide.world.SplashActivity'
device.startActivity(component='%s/%s' % (package, launchable_activity)))

A: Through adb you can simplify the app opening process by using monkey from adb itself without needing to find the launchable activity.
For example, to open Facebook:
adb shell monkey -p com.facebook.katana 1


text:
Q: Espresso - TextView contains String Quite simply, how do I say if a given TextView contains a specific string in Espresso.
The equivalent of: myStrings.contains("Subby");

A: Use withText
onView(...).check(matches(withText("Subby")));

onView(withId(R.id.textView)).check(matches(withText("Subby")));

A: Use withSubstring(substring), it is same as withText(containsString(substring)) but more concise

A: You can use the Hamcrest library. It has a method containsString.
I believe it is in the Espresso library.
You can static import it in your class:
import static org.hamcrest.core.StringContains.containsString;

Use containsString in your method on a TextView:
textView.check(matches(withText(containsString("Test"))));


text:
Q: How can I intercept the domain services generated by RIA tooling during compile? Currently it is possible to customise how entities are generated on the client side of RIA services via the 'CodeProcessor' class. For any domain service that needs client side generation, the code processor can be used to intercept each entity/namespace and make adjustments, etc.
But in my case I need to actually intercept which domain services will have generation occur to begin with.
I noticed that in the DomainServiceDescription there is a static private readonly domainServiceMap which contains all the services being generated. However there is no way to access this map during compile time that I can find.
I'm hoping (fingers crossed) that there is a hook somewhere that I can interact with that service map such that I can remove items from the collection prior to generation commencing.
Any ideas?

A: The CodeProcessor seems to the old way of doing that and I think it's limited to only generate the entities. In newer versions we can specify T4 based Generators for all the different pieces.
Install RIAServices.T4 from Nuget in the WebProejct or a Class Library that will contain the the code generation classes.
   PM> Install-Package RIAServices.T4
If you have the toolkit already, just add a reference to "Microsoft.ServiceModel.DomainServices.Tools.TextTemplate"
Then we need to inherit from CSharpClientCodeGenerator, which doesn't really generate anything, but just tells RIA which generators to use by overriding some of its properties.
[DomainServiceClientCodeGenerator("MyCustomGenerator", "C#")]
public class MyCSharpClientCodeGenerator : CSharpClientCodeGenerator
protected override Microsoft.ServiceModel.DomainServices.Tools.TextTemplate.DomainContextGenerator DomainContextGenerator
    {
        get
        {
            //return base.DomainContextGenerator;
            return new MyDomainContextGenerator();
        }
    }

Then we tell R# to implement that class for us (MyDomainContextGenerator) which has to inherit from CSharpDomainContextGenerator. Of course if you use R# it will just do it for you.
You have other 4 different code generators that you can provide from MyCSharpClientCodeGenerator.
Now to hook it all up, in the Silverlight project file we need to tell RIA to use our generator. We have to edit the Silverlight project and add the following element inside the first PropertyGroup just after LinkedServerProject (the order doesn't matter, I just say that as a reference).
  <LinkedServerProject>..\SilverlightApplication2.Web\SilverlightApplication2.Web.csproj</LinkedServerProject>
  <RiaClientCodeGeneratorName>
    SilverlightApplication2.Web.RiaStuff.MyCSharpClientCodeGenerator,SilverlightApplication2.Web
  </RiaClientCodeGeneratorName>
</PropertyGroup>

Recompile the Silverlight project and voila. It might crash. To debug this we can open another instance of Visual Studio, set breakpoints on the Generators in this new instance, attach to the first instance of Visual Studio and recompile the Silverlight project.


text:
Q: Prove that $3x^3+4y^3+5z^3 \equiv 0 \pmod{p}$ is solvable for all primes p I am trying to prove that the congruence $3x^3+4y^3+5z^3 \equiv 0 \pmod{p}$ is solvable for all primes p. I proved it using primitive root, but my professor in number theory told me that it can be more directly done using the hasse-weil theorem in the theory of elliptic curves, but i cant do it. Would someone kindly show me how to make use of the hasse-weil theorem, please? Thank you in advance.

A: This can be done in $4$ steps:

*

*Prove it directly for $p=2,3$, i.e., find a non-trivial solution modulo $2$ and one modulo $3$.

*Prove that $C: 3x^3+4y^3+5z^3=0$ is a non-singular curve over $\mathbb{F}_p$, where $p>3$ is a prime.

*Show the following: if $C:F(x,y,z)=0$ is a non-singular curve given by a homogeneous polynomial of degree $d\geq 1$, then the genus of $C$ is given by $(d-1)(d-2)/2$. In particular, in our case, $g=1$. (This is Exercise 2.7 in Chapter 2 of Silverman's "The Arithmetic of Elliptic Curves", for instance.)

*Use the Hasse-Weil bounds.
Note: you cannot use the fact that $C/\mathbb{F}_p$ is an elliptic curve before you find a $\mathbb{F}_p$-rational point on $C$!


text:
Q: How can I obtain the live state of the checkbox e.g. checkboxesVM.checked in powershell? I have the code below working perfectly to display the listed folders and the specific VM's in each folder.  The problem comes when I try to find out the checkedstate for each of the checkboxes - the active UI gives me a good checkmark, but nowhere can I find a value/variable I can reference to do two things initially - one, to mark/unmark all the VM's under each Folder if the Folder is checked/unchecked and two, to execute the desired actions - which in this case will include poweroff/poweron support.
Sorry about the size - if you want just the core of the checkbox array - it is in the checkbox region.  The button1 gives me the ability to see which of the checkboxes has been checked because I am looping through the checkboxes but that does not give me active control over the checkboxes.
The script works great in layout but I cannot seem to find the variable references to obtain the state of the checkboxes or checkboxesVM can anyone tell me how to do this inside the UI so they report their active state in the listbox?  Once I have that I think I can get it working for the stuff I need.
$ServerList = Get-VM | Sort-Object -Property Folder,Name | `
?{$_.PowerState -eq "PoweredOn"}
$ServerCount= $ServerList.Count
$VMFolders = $ServerList | Group-Object folder

#----------------------------------------------
Function GenerateForm {
$handler_button1_Click= {
#Click Event Monitor
$listBox1.Items.Clear()
foreach($x in $checkboxes) {
    $names = $x.name
    $chkStat = $x.Checkstate
    $status = $names+ " " +$chkStat
    $listBox1.Items.Add("$status")
    }
}
#end Click Event

$form1 = New-Object System.Windows.Forms.Form
$button1 = New-Object System.Windows.Forms.Button
$checkBoxes = New-Object System.Windows.Forms.CheckBox
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState

#region Generated Form Code
$Form1.Text = "VMWare VM Server Power On/Off"
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$Icon = [system.drawing.icon]::ExtractAssociatedIcon($PSHOME + "\powershell.exe")
$form1.icon=$icon
if($ServerCount -ge 6){
    $Form1ShapeW = (1000)
    if($ServerCount -ge 20){
        $Form1ShapeH = ($ServerCount * 35)/5
        } else {
        $form1ShapeH = (120)
    }
} else {
    $Form1ShapeW = 100 + (155 * $ServerCount)
}
$System_Drawing_Size = New-Object System.Drawing.Size($Form1ShapeW,$Form1ShapeH)
$form1.ClientSize = $System_Drawing_Size
$form1.autosize = $true
#endregion

$x=5
$y=30
$i=0
$FX=100
$FY=$y

#region CheckBoxes
    $Checkboxes = @()
    $VMfolders | %{
    $Checkboxes += New-Object System.Windows.Forms.CheckBox
    $Checkboxes[-1].useVisualStyleBackColor = $true
    $System_Drawing_Size = New-Object System.Drawing.Size(85,25)
    $Checkboxes[-1].Size = $System_Drawing_Size
    $Checkboxes[-1].text = $_.name
    if($x -ge 200 ) {
        $X = 5
        $Y = $y + 27
        $FY = $y
    }
    $System_Drawing_Point = New-Object System.Drawing.Point($x,$y)
    $Checkboxes[-1].Location = $System_Drawing_Point
    $Checkboxes[-1].DataBindings.DefaultDataSourceUpdateMode = 0
    $Checkboxes[-1].name = "folder"
    $y = $y + 27

#region CheckBoxesVM
    $VMList = $_.Group
    $CheckboxesVM = @()
    $VMList | %{
    $CheckboxesVM += New-Object System.Windows.Forms.CheckBox
        $System_Drawing_Size = New-Object System.Drawing.Size(150,25)
        $CheckboxesVM[-1].Size = $System_Drawing_Size
        $CheckboxesVM[-1].text = $_
        if($fx -ge 1000 ) {
            $FX = 100
            $FY = $FY + 25
        }
        $System_Drawing_Point = New-Object System.Drawing.Point($FX,$FY)
        $CheckboxesVM[-1].Location = $System_Drawing_Point
        $CheckboxesVM[-1].DataBindings.DefaultDataSourceUpdateMode = 0
        $CheckboxesVM[-1].name = "server"
        $FX = $FX + 155
        $form1.Controls.Add($CheckboxesVM[-1])
        $y=$FY + 27
    }
    $FX = 100
    $FY = $FY + 27
    #endregion checkboxesVM

    $form1.Controls.Add($Checkboxes[-1])
}
#endregion Checkboxes

#region Buttons & Boxes
$button1.TabIndex = 1
$button1.Name = "button1"
$System_Drawing_Size = New-Object System.Drawing.Size(75,23)
$button1.Size = $System_Drawing_Size
$button1.UseVisualStyleBackColor = $True
$button1.Text = "Run Script"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 25
$z = if($y -ge $FY){
    ($y + 27) }
else {
    ($FY + 27)
}
$System_Drawing_Point.Y = $z
$button1.Location = $System_Drawing_Point
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
$button1.add_Click($handler_button1_Click)
$form1.Controls.Add($button1)
$listBox1 = New-Object System.Windows.Forms.ListBox
$listBox1.FormattingEnabled = $True
$System_Drawing_Size = New-Object System.Drawing.Size(400,60)
$listBox1.Size = $System_Drawing_Size
$listBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$listBox1.Name = "listBox1"
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = ($x+100)
$System_Drawing_Point.Y = $y
$listBox1.Location = $System_Drawing_Point
$form1.Controls.Add($listBox1)
}
#End GenerateForm Function
#Call the Function
GenerateForm

A: From my Powershell GUI's, I run a function that checks the.checked state of boxes and radio buttons like this.
If ($CheckBox.Checked -eq $true){Write-Host "Do Something !"}

I call the function from the $CheckBox_CheckedChanged event, so that my gui is updated immediately.


text:
Q: Can we invoke smart phone's native share functionality with jquery? We can use phone's (android/ Iphones) native share functionality to share different content from apps. Is it also possible to invoke this share functionality through browser using javascript in all smart phones? So that on some event in browser, we can load share widget.
Thanks.

A: Yes now you can share it with Javascript for Android.
Follow link if you need more details or say thanks
https://sdtuts.com/javascript-android-native-share-popup-navigator-share-api/
async function AndroidNativeShare(Title,URL,Description){
  if(typeof navigator.share==='undefined' || !navigator.share){
    alert('Your browser does not support Android Native Share');
  } else {
    const TitleConst = Title;
    const URLConst = URL;
    const DescriptionConst = Description;

    try{
      await navigator.share({title:TitleConst, text:DescriptionConst, url:URLConst});
    } catch (error) {
    console.log('Error sharing: ' + error);
    return;
    }
  }
}

$(".share_button").click(function(){
  AndroidNativeShare('My Page Title', 'https://google.com','This is description');
});

A: For iOS/Android it is only possible if a UIWebView is opened within an app, but not from the native Safari/Chrome standalone browsers.
From in-app web view: How to Call Native Iphone/Android function from Javascript?

A: Not jquery per se but Chrome for Android and Android's native browser have support for this:
https://developer.chrome.com/multidevice/android/intents
Unfortunately the documentation is VERY limited as I'm trying to figure out how to share a link via the share dialog (giving the user the option to select which app to share the link with) myself.


text:
Q: Tracking user CPU hours I am looking to work out which users on our system are using the most CPU resources.
to check this?
So I would like to find out:

*

*CPU-hours this month, (and % of total)

*CPU hours this week, (and % of total)

*CPU hours ever, (and % of total)

For both real users and system processes


text:
Q: Extract a String out of a specific set of strings I have a text as:
sometext[string1 string2]someText
I want to retrieve string1 and string2 as separate strings from this text
How can i parse it in objective - c?

A: i have found the solution
  NSArray *arrayOne = [prettyFunctionString componentsSeparatedByString:@"["];
    NSString *parsedOne = [arrayOne objectAtIndex:1];

    NSArray *arrayTwo = [parsedOne componentsSeparatedByString:@"]"];
    NSString *parsedTwo = [arrayTwo objectAtIndex:0];

    NSArray *arrayThree = [parsedTwo componentsSeparatedByString:@" "];
    NSString *className = [arrayThree objectAtIndex:0];
    NSString *functionName = [arrayThree objectAtIndex:1];

thanks anyways

A: Maybe something like this could work for you
NSString * string = @"sometext[string1 string2]sometext";
NSString * pattern = @"(.*)\[(.+) (.+)\](.*)"

NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult * match = [expression firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];

if (match) {

    NSString * substring1 = [string substringWithRange:[match rangeAtIndex:2]];
    NSString * substring2 = [string substringWithRange:[match rangeAtIndex:3]];

    // do something with substring1 and substring2
}

A: You can Use this Simple Approach approach
NSString *str = @"sometext[string1 string2]someText";
NSInteger loc1 = [str localizedStandardRangeOfString:@"["].location;
NSInteger loc2 = [str localizedStandardRangeOfString:@"]"].location;
NSString *resultString = [str substringWithRange:(NSRange){loc1+1,loc2-loc1}];
NSArray *resultArry = [resultString componentsSeparatedByString:@" "];

result array will contain your required Reuslt

A: For completeness - if you are trying to extract strings out of a string with a known pattern, then an NSScanner is the way to go.
This goes through the string in one pass.
NSString *string = @"sometext[string1 string2]someText";
NSScanner *scanner = [NSScanner scannerWithString:string];

NSString *str1;
NSString *str2;

[scanner scanUpToString:@"[" intoString:nil]; // Scan up to the '[' character.
[scanner scanString:@"[" intoString:nil]; // Scan the '[' character and discard it.
[scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &str1]; // Scan all the characters up to the whitespace and accumulate the characters into 'str1'
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:nil]; // Scan up to the next alphanumeric character and discard the result.
[scanner scanUpToString:@"]" intoString:&str2]; // Scan up to the ']' character, accumulate the characters into 'str2'

// Log the output.
NSLog(@"First String: %@", str1);
NSLog(@"Second String: %@", str2);

Which puts the output into the console of:
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] First String: string1
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] Second String: string2


text:
Q: Is there any way to make a BASE URL which applies even if HREFs are "absolute"? I'm developing a website which will live on https://www.example.com/. While developing, and later as a test site, it's at http://127.0.0.1/temp-dir-for-my-project/.
This means that I currently have a bunch of hrefs in the HTML, as well as CSS files, starting with /temp-dir-for-my-project/, which obviously break once I'm done and upload it to the live site. Over there, it should be / instead.
Sadly, the BASE element, which I thought would solve this, only applies to relative paths. For example, ./meow.html with /temp-dir-for-my-project/ as the BASE would refer to /temp-dir-for-my-project/meow.html, but /meow.html in the same situation would be... /meow.html, because it's an "absolute" path.
Before you say "just use relative paths, then!", well... If I do that, I have to keep track of in which "dir" I am. For example, for the webpage at https://www.example.com/test.html, I could do: ./other.html and it would work both on the live site and in my test site (assuming the BASE is set). But the webpage at https://www.example.com/subdir/test.html would have to link to './../other.html' or else it wouldn't link to the correct page.
This gets messy. I wish I could use "absolute" paths and still have the BASE be the... base. Is there a way, or am I forced to use ./../../blabla... for any page located in subdirs (whether those be real subdirs or just how the URL is rewritten to look)?


text:
Q: $MATHS\times7=POISON$ where $MATHS$ is a prime Today, when I was doing a past paper for my upcoming competition, I found a interesting but hard problem:

In the equation below, each letter represents distinct digits from $0$ to $9$. $$MATHS\times7=POISON$$Where the five-digit number $MATHS$ is prime.
Find all the possible values of the $13$-digit number $MATHSISPOISON$.

I only knew that S was $1,3,7$ or $9$.
Thank You!

A: Since $1001=7\times 143$, multiplying the both sides of your equation
$$\overline{MATHS}\times7=\overline{POISON}$$
by $143$, we get
$$\overline{THS}\equiv \overline{SON}\times 143\pmod{1000}\tag1$$
Also, since we have $7\mid \overline{POISON}$ and $3\not\mid\overline{POISON}$, we get
$$2P+I\equiv 2S+N\pmod 7\tag2$$
$$P+I\not\equiv O-S-N\pmod 3\tag3$$
Also, since $\overline{MATHS}$ is a five-digit number, we see that $P\le 6$ and that if $P=0$, then $O\ge 7$.
Here, let us separate it into four cases.

Case 1 : $(S,N)=(1,7)$
From $(1)$, we have
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline
    O&0&2&3&4&5&6&8&9\\  \hline
    T&3&1&5&0&4&8&7&1\\  \hline
    H&0&6&9&2&5&8&4&7 \\\hline
\end{array}$$
implying $(O,T,H)=(3,5,9),(4,0,2)$.
If $(O,T,H)=(3,5,9)$, then from $(2)(3)$, we get $(P,I)=(4,8)$ and $\color{red}{62591\times 7=438137}$.
If $(O,T,H)=(4,0,2)$, then there is no $(P,I)$ satisfying $(2)(3)$.

Case 2 : $(S,N)=(3,1)$
From $(1)$, we have
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline
    O&0&2&4&5&6&7&8&9\\  \hline
    T&0&9&7&1&6&0&4&9\\  \hline
    H&4&0&6&9&2&5&8&1 \\\hline
\end{array}$$
implying $(O,T,H)=(2,9,0),(4,7,6),(7,0,5)$.
If $(O,T,H)=(2,9,0)$, then from $(2)(3)$, we get $(P,I)=(5,4)$ and $7\color{green}4903\times 7=52\color{green}4321$.
If $(O,T,H)=(4,7,6)$, then there is no $(P,I)$ satisfying $(2)(3)$.
If $(O,T,H)=(7,0,5)$, then from $(2)(3)$, we get $(P,I)=(4,6),(6,2),(6,9)$ and
$$\color{green}68053\times 7=47\color{green}6371,9\color{green}6053\times 7=\color{green}672371,\color{green}97053\times 7=67\color{green}9371$$

Case 3 : $(S,N)=(7,9)$
From $(1)$, we get
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline
    O&0&1&2&3&4&5&6&8\\  \hline
    T&3&8&2&6&1&5&9&8\\  \hline
    H&8&1&4&7&0&3&6&2 \\\hline
\end{array}$$
implying $(O,T,H)=(0,3,8),(4,1,0)$.
If $(O,T,H)=(0,3,8)$, then from $(2)(3)$, we get $(P,I)=(2,5),(6,4)$ and
$$\color{green}29387\times 7=\color{green}205709, \color{green}863\color{green}87\times 7=604709$$
If $(O,T,H)=(4,1,0)$, then from $(2)(3)$, we get $(P,I)=(2,5),(5,6)$ and
$$3\color{green}5107\times 7=24\color{green}5749, \color{green}7810\color{green}7\times 7=546749$$

Case 4 : $(S,N)=(9,3)$
From $(1)$, we get
$$\begin{array}{|c|c|c|c|c|c|c|c|c|c|c|c|c|c|} \hline
    O&0&1&2&4&5&6&7&8\\  \hline
    T&1&5&9&8&2&7&1&5\\  \hline
    H&2&5&8&4&7&0&3&6 \\\hline
\end{array}$$
implying $(O,T,H)=(0,1,2),(5,2,7),(6,7,0),(8,5,6)$.
If $(O,T,H)=(0,1,2)$, then from $(2)(3)$, we get $(P,I)=(4,6)$ and $\color{red}{58129\times 7=406903}$.
If $(O,T,H)=(5,2,7)$, then from $(2)(3)$, we get $(P,I)=(4,6)$ and $\color{green}65279\times 7=45\color{green}6953$.
If $(O,T,H)=(6,7,0)$, then there is no $(P,I)$ satisfying $(2)(3)$.
If $(O,T,H)=(8,5,6)$, then from $(2)(3)$, we get $(P,I)=(0,7)$ and $\color{red}{12569\times 7=087983}$.

Therefore, from the four cases above, we see that the answer is
$$\color{red}{6259181438137}\ \ (62591\times 7=438137)$$
$$\color{red}{5812969406903}\ \ (58129\times 7=406903)$$
$$\color{red}{1256979087983}\ \ (12569\times 7=087983)$$

A: As @JyrkiLahtonen noted, this may be hard to solve without a computer. Running this Python script tells us there are three solutions if $P=0$ is allowed (otherwise, only the last two are):

maths = 12569, poison = 087983, mathsispoison = 1256979087983
maths = 58129, poison = 406903, mathsispoison = 5812969406903
maths = 62591, poison = 438137, mathsispoison = 6259181438137


text:
Q: Laravel Eloquent Join Three tables together I have a table actors with CSV in one of the columns
id      | suburb                         | name
1       | Newport, Williamstown, Altona  | Stephen
2       | Seaholme, Footscary            | George

I have normalized the table into a different table actors_suburb
actor_id| suburb
1       | Newport
1       | Williamstown
1       | Altona
2       | Seaholme
2       | Footscary

I have a different table suburbs_near
 suburb   |  Council
 Newport  |  Hobson
 Footscary|  Hobson

I want to return all the actors in a council this is what I've tried
if (isset($input['council']) && $input['council'] != '')
        {

            $query = $query->join('actors_suburb', 'actors.id', '=', 'actors_suburb.actor_id')
                           ->join('suburb_near', 'actors_suburb.suburb', '=', 'suburb_near.suburb')
                           ->select(array('actors.*', 'actors_suburb.*', 'suburb_near.suburb' , 'suburb_near.council'))
                           ->where('council', 'like', '%'. $input['council'].'%')
                           ->orderBy('views', 'desc');
        }

But it is not returning any results when I put in ?council=Hobson, which should return some results.  Please help.

A: Apologies if this is incorrect, I would try a comment but I've not got the reputation yet. I'm only just learning Eloquent, but ren't you missing a ->get() or ->paginate(10)?
->orderBy('views', 'desc')->get();


text:
Q: Windows Hyper-V Debian going into Read Only mode I am running Debian 7.8 (wheezy) which is installed on a Windows Hyper-V server (not managed by me).  However, the server frequently goes into 'read only' mode and I am not sure why.  I have looked in dmesg but, to be honest, I do not know what I am looking at or for.  I ran fsck after reboot and there were errors e.g.
fsck died with exit status 4
...
Inotes that were part of a corrupted orphan linked list found. Fix
Inode <number> was part of the orphaned inode list. FIXED
...
Block bitmap differences: ....
Free blocks count wrong for group ...

After the reboot everything is ok.
Here is the output from dmesg after I ran fsck:
    [    5.951324] scsi scan: INQUIRY result too short (5), using 36
    [    5.951735] scsi scan: INQUIRY result too short (5), using 36
    [    5.951933] input: Microsoft Vmbus HID-compliant Mouse as /devices/virtual/input/input1
    [    5.952228] hid 0006:045E:0621.0001: input: <UNKNOWN> HID v0.01 Mouse [Microsoft Vmbus HID-compliant Mouse] on
    [    5.953338] hv_netvsc: hv_netvsc channel opened successfully
    [    6.057589] hv_netvsc vmbus_0_14: Device MAC 00:15:5d:00:fa:01 link state up
    [   10.954244] sd 2:0:0:0: [sda] 1006632960 512-byte logical blocks: (515 GB/480 GiB)
    [   10.954325] sd 2:0:0:0: [sda] Write Protect is off
    [   10.954330] sd 2:0:0:0: [sda] Mode Sense: 0f 00 00 00
    [   10.954539] sd 2:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
    [   10.956129]  sda: sda1 sda2 < sda5 >
    [   10.957221] sd 2:0:0:0: [sda] Attached SCSI disk
    [   11.311017] PM: Starting manual resume from disk
    [   11.311022] PM: Hibernation image partition 8:5 present
    [   11.311024] PM: Looking for hibernation image.
    [   11.311494] PM: Image not found (code -22)
    [   11.311497] PM: Hibernation image not present or could not be loaded.
    [   11.404052] EXT4-fs (sda1): mounted filesystem with ordered data mode. Opts: (null)
    [   12.562030] udevd[348]: starting version 175
    [   12.959687] input: Power Button as /devices/LNXSYSTM:00/LNXPWRBN:00/input/input2
    [   12.959696] ACPI: Power Button [PWRF]
    [   12.977694] hv_utils: Registering HyperV Utility Driver
    [   12.977698] hv_vmbus: registering driver hv_util
    [   13.080426] piix4_smbus 0000:00:07.3: SMBus base address uninitialized - upgrade BIOS or use force_addr=0xaddr
    [   13.083881] input: PC Speaker as /devices/platform/pcspkr/input/input3
    [   13.170434] alg: No test for __gcm-aes-aesni (__driver-gcm-aes-aesni)
    [   13.507475] trackpoint.c: failed to get extended button data
    [   16.708356] IBM TrackPoint firmware: 0x01, buttons: 0/0
    [   16.710497] input: TPPS/2 IBM TrackPoint as /devices/platform/i8042/serio1/input/input4
    [   19.075083] Adding 16773116k swap on /dev/sda5.  Priority:-1 extents:1 across:16773116k
    [   19.099050] EXT4-fs (sda1): re-mounted. Opts: (null)
    [   19.335774] EXT4-fs (sda1): re-mounted. Opts: errors=remount-ro
    [   19.412413] loop: module loaded
    [   20.685798] RPC: Registered named UNIX socket transport module.
    [   20.685802] RPC: Registered udp transport module.
    [   20.685811] RPC: Registered tcp transport module.
    [   20.685813] RPC: Registered tcp NFSv4.1 backchannel transport module.
    [   20.721997] FS-Cache: Loaded
    [   20.754261] FS-Cache: Netfs 'nfs' registered for caching
    [   20.763161] Installing knfsd (copyright (C) 1996 okir@monad.swb.de).
    [   23.477630] Bluetooth: Core ver 2.16
    [   23.477651] NET: Registered protocol family 31
    [   23.477653] Bluetooth: HCI device and connection manager initialized
    [   23.477656] Bluetooth: HCI socket layer initialized
    [   23.477658] Bluetooth: L2CAP socket layer initialized
    [   23.477849] Bluetooth: SCO socket layer initialized
    [   23.488920] Bluetooth: RFCOMM TTY layer initialized
    [   23.488926] Bluetooth: RFCOMM socket layer initialized
    [   23.488928] Bluetooth: RFCOMM ver 1.11
    [   23.496819] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
    [   23.496822] Bluetooth: BNEP filters: protocol multicast
    [   28.716625] postgres (3298): /proc/3298/oom_adj is deprecated, please use /proc/3298/oom_score_adj instead.
    [   41.096759] mtrr: type mismatch for f8000000,400000 old: write-back new: write-combining
    [   56.353460] hv_storvsc vmbus_0_1: cmd 0x85 scsi status 0x2 srb status 0x86
    [   56.353465] hv_storvsc vmbus_0_1: stor pkt ffff8801fbb0e2c0 autosense data valid - len 18
    [   56.353468] storvsc: Sense Key : Illegal Request [current]
    [   56.353472] storvsc: Add. Sense: Invalid command operation code

Any pointers to log files that I could look in would be greatly appreciated.

A: This might be occurring due to backups, please see https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1445195 for the related issue posted on the Ubuntu kernel.


text:
Q: Python waits for typing Im just 14 and pretty new to python. I want to make my program to wait for the user to type something (for example yes or no) and then react different depending on the answer. Im using Python 3 (3.4). Are there any simple ways to do this?

A: You can use input() function:
choice = input("Enter Yes or No: ")

But I would recomment you to read a book or Python tutorials first, which covers all you need to know to start in Python.

A: As per the other answers and comments, I would strongly suggest going through a Python tutorial.
But in answer to your question about getting user input and branching:
user_choice = input("Enter yes or no: ")
if user_choice == "yes":
    print("User entered 'yes'!")
elif user_choice == "no":
    print("User entered 'no'!")
else:
    print("Unknown value entered.")

A: Use the input() function. You should store it in a variable if you'd like to use the input later this way:
varname = input()

Or:
varname = input('Write your message here')

You'd better go through a python tutorial, check:
Invent With Python
Learn Python The Hard Way
Code Academy, Python


text:
Q: Ansible: I need to use a variable that is in a loop, and use each variable independently some assistance required if possible...
I have created users from a variable file:
"Users":
 - user1
 - user2
 - user3

I need to move files to the home directory of each user. I don't wish to do it like this, as it would mean writing an individual line for each user:
- name: Copy Playbooks
  copy:
    src: /etc/ansible/playbooks/file.yml
    dest: /home/user1/playbooks

Doing it like the below would mean ansible is trying to add to the home directory of {{ "user1" "user2" "user3" }}
- name: Copy Playbooks
  copy:
    src: /etc/ansible/playbooks/hands_on_ansible/hands_on_files/mount_nfs.yml
    dest: /home/{{ variable.get('Users') }}/playbooks

So what i need to do is add each individual variable to a different home directory using the variables file, which is a loop.
Have googled (obviously) but to no avail. All help is very much appreciated! :)

A: The type Users is list and it contains 3 items, you can find for information about YAML datastructure in the related Ansible documentation.
Basically you will want to iterate over the items in the list and apply your play Copy Playbooks for each one. This is a loop and you could do it like :
- name: Copy Playbooks
  copy:
    src: /etc/ansible/playbooks/hands_on_ansible/hands_on_files/mount_nfs.yml
    dest: "/home/{{item}}/playbooks"
  loop: "{{ variable.get('Users') }}"

A more accurate description of ansible loops can be found in the documentation.

EDIT : The above solution is for Ansible >= 2.5. As specified in the documentation :

Before 2.5 Ansible mainly used the with_<lookup> keywords to create loops, the loop keyword is basically analogous to with_list.

For Ansible versions < 2.5 the usual way of doing it would be :
- name: Copy Playbooks
  copy:
    src: /etc/ansible/playbooks/hands_on_ansible/hands_on_files/mount_nfs.yml
    dest: "/home/{{item}}/playbooks"
  with_items: "{{ variable.get('Users') }}"


text:
Q: Open new terminal tab and execute script I need to merge two osascript scripts, so that with one command I can open a new terminal tab and execute a script like echo hello into that new tab.
This one opens a new terminal tab.
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down'

This one opens a new window and runs echo hello
osascript -e 'tell app "Terminal" do script "echo hello" end tell'

A: The easiest way is by using "ttab"
https://www.npmjs.com/package/ttab
Just run ttab 'ls -la' here ls -la is the command that I want to execute in a new tab.
Note: ttab needs the installation of NPM

A: I don't know any better way to make a new tab, but you can run a command in the frontmost tab or window with do script "" in window 1.
tell application "Terminal"
    activate
    tell application "System Events" to keystroke "t" using command down
    repeat while contents of selected tab of window 1 starts with linefeed
        delay 0.01
    end repeat
    do script "echo a" in window 1
end tell

A: Here is a snippet we use. I would suggest:

*

*Put this into a function, like one called "tab"

*for the command use a variable that you pass into the function
osascript
    -e "tell application \"Terminal\" to activate" \
        -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
        -e "do script \"echo hello\" in front window" \
    -e "end tell"
    > /dev/null

A: Similar to adayzdone's answer, but slightly different:
osascript -e 'tell application "Terminal" to activate' \
  -e 'tell application "System Events" to keystroke "t" using {command down}' \
  -e 'tell application "Terminal" to do script "echo hello" in front window'

A: Try
osascript -e 'tell application "Terminal" to activate' -e 'tell application "System Events" to tell process "Terminal" to keystroke "t" using command down' -e 'tell application "Terminal" to do script "echo hello" in tab 2 of window 1'


text:
Q: Weibel IHA Exercise 1.2.4 About the Exercise 1.2.4

Suppose that $A.\xrightarrow{f} B.\xrightarrow{g} C.$
I know that $\ker{f}=\{\ker{f_n}\}$, $\mathrm{im}{f}=\{\mathrm{im} f_n\}$ are chain complexes of the abelian category $\mathcal{A}$, where $\ker\{f_n\}\xrightarrow{\ker{f_n}} A_n$ is the kernel of $A_n\xrightarrow{f_n} B_n$. $\mathrm{im} f_n=\ker(\mathrm{coker}{f_n})$ is defined similarly.
Then the sequence in $\mathbf{Ch}$ is exact at $B.$ $\iff$ $\ker{g}=\mathrm{im}{f}$
$\iff$ $\ker{f}_n=\mathrm{im}{f}_n$ for each $n\in\mathbb{Z}$
$\iff$ the sequence in $\mathcal{A}$ is exact at $B_n$ for each $n\in\mathbb{Z}$.
My question is, is this enough to prove this exercise? And if not, could you please help me to fill the gaps?


text:
Q: How to number points along a line consecutively I have a line and along this line I have different points which are max. 20m away from that line. Now I would like to number the points along the line, like shown in the grafic. Any suggestions how to achieve with QGIS or GRASS.

A: I would like to share an expansion to/variation to ike's answer (which was indeed suggested in the answer itself).
This can now be used directly within QGIS's DB manager (from QGIS 3.4.2 or QGIS 2.18.26 onwards - using SQLite3 3.25 per Giovanni Zezza's answer to my question here to make use of the row_number() or rank() window functions)
This query should allow you to renumber points:

*

*in a continuous sequence (or partitioned)

*based on the closest of multiple line features within 20 map units (changeable)

*ordered by line ID and then distance along line (in direction of line)

*even if the points are at the beginning/end of lines

The virtual layer gets updated immediately whenever you make even unsaved edits to the source point or line layers.
I haven't optimised the query, and in any case, performance can suffer with larger datasets so you should use the query directly in PostGIS instead for such situations.
Also, this hasn't been tested for multilinestring geometries.

Continuous numbering
WITH lines AS
   (SELECT geometry, lineid AS lineid FROM line_layer),

points AS
   (SELECT geometry, treeid AS pointid FROM point_layer),

located AS
  (SELECT points.geometry AS geometry,
          lines.lineid AS lineid,
          points.pointid AS pointid,
          ST_line_locate_point(lines.geometry,
          coalesce(ST_ClosestPoint(points.geometry, lines.geometry),
                   points.geometry)) AS theOrder,
          ST_distance(points.geometry, lines.geometry) AS dist
   FROM points
   INNER JOIN lines
   ON ST_Distance(points.geometry, lines.geometry) <= 20
   ORDER BY lineid),

located_closest AS
  (SELECT pointid,
          min(dist) AS mindist
   FROM located
   GROUP BY pointid)

SELECT located.*,
       row_number() OVER (ORDER BY lineid,
                                   theOrder) AS newid
FROM located
INNER JOIN
located_closest
ON located.pointid = located_closest.pointid
WHERE located.dist = located_closest.mindist

Partitioned numbering
As above but replace
   row_number() OVER (ORDER BY lineid,
                               theOrder) AS newid

with
   row_number() OVER (PARTITION BY lineid ORDER BY lineid,
                               theOrder) AS newid

Image comparisons (click to enlarge)
Original point data with lines:

Renumbered consecutively (L) and restarting with each new line (R) (PARTITION BY)
Note direction of line B1. Also, point 8 is snapped to the end of line A1:

Numbering instantly updated with unsaved edit to ID (C1 -> A3) (L) and unsaved edit to geometry (A1) (R):

A: This should probably get you pretty close to your goal:
SELECT  AID,
        BID,
        theOrder,
        rank() over (PARTITION BY AID order by theOrder asc) as rank
FROM    (
          SELECT  A."ID" AS AID,
                  B."ID" AS BID,
                  ST_line_locate_point(A."Shape", ST_ClosestPoint(A."Shape", B."Shape")) AS theOrder
          FROM    tiger."LINES"  AS A
                  INNER JOIN
                  tiger."POINTS"  AS B
                  ON  ST_Distance(A."Shape", B."Shape") <= 20
        ) AS X
        ORDER BY AID, rank;

This should rank your lines ascending by ID, with points then ascending by where they rank, and only using the points that are within 20 feet of the line.
I'd like to note here that if you have a point that is beyond an end or beginning point of a line, but still within 20 feet of the line, you will get multiple ranks of the same number (1 or n).  Should this be unwanted behavior, you will need to add distance to the line as a secondary ranking, or exclude ST_Line_Locate_Points of 0 AND 1.
If you want to include the possibility of points that fall exactly on the lines start or end points, then you would use ST_Distance = 0 (as a separate condition).

A: Reverse the operation interpolate desired ranges along segment edges. extrapolate integers from edge location via scripting, specify buffer range from edge, say 20 meters. Just an approach, not a specific answer.


text:
Q: Objective-C - Command line (clang) - print Stack Trace I would like to print the stack trace for my Objective-C program
I am compiling from the command line using clang (Automatic reference counting)
I would like to know the following:

*

*Do I have to add any parameters while compiling ?

*Do I have to add any code to start the trace and print the trace ?

Given below is a sample program for which I have to print the stack trace:
#import<Foundation/Foundation.h>

@interface Car : NSObject
@property (weak) NSNumber* doors;
@end

@implementation Car
@synthesize doors;
@end

int main()
{
    system("clear");

    Car *car1 = [[Car alloc] init];

    NSNumber *d1 = [[NSNumber alloc] initWithInteger: 4];

    //I want to start printing the stack trace from this point on
    car1.doors = d1;

    printf("---- end\n");

    return(0);
}

Command used to compile:
clang -fobjc-arc test.m -framework Foundation -o test

A: #include <execinfo.h>

void printStackTrace() {
    void *returnAddresses[500];
    int depth = backtrace(returnAddresses, sizeof returnAddresses / sizeof *returnAddresses);
    printf("stack depth = %d\n", depth);
    char **symbols = backtrace_symbols(returnAddresses, depth);
    for (int i = 0; i < depth; ++i) {
        printf("%s\n", symbols[i]);
    }
    free(symbols);
}


text:
Q: Rsync hangs / freezes when trying to sync a Symfony project via Windows XP My Symfony 1.3 project does not sync correctly with my SSH server.
I have cygWin and cwRsync installed and my local version of PHP is 5.2.11
I did not have any issues on any early versions of Symfony 1.0 but now my command line tools either hang with no response, or they close without letting me review the output of the script.
Has anyone else had this issue?
Thanks!

A: Find the sfProjectDeployTask.class.php file in your PEAR folder
For me it was here:
\php5.2.11\PEAR\symfony13\task\project

On line 162 find the code like this:
$command = "rsync $dryRun $parameters -e $ssh ./ $user$host:$dir";

and change it to read:
$command = "start cmd /k rsync $dryRun $parameters -e $ssh ./ $user$host:$dir";


text:
Q: Trouble Accessing scope variable in ng-template under script I am trying to design inline editing template using angular.I have followed this tutorial
http://blog.shubhamsaxena.com/creating-simple-inline-editing-with-angularjs/
My Code is

angular js code
$scope.getTemplate = function (admin) {
        if (admin.id === $scope.selected.id){
            $scope.template = 'edit';
        }
        else{
            $scope.template = 'display';
        }
        return $scope.template;
    };
    $scope.editAdmin = function (admin) {
        $scope.selected = angular.copy(admin);
    };

But when I run this it gives me 404 error in console
www.ip-address/dashboard/principal/display
"display" is my script id you can verify in the 1st snippet.
My question is why it is searching "display" id in the url.
scope variable admins has data but it do not accessed when I write under script.
Please help.

A: 404 means not found
 $scope.getTemplate = function (employee) {
        if (employee.empID === $scope.selected.empID){
            return 'edit';
        }
        else return 'display';
    };

getTemplate if the the Id already exist then it will open in Edit script or else will show in display script
HTMl


text:
Q: Когда скрываю меню, оно сначала дергается влево, а потом скрывается. Как пофиксить? Понял, что это из-за появления скролл-бара. Но как пофиксить, придумать не могу.
https://codepen.io/Anton-forntend/pen/zaRbYq/введите сюда код

A: Вам нужно задавать координаты меню от левой стороны экрана. Но задавать нужно явно в пикселях, а это значение мы можем получить только скриптом.
mainMenu.style.left = document.body.clientWidth + 'px';

https://codepen.io/anon/pen/KeoPOL


text:
Q: Spring boot Rest service Angular I have an application in front end i use angular and back end i use Spring boot.
In my front end i must upload a CSV file that insert data in tables.
So i send data to the backend which save it.
My problem: i have a class Individus with relation @OneToMany to others class like as comptes. So when i try to get All individus with this Rest service : http://localhost:8080/api/individus, i have a parsing json data error.
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:145) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:107) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25) ~[jackson-databind-2.9.6.jar:2.9.6]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:727) ~[jackson-databind-2.9.6.jar:2.9.6]

Here is my class Individus:
@Entity

public class Individu implements Serializable {
@Id
private String nui;
private int civility;
private String lastName;
private String useName;
private String firstName;
@Temporal(TemporalType.DATE)
@JsonFormat(pattern="dd/MM/yyyy")
private Date birthDate;
private String birthPlace;
private String birthCountry;
private String birthCountryLib;
private String nationality;
@OneToMany(mappedBy="individu", fetch = FetchType.LAZY)
private Collection<Compte> comptes;
@OneToMany(mappedBy="individu", fetch = FetchType.LAZY)
private Collection<Adresse> adresses;
@OneToMany(mappedBy="individu", fetch = FetchType.LAZY)
private Collection<Contact> contacts;
@OneToMany(mappedBy="individu", fetch = FetchType.LAZY)
private Collection<Iban> ibans;ode here

Is some one have a solution for me?

A: You didn't provide enough of the stacktrace to show what the actual error is, but I suspect that you're running into a problem with a circular graph, as the objects in your Individu class' collections (e.g. Compte, Ardresse) probably hold a reference to the parent Individu instance.
The solution in that case is to add a @JsonIgnore annotation to the children's references to the parent. This is most likely an attribute in the child that is currently marked with an @ManyToOne annotation.

A: this is another solution
public class Produit{.....
@ManyToOne(optional=false,fetch=FetchType.LAZY)
@JsonBackReference
private Category category;....}

public class Category{....
@OneToMany(fetch=FetchType.LAZY,mappedBy="category")
@JsonManagedReference
private Collection<Produit> produits;....}


text:
Q: Using a custom connection string for Code First Entity Framework Migration I have an application that can make a connection to a database.  There are many instances of this database use by numerous sites.  I want to use migration to update the database schema when the program loads.  I have got this working.
However, my connection string stored in app.config has been blanked out(by me)  And I use a connection string builder to take the users login details and server/database username/password and alter the connection string within the dbcontext to connect to their own database.
Eg.                  source.Database.Connection.ConnectionString "TrustServerCertificate=False;Encrypt=true;Integrated Security =" + integratedSecuity + ";data source=" + Server + ";initial catalog=" + Database + ";persist security info=true;"+ ";MultipleActiveResultSets=True;App=EntityFramework\" providerName = \"System.Data.SqlClient";

I have utilized a snippet from Stackoverflow to check for changes in my entity framework on program start.
Db = Internal_ConnectionTools.ChangeDatabase(Db, Txt_Database.Text, Txt_Server.Text, Txt_User.Text,Txt_Password.Text);
            LabDatabase LD = new LabDatabase(Db.Database.Connection.ConnectionString);
            Database.SetInitializer<LabDatabase>(
                new MigrateDatabaseToLatestVersion<LabDatabase, Configuration>());
            LD.Database.Initialize(true);

The problem I am having is that it keeps pointing back to the connection string in my App.config file and throwing an error that the Initial catalogue has not been defined.(because there is nothing defined by design)
If I fill the app.config connection string with my credentials, my database updates as expected.
How can I ensure that Entityobject.Database.Initialize() will use my updated custom string and update the users database instead of defaulting to the App.config string?

A: Ok, after a bit more digging I found the answer here
How do I set a connection string config programmatically in .net?
It describes and provides a method utilizing reflection to allow alteration of the connection string within an instance of App.config.
I have made some very small alterations to the original code to suit my purposes.
My amended method is below.
private void SpoofAppConfig(string connectionStringName, string connectionString)
    {
        var settings = ConfigurationManager.ConnectionStrings[connectionStringName];

        var fi = typeof(ConfigurationElement).GetField("_bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);

        fi.SetValue(settings, false);

        settings.ConnectionString = connectionString;
    }

This will not change anything within the actual app.config file.
Calling this method prior to migration will allow you to run migration with a custom connection string without the issues I was facing in the initial post.


text:
Q: Replacing contents of a .txt file with another .txt file (preserving original filename) Problem: I have a series of .txt documents in one directory and I want to replace the text with the text from a single .txt document – but I want to preserve the original document filenames.
I created this code (with a lot of research):
import os

data = open("source.txt")

for root, dirs, files in os.walk('Folder/'):
    for file in files:
        if file.endswith(".txt"):
             filepath = os.path.join(root, file)
             with open(filepath, 'r') as f:
                 text = f.read()
                 print('%s read' % filepath)
             with open(filepath, 'w') as f:
                 f.write(data.read())
                 print('%s updated' % filepath)

It works... but only for the first file in the directory. All the other files become empty (ie the original text is deleted but the new text isn't added).
Thanks in advance for you help

A: After calling data.read() the whole content of data was read. So calling data.read() again results in an empty string, as you are still at position EOF.
To re-read the content of data you need to change the file object's position by using the seek method:
import os

data = open("source.txt")

for root, dirs, files in os.walk('Folder/'):
    for file in files:
        if file.endswith(".txt"):
             filepath = os.path.join(root, file)
             with open(filepath, 'r') as f:
                 text = f.read()
                 print('%s read' % filepath)
             with open(filepath, 'w') as f:
                 f.write(data.read())
                 print('%s updated' % filepath)
                 # Set position back to beginning
                 data.seek(0)

A much simpler solution would be to store the content of data.read() in a variable, i.e. content which you can re-use when writing to the series of .txt documents. In that case you don't need to worry about the file`s position anymore.
# Read source.txt only once
with open("source.txt") as data:
    content = data.read()

for root, dirs, files in os.walk('Folder/'):
    for file in files:
        if file.endswith(".txt"):
             filepath = os.path.join(root, file)
             with open(filepath, 'r') as f:
                 text = f.read()
                 print('%s read' % filepath)
             with open(filepath, 'w') as f:
                 # Write content of variable content to file
                 f.write(content)
                 print('%s updated' % filepath)

With this you only read the content of your source.txt once and you can access it anytime by using your content variable.


text:
Q: PHP session variables not carrying over to my admin page once I redirect from login to admin page I have a Login Page; if username and password match with database will redirect to admin; but on admin page Iam not getting session variables.
first my login page:
<?php
session_start(); //Start the session
session_regenerate_id(true);
//print_r($_SESSION);
use Ct\Ct\Data\Data;
extract($_POST);
$eventlists = Data::getpassword();
foreach ($eventlists as $eventlist) {
    $get_list_username = $eventlist->user_name;
    $get_list_password = $eventlist->user_pass;
}
//echo $get_list_username.'outside';
if(isset($_POST['submit'])) {
    $your_name = $_POST['username'];
    $your_password = $_POST['password'];
    $_SESSION['usr'] = $your_name;
    $_SESSION['pwd'] = $your_password;
    //echo $_SESSION['username'];
    if($_SESSION['usr'] == $get_list_username && $_SESSION['pwd'] == $get_list_password) {
        print('');
    }
    else {
       echo 'Invalide username or password, please check again!   ';
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>Login Gun Page Update</title>

<form name="login" id="login" method="POST" action="">
     LOGIN

Username: <input type="text" size="100" name="username" id="username" value="" placeholder="UserName"/>

Password: <input type="password" size="40" name="password" id="password" value="" placeholder="Password"/>

<input type="submit" name="submit" id="submit" class="submit" value="Submit"/> <input type="reset" name="reset" id="reset" class="reset" value="reset"/>

</form>

then admin page:
<?php
session_start(); //Start the session
print_r($_SESSION);
if(!isset($_SESSION['usr']))      // if there is no valid session
{
    print('');
    //echo 'NOT working !!';
}
echo $_SESSION['usr'];
use Ct\Ct\Data\Data;
extract($_POST);
if(isset($save))
{
    Data::getupdate($ticketsavailable);
    print('');
}
$ticketleft = "";
$ticketleft = Data::getticketsavailable();
//print_r($ticketleft);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>update page</title>

<form action="" method="POST">
     UPDATE  TICKETS   Logout

     Update Number: <input type="textbox" id="ticketsavailable" name="ticketsavailable" value="<?php echo $ticketleft[0]->ticket_available; ?>"/>

  <input type="submit" name="save" value="Submit">
</form>

I have a Login Page; if username and password match with database will redirect to admin; but on admin page I am not getting session variables.
I did print_r($_SESSION); it shows empty on admin page. And I have started session on both page please help!!
please help I am not having time!!

A: my suggestion is
first you login then store username with some user access key in session ex.($_SESSION['username']=$username); and store user access in another session variable ($_SESSION['useraccess']="admin"); after login successfully, use this session for other webpage


text:
Q: html span tag in iphone webview how can i break the line in sapn tag. when line is big. I have used following code for that in iphone as webview.

                     Website Url:
                    %@

but when website url is longer so the screen no look like proper with alignment. so how can i manage the alignment in that case.
please reply

A: You could use
 tag but span is a inline element which means if you use
 it'll b considered as one line anyway.
Change span to a block element or add display:block to your class to solve the problem.


text:
Q: How do I define a relabel_config in prometheus that provides a default value? Say I have services that generally listen to port 8080.  I'd like to do it so if I specify
prometheus.port=1234

It uses 1234 as the instance port but if I don't specify it, I would get 8080 as the value I would set on the label
I am presuming it's something along the lines of
- source_labels: [__meta_dockerswarm_service_label_prometheus_port]
  regex: (\d+)
  target_label:  __port__
  replace: $1
  action: replace

A: - target_label:  __port__
  replacement: 8080
  action: replace

- source_labels: [__meta_dockerswarm_service_label_prometheus_port]
  regex: (\d+)
  target_label:  __port__
  replacement: $1
  action: replace

Then combined with the following to provide the port number for the service
- source_labels: [ __meta_dockerswarm_service_name ]
  target_label: service
  action: replace
- source_labels: [ __address__ ]
  target_label: __address__
  regex: (.+):(\d+)
  replacement: $1
  action: replace
- source_labels: [ __address__, __port__ ]
  target_label: __address__
  regex: (.+);(\d+)
  replacement: $1:$2
  action: replace


text:
Q: How to read/write a device's register connected to a gateway with pymodbus via TCP I have to read and write a sensor using pymodbus. I'm not directly connected to the sensor, but I'm connected via TCP to a gateway and the gateway is connected via serial to the sensor.
I established a connection with the gateway in this way:
client = ModbusClient("192.168.127.254", 502)
connection = client.connect()

The connection with the gateway works because the socket is open. But I can't read from the sensor in this way:
if connection:
    request = client.read_holding_registers(0x00, 8, unit=1)
    data = validator(request)
    print(data)

    request = client.read_holding_registers(0x00, 8, unit=1)
    data = validator(request)
    print(data)

    client.close()

How can I connect with the specify sensor connected to the gateway (id: 230, baud rate: 9600, parity: None, interface: RS-4852 wire)?
PS: The gateway is a Moxa MGate MB3170

A: First, you need to make sure of connection between Gateway and Modbus device.
After, you can get data and test data registers by modbus poll application.
Whenever your connection is established, it's time to coding...

A: First you should know about your modbus slave register tables(your sensor)
 and know about it functions codes if read function code is 0x3 you should use Read Holding Registers and if function code is 0x4 you should use Read Input Registers functions
after that you should find your require register address , ex:temp register address is 0x05 and number of bytes is 2 and your sensor id is  230 and requirement function code is 0x3
read_holding_registers(0x05 , 2, unit=230)


text:
Q: Installing Spotlite results in dependencies errors As a newby I am struggling to install downloaded packages. I got one since it is not in the ubuntu lib. called spotlite. I need help to get this 2.0 version installed and it is getting really very complicated with APT commands and so on. I am thinking this should be more simple, it is just an app package......
Anyone? Thanks beforehand!

A: According to the search on Repology this package is available only for ArchLinux. They mark this package as out-of-date since 2019-10-16. If you still need it, let's adapt ArchLinux PKGBUILD (or use zip-archive from Spotlite developers with debs directly) as follows on Ubuntu 18.04.5 LTS:
cd ~/Downloads
wget -c http://archive.ubuntu.com/ubuntu/pool/universe/o/openssl098/libssl0.9.8_0.9.8o-7ubuntu3.2.14.04.1_amd64.deb
wget -c http://www.spot-net.nl.vfcdn.net/downloads/spotlite/SpotLite%28v2%29Ubuntu.zip
unzip SpotLite\(v2\)Ubuntu.zip
sudo apt-get install ./libssl0.9.8_0.9.8o-7ubuntu3.2.14.04.1_amd64.deb ./spotlite-amd64.deb

For Ubuntu 20.04 LTS the problem is harder, it does not have Qt4. So we need to add special Qt4 PPA first:
sudo add-apt-repository ppa:rock-core/qt4
sudo apt-get update

and then unpack libssl0.9.8 and SpotLite to /usr/local as follows:
cd ~/Downloads
wget -c http://archive.ubuntu.com/ubuntu/pool/universe/o/openssl098/libssl0.9.8_0.9.8o-7ubuntu3.2.14.04.1_amd64.deb
dpkg -x libssl0.9.8_0.9.8o-7ubuntu3.2.14.04.1_amd64.deb libssl
sudo cp -arfv libssl/lib/x86_64-linux-gnu/* /usr/local/lib/
sudo cp -arfv libssl/usr/lib/x86_64-linux-gnu /usr/local/lib/
sudo cp -arfv libssl/usr/lib/* /usr/local/lib/
sudo cp -arfv libssl/usr/share/* /usr/local/share/

wget -c http://www.spot-net.nl.vfcdn.net/downloads/spotlite/SpotLite%28v2%29Ubuntu.zip
unzip SpotLite\(v2\)Ubuntu.zip
dpkg -x spotlite-amd64.deb spotlite
sudo cp -arfv spotlite/usr/bin/SpotLite* /usr/local/bin/
sudo cp -arfv spotlite/usr/local/share/* /usr/local/share/
sudo cp -arfv spotlite/usr/share /usr/local/

update-menus
sudo ldconfig
sudo apt-get install libaudio2 libmng2 libodbc1 libqt4-declarative libqt4-network libqt4-opengl libqt4-script libqt4-sql libqt4-sql-odbc libqt4-sql-sqlite libqt4-xml libqt4-xmlpatterns libqtcore4 libqtdbus4 libqtgui4 libqtwebkit4 qtcore4-l10n

And then use SpotLite as it was planned.


text:
Q: JMH start script -> e.g. set Iterations(5) When I start my Benchmark I will only have 5 warmupInterations, 5 measurementIterations and only 1 fork. I don't want to use the commandline options !
**my test code in Eclipse:**

package org.sample;

import java.util.concurrent.TimeUnit;

import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

public class MyBenchmark {

    @Benchmark @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS)
    public String[] testMethod() {
        return "1,2,3,4,5,6,7,8,9,10".split(",");
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(MyBenchmark.class.getSimpleName())
                .warmupIterations(5)
                .measurementIterations(5)
                .forks(1)
                .build();

        new Runner(opt).run();
    }

}

Then I say
mvn clean install
java -jar benchmark.jar

And I get the same ouput as always (no changed iterations or fork !!)
C:\Users\SPARK\Desktop\workspace\jmhBenchmark\target>java -jar benchmarks.jar
# JMH 1.11.3 (released 68 days ago)
# VM version: JDK 1.8.0_74, VM 25.74-b02
# VM invoker: C:\Program Files\Java\jre1.8.0_74\bin\java.exe
# VM options: <none>
# Warmup: 20 iterations, 1 s each
# Measurement: 20 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: org.sample.MyBenchmark.testMethod

# Run progress: 0,00% complete, ETA 00:06:40
# Fork: 1 of 10
# Warmup Iteration   1: 2108087,328 ops/s
# Warmup Iteration   2: 2435219,249 ops/s
# Warmup Iteration   3: 2589289,173 ops/s
# Warmup Iteration   4: 2606293,767 ops/s
# Warmup Iteration   5: 2548095,405 ops/s
# Warmup Iteration   6: 2594874,969 ops/s
# Warmup Iteration   7: 2583629,760 ops/s
# Warmup Iteration   8: 2579041,971 ops/s
# Warmup Iteration   9: 2580402,155 ops/s
# Warmup Iteration  10: 2546640,733 ops/s
# Warmup Iteration  11: 2580002,548 ops/s
# Warmup Iteration  12:

What I am doing wrong ??
Thanks a lot for reading

A: By executing java -jar benchmark.jar the tests are executed using the default JMH settings.
If you want to run the test using the settings specified by your OptionsBuilder. You have to run it as java -cp benchmark.jar org.sample.MyBenchmark.
Find a complete example below.
mvn archetype:generate \
    -DarchetypeGroupId=org.openjdk.jmh \
    -DarchetypeArtifactId=jmh-java-benchmark-archetype \
    -DgroupId=org.sample \
    -DartifactId=jmh-example \
    -Dversion=0.0.1 \
    -DinteractiveMode=false

Replace the file src/main/java/org/sample/MyBenchmark.java with your source.
executing java -jar target/benchamrks.jar use following settings
# VM options: <none>
# Warmup: 20 iterations, 1 s each
# Measurement: 20 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: org.sample.MyBenchmark.testMethod
...
# Fork: 1 of 10

executing java -cp target/benchmarks.jar org.sample.MyBenchmark use following settings
# VM options: <none>
# Warmup: 5 iterations, 1 s each
# Measurement: 5 iterations, 1 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Throughput, ops/time
# Benchmark: org.sample.MyBenchmark.testMethod
...
# Fork: 1 of 1


text:
Q: Passing a file path as a variable in SQL Server I'm trying to add a file to a file group in order to create a partition in SQL Server. When I pass in a hardcoded file path to the the filename, the code works. But when I use a variable for the file path, I get an error

Incorrect syntax near @FilePath or Unexpected symbol @FilePath

This is my code:
USE StudentRepository

BEGIN
    SET NOCOUNT ON;

    DECLARE @FilePath NVARCHAR(MAX) = "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\",
            @FileName NVARCHAR(MAX) = "FirstTerm2020",
            @FileExt NVARCHAR(MAX) = ".NDF";
    DECLARE @count INT = 0;

    ALTER DATABASE StudentRepository
    ADD FILE
    (
        NAME = 'FirstTerm2020',
        FILENAME = @FilePath + @FileName + @FileExt,  --Error here!
        SIZE = 5MB,
        MAXSIZE = 100MB,
        FILEGROWTH = 5MB
    )
    TO FILEGROUP  FirstTerm2020
END

When I pass a hardcoded file path to the filename, it works and creates the required partitions. as below
--Code omitted for brevity
FILENAME =  "C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\FirstTerm2020.NDF"  --No error!

Please I need some help. How do I pass a file path as a variable?

A: This is how I solved the problem. I create a dynamic sql and passed the filepath variable like this.

USE StudentRepository

BEGIN
    SET NOCOUNT ON;

    DECLARE @FilePath NVARCHAR(MAX) = 'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLEXPRESS\MSSQL\DATA\',
            @FileName NVARCHAR(MAX) = 'SecondTerm2022',
            @FileExt NVARCHAR(MAX) = '.NDF';
    DECLARE @count INT = 0;
    DECLARE @sql NVARCHAR(MAX) = '
    ALTER DATABASE StudentRepository ADD FILEGROUP ' + @FileName + ';

    ALTER DATABASE StudentRepository
    ADD FILE
    (
        NAME = '+ @FileName + ',
        FILENAME = ''' + @FilePath + @FileName + @FileExt + ''',
        SIZE = 5MB,
        MAXSIZE = 100MB,
        FILEGROWTH = 5MB
    )
    TO FILEGROUP  '+ @FileName
END

EXEC sp_executesql @sql

My major problem was that I was ommitting the three single quotes near @FilePath


text:
Q: Jupyter notebook is extremely slow suddenly after merging two python pandas dataframe.It is happening on both my mac and window I am working on my first data project for portfolio and I am trying to merge two pandas dataframes on datetime object. After merging two dataframes my jupyter notebook became extremely slow and took forever to re-run each cell. I am using git and github and It seems these are bit getting slow too.
I think I wrote the code in very inefficient way and this is my first project to apply internship and now I am so sad.. Please help....
https://github.com/Happydogs/Aurora_Policing_Project/blob/master/Aurora_Policing_Project.ipynb
I do have my code on github
Merging datasets
data.head()
data['date'] = pd.to_datetime(data['date'])
weather.head()
weather['DATE'] = pd.to_datetime(weather['DATE'])
weather['DATE'].head()
police_weather_data = pd.merge(left = data, right = weather, left_on =
'date', right_on = 'DATE', how = 'left')
police_weather_data.head()

I think I did something wrong. It is actually running, but after running the code, jupyter notebook is ridiculously and extremely slow.


text:
Q: Sony Action Camera Wowza Support We would like to use the Sony Action game to stream with our CDN. Is it possible to stream to a service other than Ustream. In particular our services uses Wowza which is a common internet streaming service.

A: Yes it's definitely possible! I'm streaming with my Sony ILCE-QX1 to my own Streaming Server over RTMP, so Wowza is also possible. It's possible to stream from all these Cameras(https://developer.sony.com/develop/cameras/) to any Streaming Server. I have also a working Live Stream from the new  Gopro4 ;)


text:
Q: How to hide UI elements from external applications? I'm developing an android app. I'm recording the screen using MediaRecorder and MediaProjection. But I need no external UI elements to be shown except the application UI elements when recording screen, like those like Messenger chat heads or others.
How can I achieve that to disable or hide external UI elements?


text:
Q: Unable to communicate to the required process opshubtfsservice. Because its already running ---------------------------
Error
Unable to communicate with the required process opshubtfsservice. Because it is probably not running. Restart application and try again.
OK
I have already so many times tried to restart the service and application as well but it couldn't. This problem occurring only in server.

A: Ref: https://stackoverflow.com/a/36170444/3627522
It seems that your machine is behind a proxy and all traffic in-out is being routed through it. (Including the communication of local traffic) You will have to bypass local addresses from the proxy as well as enable OVSMU to communicate through the proxy.
Please refer the C:\Program Files\OpsHub Visual Studio Migration Utility\Other_Resources\Resources\ProxyUtility.zip to configure OVSMU to utilize your proxy. There should be a user guide document which lists the steps.Keep the bypass local address value as default


text:
Q: Android Linear Layout Weight Programmatically I want to add three linear layouts to an activity programatically each of same width. the problem is i am not able to set the weights of these layouts programmatically. I could do this within xml, but I want to do this in program.
here is what I want:

A: Use new LinearLayout.LayoutParams(int width, int height, float weight) to set weights when setting layout params to the subviews

A: Here its the solution
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
    lp.weight = 1;

See Full Solution
LinearLayout ll1, ll2, ll3;
    /* Find these LinearLayout by ID
     i.e ll1=(LinearLayout)findViewById(R.id.ll1);
     */

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
    lp.weight = 1;
    ll1.setLayoutParams(lp);
    ll2.setLayoutParams(lp);
    ll3.setLayoutParams(lp);

A: Do this way..
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtNote = (LinedEditText) findViewById(R.id.txtNote);
    lnr = (LinearLayout) findViewById(R.id.lnr);
    LinearLayout l1 = new LinearLayout(this);
    LinearLayout l2 = new LinearLayout(this);
    LinearLayout l3 = new LinearLayout(this);
    l1.setBackgroundResource(android.R.color.holo_green_light);
    l2.setBackgroundResource(android.R.color.holo_orange_dark);
    l3.setBackgroundResource(android.R.color.holo_blue_bright);

    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT, 1);
    lnr.addView(l1, param);
    lnr.addView(l2, param);
    lnr.addView(l3, param);

}

A: You can do it by setting layout weight property for your individual linear layouts, pass it in LinearLayout - LayoutParams constructor:
LinearLayout.LayoutParams param = new LinearLayout.LayoutParam(
                         LayoutParams.MATCH_PARENT,
                         LayoutParams.MATCH_PARENT, 1);

or
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                         0,
                         LayoutParams.MATCH_PARENT, 1);

Hope it may help you !


text:
Q: String update in SQL Server Currently I have varchar field. The delimiter is "$P$P$".
The delimiter will appear at least once and at most twice in the varchar data.
Eg.
Sample Heading$P$P$Sample description$P$P$Sample conclusion

Sample Heading$P$P$Sample Description

If the delimiter appears twice, I need to insert a text before the second occurance of the delimiter.
Eg:
Sample Heading$P$P$Sample DescriptionINSERT TEXT HERE$P$P$Sample Conclusion

If the delimiter occurs only once, then I need to insert a text at the end of the field.
Eg:
Sample Heading$P$P$Sample DescriptionAPPEND TEXT HERE

How this can be done in SQL query?

A: If you are going to do a lot of string manipulation you might want to use a CLR (.net) function. Since SQL Server isn't exactly made for string manipulation.
Or even better, pull this data back to your application and do it in code.
I even think you can't do it using the default SQL Server String functions

A: The CharIndex function has an optional 3rd parameter that allows you to specify the starting position of the search.  You can use this to find the 2nd occurrence of a string using CharIndex. You can also use the stuff function to insert a string in to another string.
Example:
Declare @Temp Table(Data VarChar(8000))

Insert Into @Temp Values('Sample Heading$P$P$Sample description$P$P$Sample conclusion')
Insert Into @Temp Values('Sample Heading$P$P$Sample Description')

Select len(Data),
        CharIndex('$P$P$', Data + '$P$P$',CharIndex('$P$P$',Data) + 1),
        Stuff(Data + ' ', CharIndex('$P$P$', Data + '$P$P$',CharIndex('$P$P$',Data) + 1), 0, 'Text Here')
From   @Temp

I realize it looks like a mess, but I do encourage you to understand how this works because you may need something similar in the future.

A: instead of using delimiters, why not creating 3 columns or if you only want one --> an xml field?


text:
Q: How to scale vector data in R using min/max? Imagine I have a vector of values in R. It's super long but just do give you a sample:
[1] 2782.779 2781.655 2780.531 2779.407 2778.282 2777.898 2777.514
2777.130 2776.746 2776.471 2776.196 2775.921
[13] 2775.646 2775.055 2774.463 2773.872 2773.281 2774.238 2775.195
2776.152 2777.109 2776.905 2776.701 2776.497
[25] 2776.293 2775.658 2775.024 2774.389 2773.755 2774.214 2774.673
2775.132 2775.591 2777.585 2779.579 2781.574
[37] 2783.568 2787.358 2791.149 2794.940 2798.731 2802.518 2806.305
2810.092 2813.879 2814.760 2815.641 2816.522

I want to scale/normalize each value in the vector so it ranges between 0 and 1. The max value of the dataset would take on a value of 1 and the min value would take on a value of 0. Are there any existing functions/libraries to easily implement this?
Thanks!

A: Note that here, normalized values = (value-min)/(max-min). So try this:
v1 <- 1:100
v2 <- (v1-min(v1))/(max(v1)-min(v1))
v2

or just v2 <- scales::rescale(v1, to=c(0,1))


text:
Q: Failure failing in CATCH I'm probably overlooking something simple, but I do not expect the below code to fail. It is behaving as if I wrote die instead of fail in the catch block.
The Failure does not get properly handled and the code dies.
sub foo()
{
  try {
    say 1 / 0;
    CATCH { default { fail "FAIL" } }
  }

  return True;
}

with foo() {
    say "done";
}
else
{
  say "handled {.exception.message}"
}

Output:
FAIL
  in block  at d:\tmp\x.pl line 5
  in any  at d:\tmp\x.pl line 5
  in sub foo at d:\tmp\x.pl line 4
  in block <unit> at d:\tmp\x.pl line 11

A: To bring home to later readers the full force of what Yoda said in their comment, the simplest solution is to unlearn the notion that you have to try in order to CATCH. You don't:
sub foo()
{
  say 1 / 0;
  CATCH { default { fail "FAIL" } }
  return True;
}

with foo() {
    say "done";
}
else
{
  say "handled {.exception.message}"
}

correctly displays:
handled FAIL

A: According to the Failure documentation this seems to be the defined behavior.

Sink (void) context causes a Failure to throw, i.e. turn into a normal exception. The use fatal pragma causes this to happen in all contexts within the pragma's scope. Inside try blocks, use fatal is automatically set, and you can disable it with no fatal.

You can try to use the no fatal pragma.
sub foo() {
try {
    no fatal;
    say 1 / 0;
    CATCH { default { fail "FAIL" } }
  }
}

unless foo()  {
     say "handled"
}