text:
Q: Formatting a sharepoint workflow email table using HTML Tags I'm setting up a workflow email that takes values from a sharepoint form and then formats that email for users.
I've gotten everything working correctly, except for one part. When the email is sent out, the field that is being looked up doesn't get word-wrapped which then causes my emails(including the table) to expand straight across the screen.
Here's a snippet of the code. (Sharepoint 2013 Designer needs to have everything as one long string, which makes it a pain to edit. Probably run it through an online HTML editor to see what is going on)

<COLGROUP>
    <COL style="WIDTH: 192pt" width=256>

         Service ID
        [%Current Item:Service ID%]

        Order ID
        [%Current Item:Order ID%]

        Account ID
        [%Current Item:Account ID%]

        Change Type
        [%Current Item:Change Type%]

I used style="WORD-WRAP: break-word;" which works in sharepoint designer for pre-filled data but it doesn't work for the lookup values. I've looked around but i'm stumped.
Can anyone help me with this?


text:
Q: Select a column twice with different conditions from one table and using join with two other tables I will try to do this properly this time
So I have 3 SQL tables, Production,Resources,Asset and they look like this:
Asset:
ID     Name
------------
1     Line1
2     Line2
3     Line3

Resource:
ID   Asset_ID
------------
1      1
2      1
3      2
4      3
5      3

Production:
Resource_ID  Quantity    Type
------------------------------
1               5        Scrap
3               10       Scrap
1               6        Rework
3               3        Rework
1               15       Scrap

What I'm trying to is to get to this result:
Name   Scrap    Rework
-----------------------
Line1    20       6
Line2    10       3
Line3    0        0

Basically I need to grab each line name and then display the total scrap count and total rework count in the next two columns. Now I have done part of it, I have no problem getting what I need for either Scrap or Rework one at the time, where I get stuck is when I want to get both of them in one table in different columns.
I'm using the following right now:
SELECT a.ID, a.Name, d.Resource_ID, SUM(d.Quantity) [Scrap]
FROM Production d inner join SubResource r ON d.Resource_ID = s.ID
inner join Asset a ON a.ID = r.Asset_ID
WHERE Type = 'Scrap' group by a.ID, a.Name, d.Resource_ID

Which gives me:
Name   Scrap
------------
Line1    20
Line2    10
Line3    0

I know I need to sub-queries here(One to get scrap and one for rework) and I tried to do research on it but getting all these inner joins to work with the sub-queries confused the heck out of me.
I tried a few and I kept getting the total number of scraps and total number of reworks for ALL lines which clearly isn't correct.
I'd appreciate if someone can point me to the right direction. Thank you

A: The traditional cross tab / conditional aggregation version of a pivot() would be like so:
select
    a.id
  , a.Name
  , sum(case when [Type]='Scrap' then d.Quantity else 0 end) as [Scrap]
  , sum(case when [Type]='Rework' then d.Quantity else 0 end) as [Rework]
from Asset a
  left join Resource r
    on a.id = r.Asset_id
  left join Production d
      on d.Resource_id = r.id
     and d.[Type] in ('Scrap','Rework')
group by
    a.id
  , a.Name

test setup: http://rextester.com/LPMJB2638
returns:
+----+-------+-------+--------+
| id | Name  | Scrap | Rework |
+----+-------+-------+--------+
|  1 | Line1 |    20 |      6 |
|  2 | Line2 |    10 |      3 |
|  3 | Line3 |     0 |      0 |
+----+-------+-------+--------+

redpajama_set_name: RedPajamaStackExchange


text:
Q: add olark chat window to arbitrary url with chrome extension? I would like to make a chrome extension that includes adding an olark window to any webpage on click of the browser action button. olark customer support wasn't sure if this was possible but thought it might be. is there any reason why this wouldn't work?
I've been working on it using the
document.body.appendChild(script); method to add the olark snippet, is this a reasonable approach?


text:
Q: maven failsafe plugin. Copy resources In my project I have created the following directory structure
src
  -> main
       -> java
       -> resources
  -> test
       -> java
       -> resources
  -> integration-test
       -> java
       -> resources

In my pom.xml I have made following entry
        <plugin>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.17</version>
            <configuration>
                <testSourceDirectory>src/integration-test/java</testSourceDirectory>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

If i copy a resource in the src->test->resources it is copied successfully to /target/test-classes automatically. But if I copy a file into /src/integration-test/resources then it is not copied into the target/test-classes at build time.
How can I make the integration test also copy the files inside the resource into the target?

A: The integration-test goal of the maven-failsafe-plugin in by default bound to the integration-test lifecycle phase: http://maven.apache.org/surefire/maven-failsafe-plugin/integration-test-mojo.html. Therefore, since the integration-test phase comes way after the process-test-sources [1] (during which test sources are usually copied to the target directory) and because I assume what your are referring to by by "build time" is actually the Eclipse "Automatic build" feature, your integration test sources are not copied because Eclipse build stops at the test-compile lifecycle phase.
You should check out Maven lifecycle and how to map certains goal to lifecycle phases that fit your needs.
[1] https://maven.apache.org/ref/3.3.9/maven-core/lifecycles.html


text:
Q: Which circuit is better for low-noise, high-precision light sensing? Circuit #1:

Circuit #2 (R is small, and Vout is amplified using the same op amp in the above circuit, which is not included in the image below):

My voltmeter (an ADC) has a low input impedance (10k Ohms).

A: The first one (transimpedance amplifier) will have a much better high frequency response. If you want to reduce the high frequency response you can add a parallel capacitor across the feedback resistor.
The second will have frequency response limited by the photodiode capacitance.
Here is a TI application note on calculating noise in a transimpedance amplifier.
In the second case, you'll have an amplifier with voltage and current noise spectra and Johnson-Nyquist noise in the resistor.
There is also shot noise in the photodiode.

A: Circuit 1 with modification: You don't need to bias the photodiode with a -5V. Instead, connect it to ground. This will reduce dark current. Biasing the photodiode is only beneficial when you want higher bandwidths as it reduces the capacitance of the photodiode.


text:
Q: SQL Query in Excel gives "undefined function name" error I wrote a SQL query in MS Access that uses the MonthName function.  In access it works flawlessly.  I copied the exact SQL statement into an excel module that I frequently use to query databases.  When I run the query, excel keeps telling me that MonthName is an undefined function name.  If I remove the MonthName portion, the query runs fine.
It seems like I'm missing a reference or something... Right now, I'm referencing Microsoft ActiveX Data Objects Library 6.0.  Can anyone point me in the right direction?  Thanks
strSQL = "SELECT DISTINCT Customers.CustomerName, Employees.EmployeeName, [Policy data revised].EXDT, MonthName(Month([EXDT])) AS expMonth
          FROM (([Service Team table]
          INNER JOIN Customers
          ON [Service Team table].CustID = Customers.CustID)
          INNER JOIN Employees
          ON [Service Team table].EmployeeID = Employees.EmployeeID)
          INNER JOIN [Policy data revised]
          ON Customers.CustID = [Policy data revised].CustID
          WHERE ((([Service Team table].RoleExtension)='2.  Underwriting Assistant')
          AND (([Policy data revised].EXDT)
             BETWEEN #" & minExpDt & "# AND #" & maxExpDt & "#))
          ORDER BY [Policy data revised].EXDT ASC;"

A: The MonthName() function is only available for queries run within an Access application session.  See the "The following VBA functions won't work when called from a property sheet or used in an SQL statement" bullet point at About Microsoft Jet Expression Service sandbox mode.  Within an Access application session, the db engine can use the expression service to use that sandboxed function.
Since you can't use MonthName, try this Format expression instead.
Format([EXDT], 'mmmm') AS expMonth

A: Strange, I just tried the following code in Excel 2010 (64-bit) and it worked for me:
Sub foo()
'' Reference: "Microsoft ActiveX Data Objects 6.0 Library"
Dim con As ADODB.Connection, rst As ADODB.Recordset
Set con = New ADODB.Connection
con.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Gord\Desktop\Database1.accdb;"
Set rst = New ADODB.Recordset
rst.Open "SELECT MonthName(Month([BookingStart])) FROM Payment_tbl", con, adOpenStatic, adLockOptimistic
Debug.Print rst(0).Value
rst.Close
Set rst = Nothing
con.Close
Set con = Nothing
End Sub

Edit
Further to HansUp's comment, something must have changed between Office 2007 and Office 2010. I ran another test from a 32-bit machine running Office 2010 and the above code run against an Access 2000 .mdb file worked for me using both...
Provider=Microsoft.ACE.OLEDB.12.0;

...and...
Provider=Microsoft.Jet.OLEDB.4.0;

I also checked the SandBoxMode registry value under...
HKLM\Software\Microsoft\Office\14.0\Access Connectivity Engine\Engines

...and it is 3, which is the value for "Enabled" (ref: here).


text:
Q: NullPointerException in Clicking a row in JTable I want to activate a button if I click an empty 8th column in my Jtable. But I'm getting this:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at records$1.valueChanged(records.java:57)

Here's my code:
tb_records.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent event) {

                int row = tb_records.getSelectedRow();
                DefaultTableModel model = (DefaultTableModel)tb_records.getModel();
                String hehe = (String) model.getValueAt(row, 7);

                if(!hehe.equals("")) {
                    b_extend.setEnabled(false);
                }
                else {
                    b_extend.setEnabled(true);
                }
            }
        });

A: (not an answer, I'd be talking about simple way)

*

*change ListSelectionMode to SINGLE_...., then only one row can be selected, otherwise you have to loop inside array of selected rows

*test if (row > -1) == no row is selected, if passed then you can to

*for better help sooner post an SSCCE, short, runnable, compilable, with hardcoded value for JTable

A: I made few changes to your code, may be help.
.(new ListSelectionListener(){
            public void valueChanged(ListSelectionEvent e) {

            if (! e.getValueIsAdjusting() ) {
              ListSelectionModel d = (ListSelectionModel)e.getSource();
              if(d.getLeadSelectionIndex() != -1){
                   String hehe = (String) model.getValueAt(d.getLeadSelectionIndex(), 7);
                   b_extend.setEnabled("".equals(hehe));
              }
            }

            }
        });


text:
Q: Encryption for iOS 3des not same as android and .net I'm trying do some encrypt something using 3des on the iOS that must match the results from java and .NET.
Java code is :
public class EncryptionHelper {

// Encrypts string and encode in Base64
public static String encryptText(String plainText,String key, String IV) throws Exception {
    // ---- Use specified 3DES key and IV from other source --------------
    byte[] plaintext = plainText.getBytes();//input
    byte[] tdesKeyData = key.getBytes();// your encryption key

    byte[] myIV = IV.getBytes();// initialization vector

    Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
    IvParameterSpec ivspec = new IvParameterSpec(myIV);

    c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
    byte[] cipherText = c3des.doFinal(plaintext);
    String encryptedString = Base64.encodeToString(cipherText,
            Base64.DEFAULT);
    // return Base64Coder.encodeString(new String(cipherText));
    return encryptedString;
}

}
and iOS code for the same is :
-(NSString*)new3DESwithoperand:(NSString*)plaintext encryptOrDecrypt:(CCOperation)encryptorDecrypt key:(NSString*)key initVec:(NSString*)initVec
{

NSData* data = [plaintext dataUsingEncoding:NSUTF8StringEncoding];
const void *vplainText = [data bytes];;
size_t plainTextBufferSize = [data length];
NSLog(@"%@, Length: %u",[data description],[data length]);

size_t bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
NSLog(@"%zu, sizof of uint8_t: %zu",bufferPtrSize, sizeof(uint8_t));
size_t movedBytes = 0;
uint8_t *bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
NSLog(@"%zu",sizeof(bufferPtr));
memset((void*)bufferPtr, 0x0, bufferPtrSize);
NSLog(@"%zu",sizeof(bufferPtr));

const void * vkey = [[NSData base64DataFromString:key] bytes];
const void *vinitVec = [[NSData base64DataFromString:initVec] bytes];
NSLog(@"vinitvec: %@",[[NSData base64DataFromString:initVec] description]);

CCCryptorStatus ccStatus;
ccStatus = CCCrypt(encryptorDecrypt,
                   kCCAlgorithm3DES,
                   kCCOptionPKCS7Padding & kCCModeCBC,
                   vkey,
                   kCCKeySize3DES,
                   vinitVec,
                   vplainText,
                   plainTextBufferSize,
                   (void*)bufferPtr,
                   bufferPtrSize,
                   &movedBytes);

NSData* result = [NSData dataWithBytes:(const void*)bufferPtr length:(NSUInteger)movedBytes];
NSString* str = [NSString base64StringFromData:result length:result.length];
NSLog(@"%@",str);
return str;

}
This code successfully encrypts and decrypts a string. However, it does not match the results from .NET and java.
Thank you

A: Have found a solution for the above problem of encryption value generated different on iOS and .NET or Java.
Solution:
1. In Android and .NET you have to use a key of size 16 Bytes (eg: key="1234567890123456")
In iOS you need to use a key size of 24 bytes but the generation of key makes a little difference.
Use the same key as used in Android or .NET (16 bytes) and append it with the first 8 Bytes of the same key.
key16Byte = "1234567890123456"       //Android and .NET key
key24Byte = key16Byte + "12345678"   //ios and Java key, Replicated first 8 Bytes of 16Byte key
//new24ByteKey = "123456789012345612345678"

*Remove "& kCCModeCBC" from CCypher Mode.

*Some values require bytes in CCCrypt function which I have changed in the below mentioned code below. like keyData, encryptData.
Reason for different encryption generated:
Android and .NET - It takes 16Byte key and internally replicates, and generates a 24Byte key.
Java - It throws an Exception "Invalid key length", if you provide a 16Byte key value.
iOS - It generates encryption value with 16Byte and 24Byte both values without throwing any exception, so is the reason we get a different encryption generated in case of 16Byte key.
Java Code
public class EncryptionHelper {

// Encrypts string and encode in Base64
public static String encryptText(String plainText,String key, String IV) throws Exception {
   // ---- Use specified 3DES key and IV from other source --------------
    byte[] plaintext = plainText.getBytes();//input
    byte[] tdesKeyData = key.getBytes();// your encryption key

    byte[] myIV = IV.getBytes();// initialization vector

    Cipher c3des = Cipher.getInstance("DESede/CBC/PKCS5Padding");
    SecretKeySpec myKey = new SecretKeySpec(tdesKeyData, "DESede");
    IvParameterSpec ivspec = new IvParameterSpec(myIV);

    c3des.init(Cipher.ENCRYPT_MODE, myKey, ivspec);
    byte[] cipherText = c3des.doFinal(plaintext);
    String encryptedString = Base64.encodeToString(cipherText,
            Base64.DEFAULT);
    // return Base64Coder.encodeString(new String(cipherText));
    return encryptedString;
}

iOS Code:
- (NSString *)encrypt:(NSString *)encryptValue key:(NSString *)key24Byte IV:(NSString *)IV{
    // first of all we need to prepare key
    if([key length] != 24)
        return @"Require 24 byte key, call function generate24ByteKeySameAsAndroidDotNet with a 16Byte key same as used in Android and .NET"; //temporary error message

    NSData *keyData = [key24Byte dataUsingEncoding:NSUTF8StringEncoding];

    // our key is ready, let's prepare other buffers and moved bytes length
    NSData *encryptData = [encryptValue dataUsingEncoding:NSUTF8StringEncoding];
    size_t resultBufferSize = [encryptData length] + kCCBlockSize3DES;
    unsigned char resultBuffer[resultBufferSize];
    size_t moved = 0;

    // DES-CBC requires an explicit Initialization Vector (IV)
    // IV - second half of md5 key
    NSMutableData *ivData = [[IV dataUsingEncoding:NSUTF8StringEncoding]mutableCopy];
    NSMutableData *iv = [NSMutableData dataWithData:ivData];

    CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithm3DES,
                                            kCCOptionPKCS7Padding , [keyData bytes],
                                            kCCKeySize3DES, [iv bytes],
                                            [encryptData bytes], [encryptData length],
                                            resultBuffer, resultBufferSize, &moved);

    if (cryptorStatus == kCCSuccess) {
        return [[NSData dataWithBytes:resultBuffer length:moved] base64EncodedStringWithOptions:0];
    } else {
        return nil;
    }
}

iOS
-(NSString *)generate24ByteKeySameAsAndroidDotNet:(NSString *)key{
    NSString *new24ByteKey = key;

    ;
    new24ByteKey = [new24ByteKey stringByAppendingString:[key substringWithRange:NSMakeRange(0, 8)]];

    return new24ByteKey;
}

A: As @Jugal Desai mentioned, the key difference between iOS and Android/.Net is that the later ones automatically fill the key (with size  16 bytes) with another 8 bytes from the start of the key! You saved me :)
Here I provide the simple fix in Swift 3:
....

YOUR_KEY_SIZE_16 = YOUR_KEY_SIZE_16 + YOUR_KEY_SIZE_16[0...7]

....
Sample complete code (MD5 for key hash + ECB + PKCS7Padding) with base64 result:
func tripleDesEncrypt(keyString: String, pass: String) -> String{
    let keyData = keyString.data(using: .utf8)!

    var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in

        keyData.withUnsafeBytes {messageBytes in
            CC_MD5(messageBytes, CC_LONG(keyData.count), digestBytes)
        }
    }

    digestData = digestData + digestData[0...7]
    let data = pass.data(using: .utf8)!
    let dataNS = data as NSData

    let cryptData    = NSMutableData(length: Int(dataNS.length) + kCCBlockSize3DES)!

    let keyLength              = size_t(kCCKeySize3DES)
    let operation: CCOperation = UInt32(kCCEncrypt)
    let algoritm:  CCAlgorithm = UInt32(kCCAlgorithm3DES)
    let options:   CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)

    var numBytesEncrypted :size_t = 0

    let cryptStatus = CCCrypt(operation,
        algoritm,
        options,
        (digestData as NSData).bytes,
        keyLength,
        nil,
        dataNS.bytes,
        dataNS.length,
        cryptData.mutableBytes,
        cryptData.length,
        &numBytesEncrypted)

    if UInt32(cryptStatus) == UInt32(kCCSuccess) {
        cryptData.length = Int(numBytesEncrypted)

        // Not all data is a UTF-8 string so Base64 is used
        let base64cryptString = cryptData.base64EncodedString(options: NSData.Base64EncodingOptions.lineLength76Characters)
        return base64cryptString
    } else {
        print("Error: \(cryptStatus)")
    }
    return ""
}

A: How serious in decrypted?
- (NSString *)encrypt:(NSString *)encryptValue key:(NSString *)key24Byte IV:(NSString *)IV{
    // first of all we need to prepare key
    if([key length] != 24)
        return @"Require 24 byte key, call function generate24ByteKeySameAsAndroidDotNet with a 16Byte key same as used in Android and .NET"; //temporary error message

    NSData *keyData = [key24Byte dataUsingEncoding:NSUTF8StringEncoding];

    // our key is ready, let's prepare other buffers and moved bytes length
    NSData *encryptData = [encryptValue dataUsingEncoding:NSUTF8StringEncoding];
    size_t resultBufferSize = [encryptData length] + kCCBlockSize3DES;
    unsigned char resultBuffer[resultBufferSize];
    size_t moved = 0;

    // DES-CBC requires an explicit Initialization Vector (IV)
    // IV - second half of md5 key
    NSMutableData *ivData = [[IV dataUsingEncoding:NSUTF8StringEncoding]mutableCopy];
    NSMutableData *iv = [NSMutableData dataWithData:ivData];

    CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithm3DES,
                                            kCCOptionPKCS7Padding , [keyData bytes],
                                            kCCKeySize3DES, [iv bytes],
                                            [encryptData bytes], [encryptData length],
                                            resultBuffer, resultBufferSize, &moved);

    if (cryptorStatus == kCCSuccess) {
        return [[NSData dataWithBytes:resultBuffer length:moved] base64EncodedStringWithOptions:0];
    } else {
        return nil;
    }
}


text:
Q: WebView ignores attributes weight and height I'm trying to load html document to WebView via JSoup. Document has images:

I change width="1920" height="1080" to width="100%" height="auto" this way:
doc = Jsoup.connect("http://example.com/test").get();
                entryContent = doc.select("#content .entry-content");

                for( Element element : entryContent.select("img")) {
                    element.attr("width", "100%");
                    element.attr("height", "auto");
                    System.out.println(element);
                }

logcat shows that new attributes applied to all four images

But WebView ignores new attributes for second and third image. First image and the last one shows correct. Where can be problem?


text:
Q: ruby language syntax(how platform_info variable is used  class EncodeDemoTest < Test                      #inheritance in ruby
      def setup(platform_info, logdir)
        @telnet_ip                  = platform_info["telnet_ip"]
        @telnet_login               = platform_info["telnet_login"]
        @telnet_password            = nil
        @filesys_path               = platform_info["filesys_path"]
        @host_files_path            = platform_info["host_files_path"]
        @host_machine_ip            = platform_info["host_machine_ip"]
        @linuxserver_ip             = platform_info["linuxserver_ip"]
        @target_prompt              = platform_info["target_prompt"]
        @demo_execuable_path        = platform_info["demo_execuable_path"]
        @mts4ea_machine_ip          = platform_info["mts4ea_machine_ip"]
        @mts4ea_files_path          = platform_info["mts4ea_files_path"]
        @ffmpeg_machine_ip          = platform_info["ffmpeg_machine_ip"]
        @ffmpeg_service_machine_ip  = platform_info["ffmpeg_service_machine_ip"]
        @ffmpeg_files_path          = platform_info["ffmpeg_files_path"]
        @ffmpeg_login               = platform_info["ffmpeg_login"]
        @ffmpeg_password            = platform_info["ffmpeg_password"]
        @ffmpeg_prompt              = platform_info["ffmpeg_prompt"]
        @platform_info              = platform_info

could anyone tell me how argument passed in setup method .means what does that syntax means platform_info["telnet_ip"]

A: It looks like platform_info is intended to be a Hash.
setup would be called with something like setup({'telnet_ip' => 'value'}, 'logdir_value') and platform_info["telnet_ip"] would then return the value from platform_info for the key "telnet_ip".
Update
Given the code:
@board = Target::TelnetClient.new "192.168.247.68", "root",
  @telnet_password, logdir + "/log.txt"
app = Target::EncodeDemoApp.new() app.setup(@board, @demo_execuable_path)

it looks like @board is not a Hash but is a Target::TelnetClient which must have a [] method that makes it behave like a Hash.
If you want to find out what class something is you can use the class method e.g. you can put in your program:
puts "@board is a #{@board.class}"
puts "@demo_executable_path is a #{@demo_executable_path.class}"

For @board, to see what values it contains (telnet_ip, telnet_login etc) you could try:
puts @board.keys.inspect

Finally, to see the methods that an object provides you can use public_methods e.g.
puts @board.public_methods.inspect


text:
Q: RegEx matching standalone string with dashes I need to write a RegEx to match the "1-234-5678" string if there are no dash characters around it.
I have the following RegEx:
\b\d\-\d{3}\-\d{4}\b

Now this works fine and matches "1-234-5678" correctly in the strings below:

*

*text 1-234-5678 text

*111 1-234-5678 1212

The RegEx also correctly NOT matches "1-234-5678" in the strings below:

*

*text1-234-5678text

*1111-234-56781212

But the problem is that it also matches in the following strings:

*

*text-1-234-5678-text

*111-1-234-5678-1212

It's because \b matches before and after the dashes.
How can I eliminate matches if there's a dash in front or after the data?

A: Use a negative lookbehind and negative lookahead to check whether the above mentioned format is not preceded and followed by a - symbol,
(?<!-)\b\d\-\d{3}\-\d{4}\b(?!-)

DEMO


text:
Q: Ruby Replacing Parts of String I have this String
s = "03:23 PM on 09/04/12"

I want to take out the ' on ' and replace it with just a space ' '.  I thought the string's gsub method, along with regex, would be the best solution.  I am just not sure why this wont work.
s ="03:23 PM on 09/04/12"
s.gsub(/ on /, ' ')
puts s
#=> "03:23 PM on 09/04/12"

A: A string's gsub method returns the modified string and leaves the object string alone. If you want to modify the object in-place then you have to use gsub!.
Also, if you want to change only one occurrence then sub is probably your best bet.
So
s = "03:23 PM on 09/04/12"

s = s.sub(' on ', ' ')

or
s.sub!(' on', ' ')

A: works fine for me... Perhaps you meant to use gsub!?
>> s ="03:23 PM on 09/04/12"
=> "03:23 PM on 09/04/12"
>> s.gsub(/ on /, ' ')
=> "03:23 PM 09/04/12"
>> s.gsub!(/ on /, ' ')
=> "03:23 PM 09/04/12"
>> s
=> "03:23 PM 09/04/12"

A: You are not required to use a Regexp object for the gsub parameter (/ on /)  you can also use a string - this worked for me!
s = "03:23 PM on 09/04/12"

p s.gsub " on ", " "
#=> "03:23 PM 09/04/12"

A: s ="03:23 PM on 09/04/12"
s.gsub(' on ', ' ')
#>> "03:23 PM 09/04/12"

You can go without regex in this case,but if you want to use regex,then use s.gsub!(/ on /, ' ')


text:
Q: Detect IE in expressjs, but can't get static files I've tried to detect IE by using expressjs, the code surely redirect me to the error page.
But the problem is that it won't render css files and get image files in my folder.
I think the problem is that expressjs redirect to error_page before the static path is set.
So I put app.all('*', ieRedirecter);, after
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'));

The problem is still occur... could someone help me out, thanks!
My settings
function ieRedirecter(req, res, next) {
  if(req.headers['user-agent'].indexOf("MSIE") >= 0) {
    var myNav = req.headers['user-agent'];
    var IEbrowser = parseInt(myNav.split('MSIE')[1])
    if(IEbrowser < 9) {
      res.render('error/browser_error', {title : 'not supporting your browser'})
    } else {
      next();
    }
  } else {
    next();
  }
};

app.configure(function(){
    app.set('port', process.env.PORT || 3000);
    ...
    ...
    ...
    app.use(app.router);

    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.static(__dirname + '/uploads'));

    app.all('*', ieRedirecter);
})

A: This order doesn't work:

app.use(app.router);

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'));

app.all('*', ieRedirecter);

app.router is the middleware that handles all your routing requests, including app.all(), even though you declare that route after your other middleware (fun fact: at any moment you declare a route – using app.{get,post,all,...} – the app.router middleware is inserted into the middleware chain automatically).
If possible, the easiest solution would be to move the static and IE middleware to before your routes (but I realize that might cause problems with your application setup):
// static middleware first...
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(__dirname + '/uploads'))

// ...followed by the IE check
app.use(ieRedirecter);

// ...followed by your routes
app.get('/', ...);
...

Another solution would be filter out requests for static resources in your ieRedirecter middleware  by looking at req.path, but that assumes that you can easily identify those requests (like if they start with /css or /js).


text:
Q: SOLR backup status request not found I have been trying to figure out a way that I know when the SOLR backup is done and its status. We have a lot of collections that we are trying to backup. The request has an error
status={state=notfound,msg=Did not find [requestId123] in any tasks queue}
When I looked at the SOLR source code, I realized that the status is reported from the request status in the overseer queue i.e. COMPLETED,FAILED,RUNNING,SUBMITTED is based on the overseer queue. When the request in not found in the overseer queue or when the queue is cleared then we get this error.
My question is there any other way to get the SOLR backup status reliably.
Thanks

A: Taking backup
I am not sure how you are running the process for a backup (nor where you can see that error). My assumption is that you are checking logs (because it looks like a similar message which will appear in logs).
Additionally you did not mention which solr version you are using. I will elaborate the answer bellow for 8.9 (but any version which supports v2 AND v1 api should work similar).
If you want to run backup asynchronously you can use following:
curl -X POST http://localhost:8983/api/collections -H 'Content-Type: application/json' -d '
      {
        "backup-collection": {
          "name": "openaccess-v26-backup",
          "collection": "openaccess-v26",
          "location": "/var/solr/mounted-efs-backup",
          "async": "1000"
        }
      }
    '

This will start async process for a backup with track id 1000.
Checking action status
You can use following to check the status of the process:
curl 'http://localhost:8983/solr/admin/collections?action=REQUESTSTATUS&requestid=1000'

This will return response like this:
{
  "responseHeader":{
    "status":0,
    "QTime":3},
  "status":{
    "state":"running",
    "msg":"found [1000] in running tasks"}}

Additionally, this is the way to check all of the actions (not only backup). For example, using the same way you can check status of RESTORE action if you are restoring your backup into the solr collection.
Listing backups
It seems that relevant info as well can be to try to list backups from time to time and see is the backup within your list (if above approach is not working for you).
Please make a note that I am not 100% sure is there a possibility for backup to be listed if its not completed, but based on my testing and pure empirical approach seems that this is not the case.
So, if I start backup, and try to execute an api which is going to give me a list of all of the backups, I will get empty list for example:
curl -X POST http://localhost:8983/v2/collections/backups -H 'Content-Type: application/json' -d '
{
  "list-backups" : {
    "name": "openaccess-v26-backup",
    "location": "/var/solr/mounted-efs-backup"
  }
}'

{
  "responseHeader":{
    "status":0,
    "QTime":165},
    "backups":[]
  }
}

However, if you execute this after a while (when backup is completed), the response will be in a following format:
{
  "responseHeader":{
    "status":0,
    "QTime":14},
  "collection":"openaccess-v26",
  "backups":[{
      "indexFileCount":0,
      "indexSizeMB":0.0,
      "shardBackupIds":{
        "shard2":"md_shard2_0.json",
        "shard3":"md_shard3_0.json",
        "shard1":"md_shard1_0.json"},
      "collection.configName":"openaccess-v26",
      "backupId":0,
      "collectionAlias":"openaccess-v26",
      "startTime":"2022-07-05T08:34:53.703175Z",
      "indexVersion":"8.9.0"}]}

This kind of approach works fine for the 8.9 version of solr im using with apiv2.
I was able to restore and use backups without any kind of issues after they are listed.


text:
Q: Can't update the state after getting the data from API initial state is:
 const [state, setState] = useState({
    priceType: 0,
    recurrenceType: 0,
    start_date: '',
    end_date: '',
    minCapacity: 0,
    maxCapacity: 0,
    price: 0,
    min: 0,
    max: 0,
    days: []
});

data which I want to update,
SpecialPriceEditData
I am trying in this way;
  useEffect(() => {
    {
        if (SpecialPriceEditData !== null) {
            setState(SpecialPriceEditData)
        }
        setState({ ...state });
    }
}, [SpecialPriceEditData]);

But state not getting update,
How to achive this
Thank you..

A: use this:
  useEffect(() => {

        if (SpecialPriceEditData !== null) {
        setState({...state , ...SpecialPriceEditData})
        }

  }, [SpecialPriceEditData]);

A: WARNING: The content below base on the guess that SpecialPriceEditData is merely a props. If it's not true, I will modify my answer.
According to your code, you will always call setState({...state}) inside useEffect regardless of SpecialPriceEditData is null or not ;
And because setState is not sync, and the state value is merely closure for useEffect, the state inside useEffect will always remain the original value, so after you call  setState(SpecialPriceEditData), the state will not change, and then you call setState(state), the previous state chang request will be ignored by React at next render, keep all the same at last ;
And I guess you want to apply all SpecialPriceEditData to state when SpecialPriceEditData is valid, so you can try:
  useEffect(() => {
    {
        if (SpecialPriceEditData !== null) {
            setState(SpecialPriceEditData)
        }
    }
}, [SpecialPriceEditData]);


text:
Q: How to detect if there're more than one html tags in web page We have an aspx page that is embed in an external application, and we recently found they inserted an extra html tag in the page for some cookie reason. There is no way they can remove the tag or fix the problem. I would think if there's any way that I can detect the injected extra html tag from my side so we can do something specific for it.
The final page would look like this:
<!--Here is the injected stuff-->
<html>
    <body onfocus="document.cookie='blahblahblah'"></body>
</html>
<!--Below is our original markup-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <body>
      Some content
    </body>
</html>

I have tried use jQuery selectors and JavaScript document.querySelectorAll to select all the html/body tags but look like they can only find the html/body tag in original markup. They're like
$(function(){
  if($('html').length > 1)
    //Do something
  else if(document.querySelectorAll('html').length > 1)
    //Do something
});

None of these worked. They always return length = 1 while the browser is giving the following warning message:

HTML1502: Unexpected DOCTYPE. Only one DOCTYPE is allowed and it must occur before any elements.
  HTML1513: Extra "<html>" tag found. Only one "<html>" tag should exist per document.

I am wondering if there's any way that I can find this extra tag using JavaScript or can I simulate what the browser did to detect this extra tag.
Thanks for help.

A: I think it's not possible to do that in native Javascript, because the Html DOM Tree can have only one Html tag and it's a convention.
I think you can do this using a serverSide language.
Something like this.
$(document).ready(function(){
    $.ajax({
        url: 'yourscript.yourTechno',
        method: 'GET'
    }).done(function(result){
        alert('you have '+result+ 'html tags');
    })
})

On the server side (with PHP and a dom parser for example)
$count = 0;
$html = file_get_html('http://www.myWebSite.com/myPageToParse.html');
foreach($html->find('html') as $element){
    $count ++;
}
echo($count);

http://api.jquery.com/jquery.ajax/
http://simplehtmldom.sourceforge.net/


text:
Q: Visual Studio 2017 Suggestion List only showing Snippets PROBLEM

I'm on Windows 10 (November TH2 build) using Visual Studio 2017 v15.1.26403.7, and I'm not sure whether this problem happens in earlier releases but I noticed that the only way to show snippets in the suggestion list in both C# and VB.NET text editors is by enabling this option:

However, the weird problem is that after the option is activated, IntelliSense brokes and it only show snippets:

...as you can see, there is ANY other kind of built-in member suggestion, just snippets, so time-saving programming using IntelliSense is totally lost.
QUESTION

I'm missing something?, it is a bug or is my configuration wrong?. Is there any way I can set the damn intellisense behavior to show normal suggestions plus snippets?, I mean these normal suggestions:

...plus snippets.
This is my settings file for Visual Studio 2017 (you can import it in your Visual Studio to test it):
http://www.mediafire.com/file/5g2w8j9f6floj19/CurrentSettings.vssettings

A: Thank you for your feedback and I tested it on my side with the same VS version, but my result has little differences as yours. Enable 'Always include snippets' for both C# and Basic and save it, then type 'm' in the *.vb file or *.cs file, the List members only display sinppets in the *.vb file and display normally in the *.cs file, please check the following screenshot:

I have already reported this issue to the VS Product Team, please see this: VS 2017 (version: 26403.7): Enable Tools>Options>Text Editor>Basic>Intellisense>Always include snippets and the list members only display the snippets, not includes other types
You can vote it and add a comment, then please pay patiently to waiting for the response from the VS Product Team Engineers. Sorry for this inconvenience and thank you for your understanding.


text:
Q: visual studio, want to add reference assembly websocket from system.net.websockets .net framework Am using Visual Studio Community 2017.
Trying to reference .net framework Websockets, link below.
https://learn.microsoft.com/en-gb/dotnet/api/system.net.websockets?view=netframework-4.5
Though am unable to find this file from Nuget, or from `

C:\Program Files (x86)\Reference
  Assemblies\Microsoft\Framework.NETFramework\v4.5

`
Should I be downloading the raw dll file and to add to the local folder?
Please help I am stuck and just want to use the microsoft APIs, and wondering why is microsoft API so tough to use...
EDIT 1:
After some further testing with help of friends of stack overflow, I realised some mistakes that I had which led to my miscommunication of question.
Firstly, whilst browsing through the object browser in Visual Studio, the reference assembly packages would show the functions within, however when I reference the packages from Nuget, none of the functions appear, wherein I thought that the package was not loaded.
However, it has actually been loaded already and will work, I just required to set the target framework to 4.6.0 such that it works with the nuget package linked by accepted answer.

A: Websocket is already available here ,you just need to install this package by going
tools > nuget package manager > Package Manager Console

Install-Package System.Net.WebSockets -Version 4.3.0


text:
Q: Is there a way of keeping a SSE connection but not run any code? So basically I'm working with a server in PHP and client in JS and I need to implement a way of sending updates to clients.
There's a long polling that we want to replace for something more efficent so we were thinking in SSE but I want to send the data to a specific client after I do an INSERT into the database in a specific action.
So I have some questions about it

*

*Do I need to connect the EventSource from the client to the action that makes the INSERT to have access to it from there?

*It is possible to connect the EventSource to some action and not run the code in it?

Because I'll like to have the connection available to send data after the INSERT but I don't want to run the code every time the EventSource reconnect. Is any of this possible or should I use some other technology like WebSocket?
Thanks and sorry if my english sucks. Hope you understand my question.

A: Your SSE connection in PHP is a dedicated process (for each client). There has to be code there, but in your case it will be as simple as hanging around waiting for a signal that the INSERT has happened.
This is all likely to be identical to how your current long poll solution works?

There's a long polling that we want to replace for something more efficent
...
should I use some other technology like WebSocket?

It depends on in what way long poll is inefficient, but I'd expect the bottlenecks to not change.
SSE is really just a HTML5 standard, wrapped around how long poll works. And WebSocket is the same, except it is two-way (and trading more flexiblity for more complexity). In all three cases you are keeping a dedicated socket open (*), and there has to be a process on the server handling that connection.
*: Less of an issue with http2 multiplexing.


text:
Q: Yandex Maps, расстояние между двумя точками на PHP Для Yandex Maps данный метод существует только в JS API, подскажите пожалуйста как реализовать на PHP?
https://tech.yandex.ru/maps/doc/jsapi/2.0/ref/reference/ICoordSystem-docpage/#getDistance
Быть может возможно получить как то ответ через XML-запросы?

A: Вобщем от Яндекса буду использовать только координаты.
Решение здесь
https://www.kobzarev.com/programming/calculation-of-distances-between-cities-on-their-coordinates/


text:
Q: WPF, can you get the default windows colors? Okay here is a softball beginner WPF question.
By default the background of the window is white.  I'm trying to hack in an error reporting form and I want to emulate the more standard windows look and feel.
Any easy way to grab the default color for the background?

A: Using the SystemColors class and specifically the WindowColor property. When using xaml it is better to use DynamicResources and therefore use the ...Key properties. That way your application changes in the fly when the user changes the color in Windows.
<Window>
  <Window.Background>
    <SolidColorBrush Color="{DynamicResource {x:Static SystemColors.WindowColorKey}}">
    </SolidColorBrush>
  </Window.Background>
</Window>

Using the ...BrushKey properties makes it easier to use when in need of a brush
<Window Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
</Window>

PS: WPF Windows should already have the correct color by default


text:
Q: Generate number in certain range from current date of device in Swift 3 I am looking for solution in Swift 3 where my app will generate random number from current date in the range <0;1000>.
For example I would love to get something like this:
14/2/2017 -> 323
15/2/2017 -> 25
16/2/2017 -> 898
...

If I remember right in Java I was able to generate same number each time by using certain seed in my random number generator which allowed me to generate same number all the time. I was thinking about using value of year+month+day as the seed to generate same number for all the users that will use app at the same day.
Java:
seed = currentYear + currentMonth + currentDay
Random generator = new Random(seed);
double random = generator.nextDouble();
...

Please help me to solve that problem in Swift 3, I have tried to go through all arc4random and other random functions and I didn't found any solution.


text:
Q: PHP/ Get current URL + conditional I am not very good at php but I want to detect if a user is in the home of the website such as;
<?php
if (current path = http://website.com/ || website.com)
{?>

We are in home

<?php } else { ?>

do something

<?php } ?>

Someone help me please thanks

A:  $pageName = $_SERVER['PHP_SELF'];

 if($pageName == 'http://website.com'){
       echo '
We are in home
';
 } else { do something };


text:
Q: java.lang.reflect.invocationtargetexception Android Studio hello I hope you help me, I have an activity with Android Expandable News, it was working fine but yesterday I realized that I was not showing the detail of the news, and I get this error:
java.lang.reflect.invocationtargetexception
the code is the following:
the error is in this line:
captionTxt.setText(mInfo.getDetalle());
@Layout(R.layout.feed_item)
public class InfoView {

    @ParentPosition
    private int mParentPosition;

    @ChildPosition
    private int mChildPosition;

    @View(R.id.captionTxt)
    private TextView captionTxt;

    private Preguntas mInfo;
    private Context mContext;

    public InfoView(Context context, Preguntas info) {
        mContext = context;
        mInfo = info;
    }

    @Resolve
    private void onResolved() {

        captionTxt.setText(mInfo.getDetalle());

    }
}

I hope someone can guide me

A: InvocationTargetException occurs if you are trying to find the textview with the given ID which does not exist.
Please verify if you get the TextView object returned by below code
TextView txt = (TextView) findViewById (R.id.captionTxt);

Verify in your  layout file, the text view ID should exactly match with the cases.


text:
Q: Setting the position of a tool tip for dynamic elements using jQuery UI So I have the following code:
$(document).tooltip
({
    tooltipClass: 'customToolTipTop',
    position: {my: 'center bottom', at: 'center top-10'},
    content: function()
    {
        var title = $(this).attr("title");

        if (title != null)
        {
            title = title.replace(new RegExp('\r?\n','g'), "<br />");
        }
        return title;
    }
});

So this sets the tooltips for all elements to have the class custom tooltip and be above the centre of the element. This works fine.
I also have css that shows an Arrow that points to the element.
My problem is that I have to specify the position and so the css class. So if the element is near the top of the page the tooltip will show under it but the arrow will still point down.
Is there a way I can know where the tooltip will show in relation to the element?

A: You could add some code in the tooltip's open event (at which point the tooltip will be ready for measuring) to see whether the offset().top of the element is higher or lower than the offset().top of the tooltip.  Something like this (where elem is whatever triggered the tooltip):
open: function(e,ui){
    var topOfToolTip = ui.tooltip.offset().top;
    if (elem.offset().top < topOfToolTip) {
        // Add a class or whatever
        ui.tooltip.addClass("top");
    }
}

See this fiddle where it's all put together.  I'm likely "cheating" to produce that elem variable in the fiddle.  There's probably a canonical way to get the element that triggered the tooltip, but I'm rusty.


text:
Q: Weak Entities + Partial Keys + 2NF I'm a bit confused on the concept of weak entities and normalization and couldn't find any answers online. I know that generally weak entities have a partial key to uniquely identify its own records but the primary key is usually a composite key made up of this partial key and the foreign key (that refers to the weak entity's parent's primary key). Before I thought we could just have the foreign key be the sole primary key for the weak entity but apparently this is not such a good idea.
I am confused however on normalization, specifically 2NF where we have to make sure that no non-prime attribute is solely dependent on a subset of the primary key.
I'm missing something crucial in my understanding here. So wouldn't a weak entity be in violation of 2nf? Because a non-prime attribute could be dependent solely on the foreign key?

A:
So wouldn't a weak entity be in violation of 2nf? Because a non-prime attribute could be dependent solely on the foreign key?

No.  Consider a typical example:
SalesOrder(OrderId,OrderDate) PK (OrderID)
SalesOrderItem(OrderId,OrderItemNum,ProductId,Quantity,Price) PK (OrderId,OrderItemNum)

No OrderItem non-key attribute is functionally dependent on OrderItemNum.  OrderItemNum could be repeated for multiple orders.  In practice it's often not, but for the purposes of normalization it's just the trailing column of the primary key.


text:
Q: Best way to paginate a raw SQL query in a Django REST ListAPI view? I have a raw SQL query that I use to build a query set for a Django REST ListAPI view.  It is along the lines of the following (please excuse the meaningless names):
class MyView(ListAPIView):
    serializer_class = MySerializer
    paginate_by = 10
    def get_queryset(self):
        params = {
            "uid": str(self.request.user.id),
            "param": str(self.kwargs['param'])
        }
        query = 'SELECT f.id ' \
            'FROM myapp_foo f, myapp_bar b ' \
            'WHERE b.foo_id = f.id AND ' \
            'b.param >= %(param)s AND ' \
            'f.dt_tm >= NOW() AND ' \
            '(SELECT COUNT(*) FROM myapp_baz z ' \
            'WHERE z.user_id = %(uid)s AND ' \
            'z.qux_id = f.qux_id) = 0 ' \
            'ORDER BY f.dt_tm;'
        return Foo.objects.raw(query, params)

This gives the error:
object of type 'RawQuerySet' has no len()

I would like to calculate a count with a similar SQL query and then use the LIMIT and OFFSET parameters to do the pagination.  I have read some suggestions where the list items are counted to get the len but this does not seem satisfactory, as it would be inefficient unless there was a small LIMIT in the query (which in any case would defeat the purpose of having pagination).
Update:
I just noticed paginate_by is pending deprecation.
To start with how would I add a count method to the returned object?

A: A more efficient solution than the other alternatives would be to write your own RawQuerySet replacement. I am showing the code below, but you can also access it as a gist here. It is absolutely not guaranteed to be error-free; nevertheless I'm using it in Django 1.11 on Python 3 (with PostgreSQL as the database; should work with MySQL too). Simply put, this class adds the corresponding LIMIT and OFFSET clauses to your raw SQL query. There's nothing crazy, just some simple string concatenation, so make sure not to include these clauses in your raw SQL query.
The class
from django.db import models
from django.db.models import sql
from django.db.models.query import RawQuerySet

class PaginatedRawQuerySet(RawQuerySet):
    def __init__(self, raw_query, **kwargs):
        super(PaginatedRawQuerySet, self).__init__(raw_query, **kwargs)
        self.original_raw_query = raw_query
        self._result_cache = None

    def __getitem__(self, k):
        """
        Retrieves an item or slice from the set of results.
        """
        if not isinstance(k, (slice, int,)):
            raise TypeError
        assert ((not isinstance(k, slice) and (k >= 0)) or
                (isinstance(k, slice) and (k.start is None or k.start >= 0) and
                 (k.stop is None or k.stop >= 0))), \
            "Negative indexing is not supported."

        if self._result_cache is not None:
            return self._result_cache[k]

        if isinstance(k, slice):
            qs = self._clone()
            if k.start is not None:
                start = int(k.start)
            else:
                start = None
            if k.stop is not None:
                stop = int(k.stop)
            else:
                stop = None
            qs.set_limits(start, stop)
            return qs

        qs = self._clone()
        qs.set_limits(k, k + 1)
        return list(qs)[0]

    def __iter__(self):
        self._fetch_all()
        return iter(self._result_cache)

    def count(self):
        if self._result_cache is not None:
            return len(self._result_cache)

        return self.model.objects.count()

    def set_limits(self, start, stop):
        limit_offset = ''

        new_params = tuple()
        if start is None:
            start = 0
        elif start > 0:
            new_params += (start,)
            limit_offset = ' OFFSET %s'
        if stop is not None:
            new_params = (stop - start,) + new_params
            limit_offset = 'LIMIT %s' + limit_offset

        self.params = self.params + new_params
        self.raw_query = self.original_raw_query + limit_offset
        self.query = sql.RawQuery(sql=self.raw_query, using=self.db, params=self.params)

    def _fetch_all(self):
        if self._result_cache is None:
            self._result_cache = list(super().__iter__())

    def __repr__(self):
        return '<%s: %s>' % (self.__class__.__name__, self.model.__name__)

    def __len__(self):
        self._fetch_all()
        return len(self._result_cache)

    def _clone(self):
        clone = self.__class__(raw_query=self.raw_query, model=self.model, using=self._db, hints=self._hints,
                               query=self.query, params=self.params, translations=self.translations)
        return clone

How to use it
A custom manager
I'm using the query set above through a custom manager:
class MyModelRawManager(models.Manager):
    def raw(self, raw_query, params=None, translations=None, using=None):
        if using is None:
            using = self.db
        return PaginatedRawQuerySet(raw_query, model=self.model, params=params, translations=translations, using=using)

    def my_raw_sql_method(some_arg):
        # set up your query and params
        query = 'your query'
        params = ('your', 'params', 'tuple')
        return self.raw(raw_query=query, params=params)

A custom pagination class
For completion, I'm also including a pagination class:
from rest_framework.pagination import PageNumberPagination

class MyModelResultsPagination(PageNumberPagination):
    """Fixed page-size pagination with 10 items."""
    page_size = 10
    max_page_size = 10

Your ListAPIView
class MyModelView(generics.ListAPIView):

    serializer_class = MyModelSerializer
    pagination_class = MyModelResultsPagination

    def get_queryset(self):
        return MyModel.raw_manager.my_raw_sql_method(some_arg)

A word of caution
The PaginatedRawQuerySet class, while functional for me, has not been extensively tested, but I believe it does give an idea of what it takes to have a solution which is more efficient than selecting all the items in your queryset for every call.
You may notice that there is a custom count method implementation (originally missing from RawQuerySet), which is calculated by calling self.model.objects.count(). Without this method, the paginator would evaluate len(your_raw_queryset), which would have the same effect on performance as the other answer.
This class is not a one-size-fits-all replacement for RawQuerySet, which means you should add your own customizations to make it fit your needs.
For example, if you need something more complicated, you could add another attribute to the PaginatedRawQuerySet class, called raw_count_query, which would then be called inside count() instead of counting all the objects the way it is right now (this would be used in cases you need filtering; the raw_count_query would provide the SQL to count the subset based on your conditions).

A: If you cast the raw queryset to a list before returning it, that should prevent the 'RawQuerySet' has no len() error.
return list(Foo.objects.raw(query))

As you say, that will be inefficient, as it will load the entire queryset.
It might be possible to write a custom pagination class, which paginates efficiently using limit and offset, and use it in your view with the pagination_class attribute.

A: I had the same problem and I just found that instead use raw you may use extra :
(...)
return Foo.objects.extra(where=query, params=params)

extras variables
where=['data->>"$.SOMETHING" = %s OR data->>"$.SOMETHING" = %s OR data->>"$.SOMETHING" = %s', 'data->>"$.GROUP" LIKE %s']
params=['EX1', 'EX2', 'EX3', '%EXEMPLE4%']

Note : the main question is use a RawQuerySet with same properties of QuerySet the best way IMHO is use extra of QuerySet API , if is possible .


text:
Q: Не отправляется письмо на почту при регистрации Написал регистрацию пользователей на сайте, но при нажатии на кнопку зарегистрироваться, появляется ошибка "Ошибка при отправлении письма с сcылкой подтверждения, на почту", запись в БД добавляется. Вот код обработчика формы. Заранее спасибо за помощь.
<?php
    //Запускаем сессию
    session_start();

    //Добавляем файл подключения к БД
    require_once("dbconnect.php");

    //Объявляем ячейку для добавления ошибок, которые могут возникнуть при обработке формы.
    $_SESSION["error_messages"] = '';

    //Объявляем ячейку для добавления успешных сообщений
    $_SESSION["success_messages"] = '';

    /*
        Проверяем, была ли отправлена форма, то есть была ли нажата кнопка зарегистрироваться. Если да, то идём дальше, если нет, то выведем пользователю сообщение об ошибке, о том, что он зашёл на эту страницу напрямую.
    */
    if(isset($_POST["btn_submit_register"]) && !empty($_POST["btn_submit_register"])){

        //Проверяем полученную капчу
        //Обрезаем пробелы с начала и с конца строки
        $captcha = trim($_POST["captcha"]);

        if(isset($_POST["captcha"]) && !empty($captcha)){

            //Сравниваем полученное значение со значением из сессии.
            if(($_SESSION["rand"] != $captcha) && ($_SESSION["rand"] != "")){

                // Если капча не верна, то возвращаем пользователя на страницу регистрации, и там выведем ему сообщение об ошибке что он ввёл неправильную капчу.
                $error_message = "
Ошибка!Неправильная капча
";

                // Сохраняем в сессию сообщение об ошибке.
                $_SESSION["error_messages"] = $error_message;

                //Возвращаем пользователя на страницу регистрации
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: ".$address_site."form_register.php");

                //Останавливаем скрипт
                exit();
            }

            /* Проверяем, если в глобальном массиве $_POST существуют данные отправленные из формы и заключаем переданные данные в обычные переменные.*/

            if(isset($_POST["first_name"])){

                //Обрезаем пробелы с начала и с конца строки
                $first_name = trim($_POST["first_name"]);

                //Проверяем переменную на пустоту
                if(!empty($first_name)){
                    // Для безопасности, преобразуем специальные символы в HTML-сущности
                    $first_name = htmlspecialchars($first_name, ENT_QUOTES);
                }else{
                    // Сохраняем в сессию сообщение об ошибке.
                    $_SESSION["error_messages"] .= "
Укажите Ваше имя
";

                    //Возвращаем пользователя на страницу регистрации
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location: ".$address_site."form_register.php");

                    //Останавливаем скрипт
                    exit();
                }

            }else{
                // Сохраняем в сессию сообщение об ошибке.
                $_SESSION["error_messages"] .= "
Отсутствует поле с именем
";

                //Возвращаем пользователя на страницу регистрации
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: ".$address_site."form_register.php");

                //Останавливаем скрипт
                exit();
            }

            if(isset($_POST["last_name"])){

                //Обрезаем пробелы с начала и с конца строки
                $last_name = trim($_POST["last_name"]);

                if(!empty($last_name)){
                    // Для безопасности, преобразуем специальные символы в HTML-сущности
                    $last_name = htmlspecialchars($last_name, ENT_QUOTES);
                }else{

                    // Сохраняем в сессию сообщение об ошибке.
                    $_SESSION["error_messages"] .= "
Укажите Вашу фамилию
";

                    //Возвращаем пользователя на страницу регистрации
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location: ".$address_site."form_register.php");

                    //Останавливаем  скрипт
                    exit();
                }

            }else{

                // Сохраняем в сессию сообщение об ошибке.
                $_SESSION["error_messages"] .= "
Отсутствует поле с фамилией
";

                //Возвращаем пользователя на страницу регистрации
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: ".$address_site."form_register.php");

                //Останавливаем  скрипт
                exit();
            }

            if(isset($_POST["email"])){

                //Обрезаем пробелы с начала и с конца строки
                $email = trim($_POST["email"]);

                if(!empty($email)){

                    $email = htmlspecialchars($email, ENT_QUOTES);

                    // (3) Место кода для проверки формата почтового адреса и его уникальности

                    //Проверяем формат полученного почтового адреса с помощью регулярного выражения
                    $reg_email = "/^[a-z0-9][a-z0-9\._-]*[a-z0-9]*@([a-z0-9]+([a-z0-9-]*[a-z0-9]+)*\.)+[a-z]+/i";

                    //Если формат полученного почтового адреса не соответствует регулярному выражению
                    if( !preg_match($reg_email, $email)){
                        // Сохраняем в сессию сообщение об ошибке.
                        $_SESSION["error_messages"] .= "
Вы ввели неправельный email
";

                        //Возвращаем пользователя на страницу регистрации
                        header("HTTP/1.1 301 Moved Permanently");
                        header("Location: ".$address_site."form_register.php");

                        //Останавливаем  скрипт
                        exit();
                    }

                    //Проверяем, нет ли уже такого адреса в БД.
                    $result_query = $mysqli->query("SELECT `email` FROM `users` WHERE `email`='".$email."'");

                    //Если кол-во полученных строк ровно единице, значит, пользователь с таким почтовым адресом уже зарегистрирован
                    if($result_query->num_rows == 1){

                        //Если полученный результат не равен false
                        if(($row = $result_query->fetch_assoc()) != false){

                                // Сохраняем в сессию сообщение об ошибке.
                                $_SESSION["error_messages"] .= "
Пользователь с таким почтовым адресом уже зарегистрирован
";

                                //Возвращаем пользователя на страницу регистрации
                                header("HTTP/1.1 301 Moved Permanently");
                                header("Location: ".$address_site."form_register.php");

                        }else{
                            // Сохраняем в сессию сообщение об ошибке.
                            $_SESSION["error_messages"] .= "
Ошибка в запросе к БД
";

                            //Возвращаем пользователя на страницу регистрации
                            header("HTTP/1.1 301 Moved Permanently");
                            header("Location: ".$address_site."form_register.php");
                        }

                        /* закрытие выборки */
                        $result_query->close();

                        //Останавливаем  скрипт
                        exit();
                    }

                    /* закрытие выборки */
                    $result_query->close();
                }else{
                    // Сохраняем в сессию сообщение об ошибке.
                    $_SESSION["error_messages"] .= "
Укажите Ваш email
";

                    //Возвращаем пользователя на страницу регистрации
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location: ".$address_site."form_register.php");

                    //Останавливаем  скрипт
                    exit();
                }

            }else{
                // Сохраняем в сессию сообщение об ошибке.
                $_SESSION["error_messages"] .= "
Отсутствует поле для ввода Email
";

                //Возвращаем пользователя на страницу регистрации
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: ".$address_site."form_register.php");

                //Останавливаем  скрипт
                exit();
            }

            if(isset($_POST["password"])){

                //Обрезаем пробелы с начала и с конца строки
                $password = trim($_POST["password"]);

                //Проверяем, совпадают ли пароли
                if(isset($_POST["confirm_password"])){
                    //Обрезаем пробелы с начала и с конца строки
                    $confirm_password = trim($_POST["confirm_password"]);

                    if($confirm_password != $password){
                        // Сохраняем в сессию сообщение об ошибке.
                        $_SESSION["error_messages"] .= "
Пароли не совпадают
";

                        //Возвращаем пользователя на страницу регистрации
                        header("HTTP/1.1 301 Moved Permanently");
                        header("Location: ".$address_site."form_register.php");

                        //Останавливаем  скрипт
                        exit();
                    }

                }else{
                    // Сохраняем в сессию сообщение об ошибке.
                    $_SESSION["error_messages"] .= "
Отсутствует поле для повторения пароля
";

                    //Возвращаем пользователя на страницу регистрации
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location: ".$address_site."form_register.php");

                    //Останавливаем  скрипт
                    exit();
                }

                if(!empty($password)){
                    $password = htmlspecialchars($password, ENT_QUOTES);

                    //Шифруем папроль
                    $password = md5($password."top_secret");
                }else{
                    // Сохраняем в сессию сообщение об ошибке.
                    $_SESSION["error_messages"] .= "
Укажите Ваш пароль
";

                    //Возвращаем пользователя на страницу регистрации
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location: ".$address_site."form_register.php");

                    //Останавливаем  скрипт
                    exit();
                }

            }else{
                // Сохраняем в сессию сообщение об ошибке.
                $_SESSION["error_messages"] .= "
Отсутствует поле для ввода пароля
";

                //Возвращаем пользователя на страницу регистрации
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: ".$address_site."form_register.php");

                //Останавливаем  скрипт
                exit();
            }

            // (4) Место для кода добавления пользователя в БД

            //Удаляем пользователей из таблицы users, которые не подтвердили свою почту в течении сутки

            //Запрос на добавления пользователя в БД
            $result_query_insert = $mysqli->query("INSERT INTO `users` (first_name, last_name, email, password, date_registration) VALUES ('".$first_name."', '".$last_name."', '".$email."', '".$password."', NOW())");

            if(!$result_query_insert){
                // Сохраняем в сессию сообщение об ошибке.
                $_SESSION["error_messages"] .= "
Ошибка запроса на добавления пользователя в БД
";

                //Возвращаем пользователя на страницу регистрации
                header("HTTP/1.1 301 Moved Permanently");
                header("Location: ".$address_site."form_register.php");

                //Останавливаем  скрипт
                exit();
            }else{

                //Удаляем пользователей из таблицы confirm_users, которые не подтвердили свою почту в течении сутки

                //Составляем зашифрованный и уникальный token
                $token=md5($email.time());

                //Добавляем данные в таблицу confirm_users
                $query_insert_confirm = $mysqli->query("INSERT INTO `confirm_users` (email, token, date_registration) VALUES ('".$email."', '".$token."', NOW()) ");

                if(!$query_insert_confirm){
                    // Сохраняем в сессию сообщение об ошибке.
                    $_SESSION["error_messages"] .= "
Ошибка запроса на добавления пользователя в БД (confirm)
";

                    //Возвращаем пользователя на страницу регистрации
                    header("HTTP/1.1 301 Moved Permanently");
                    header("Location: ".$address_site."form_register.php");

                    //Останавливаем  скрипт
                    exit();
                }else{

                    //Составляем заголовок письма
                    $subject = "Подтверждение почты на сайте ".$_SERVER['HTTP_HOST'];

                    //Устанавливаем кодировку заголовка письма и кодируем его
                    $subject = "=?utf-8?B?".base64_encode($subject)."?=";

                    //Составляем тело сообщения
                    $message = 'Здравствуйте!

 Сегодня '.date("d.m.Y", time()).', неким пользователем была произведена регистрация на сайте '.$_SERVER['HTTP_HOST'].' используя Ваш email. Если это были Вы, то, пожалуйста, подтвердите адрес вашей электронной почты, перейдя по этой ссылке: '.$address_site.'activation/'.$token.'

 В противном случае, если это были не Вы, то, просто игнорируйте это письмо.

 Внимание! Ссылка действительна 24 часа. После чего Ваш аккаунт будет удален из базы.';

                    //Составляем дополнительные заголовки для почтового сервиса mail.ru
                    //Переменная $email_admin, объявлена в файле dbconnect.php
                    $headers = "FROM: $email_admin\r\nReply-to: $email_admin\r\nContent-type: text/html; charset=utf-8\r\n";

                    //Отправляем сообщение с ссылкой для подтверждения регистрации на указанную почту и проверяем отправлена ли она успешно или нет.
                    if(mail($email, $subject, $message, $headers)){
                        $_SESSION["success_messages"] = "
Регистрация прошла успешно!!!

 Теперь необходимо подтвердить введенный адрес электронной почты. Для этого, перейдите по ссылке указанную в сообщение, которую получили на почту ".$email."
";

                        //Отправляем пользователя на страницу регистрации и убираем форму регистрации
                        header("HTTP/1.1 301 Moved Permanently");
                        header("Location: ".$address_site."form_register.php?hidden_form=1");
                        exit();

                    }else{
                        $_SESSION["error_messages"] .= "
Ошибка при отправлении письма с сcылкой подтверждения, на почту ".$email."
";
                    }

                    // Завершение запроса добавления пользователя в таблицу users

                    // Завершение запроса добавления пользователя в таблицу confirm_users

                }
            }

            //Закрываем подключение к БД
            $mysqli->close();

            //Отправляем пользователя на страницу регистрации
            header("HTTP/1.1 301 Moved Permanently");
            header("Location: ".$address_site."form_register.php");

            exit();

        }else{
            //Если капча не была передана либо оно является пустой
            exit("
Ошибка! Отсутствует проверечный код, то есть код капчи. Вы можете перейти на  главную страницу .
");
        }

    }else{

        exit("
Ошибка! Вы зашли на эту страницу напрямую, поэтому нет данных для обработки. Вы можете перейти на  главную страницу .
");
    }
?>


text:
Q: How to limit the number of "candidate" documents when using the "fq" parameter in SOLR I believe this will require custom coding, but what I'd like to do is
a) require that queries run against solr contain a value for the filter query parameter (fq)
b) short circuit the request if the resulting candidate list from the filter query is larger than some threshold.
From looking at the SOLR code is seems like I can do the first by providing a custom component to the /select request handler (via the config file), but the second is a little bit more murky.
Is anyone aware of a plugin already implementing something like this?  Or has suggestions on how to implement it?  As best I can see if I extend QueryComponent and inject a custom SolrIndexSearcher it ought to be possible, but I'm not seeing where the filter cache is used exactly (get from cache I found).
edit, adding a sample query
Here's an example query, after sanitizing it
https://....?q=startDate%3A%5B2019-01-10T00%3A00%3A00.000Z%20TO%202019-01-10T23%3A59%3A59.999Z%5D%20AND%20(name%3A%22grr%22)&wt=json&sort=startDate%20asc&fl=recordId,startDate,aName,aSomethingOrOtherType,&start=0&rows=50&joinCollection=
The application is multi-tenant, and while some tenants produce a smaller volume of documents others produce very larger volumes.  We already force a date range into the search to limit the total number of potential documents looked at, but what we'd really like is be able to determine the total number of potential documents before considering anything else and fail the request if it's too broad.  That way we don't incur the cost of the additional search parameters or sorting.


text:
Q: How can show only the characters after dash ( - )? I have the title ( Architectural_Garden_Hardware-Switch Plates & Outlet Covers )
But i whant show only the characters after dash ( - ) like ( Switch Plates & Outlet Covers )\
How can do that?
{foreach from=elements item=birds}
   <option value="{$birds}">{$birds}</option>
/foreach}

A: You should use strpos and substr as in the following example:
{assign var="var" value=" ( Architectural_Garden_Hardware-Switch Plates & Outlet Covers )"}
{assign var="pos" value=$var|strpos:"-"}
{$var|substr:($pos+1)}

You could also use shorter syntax:
{assign var="var" value=" ( Architectural_Garden_Hardware-Switch Plates & Outlet Covers )"}
{$var|substr:($var|strpos:"-"+1)}

so in your case you could probably use:
{foreach from=elements item=birds}
   <option value="{$birds|substr:($birds|strpos:"-"+1)}">{$birds|substr:($birds|strpos:"-"+1)}</option>
{/foreach}


text:
Q: how to make autologin in windows form application when it connects on online database remotely i am working on a windows form application in which i have to make an autologin window.i want that when user desktop connects with internet, Automatically login must be occur. My Desktop application is connected with online database.
Can Any body tell me that what is the procedure to do that.
Please help me i am stucked badly in that.
Thanks in Advance,

A: Take a look at the System.Net.NetworkInformation Namespace. In particular the NetworkChange class.
Example:
NetworkChange.NetworkAvailabilityChanged += (sender, networkAvailabilityEventArgs) =>
    {
        if (networkAvailabilityEventArgs.IsAvailable)
        {
            // Network is available
            // Try to open a database connection
        }
        else
        {
            // Network is not available
            // Stop trying to open a database connection, or clean up existing connections
        }
    };

edit
You can also call NetworkInterface.GetIsNetworkAvailable() to get the same information on-demand.
if (NetworkInterface.GetIsNetworkAvailable())
{
    // Network is available
    // Try to log on
}
else
{
    // Network is not available
    // Do nothing
}

A: Keep trying to connect to the database until you don't get any error (or at least you can reach the database).
You could also try telnet-ing the remote port, but you can't be sure there's one (if you use SQL Server it's possible you're using Named pipes or other protocols)


text:
Q: Convert SQL Request to linq query c# (left outer join and inner join) I am a new developer and I am used to doing my linq c # queries. I have to convert an sql query to linq and I have a problem with a left outer join and an inner join right after. Here is the query below, can you help me?
select ETAB_NOM, ETAB_CODE, count(etab_nom) as nbFiches from tbl_offreSec OS
left outer join tbl_ecoleSec ES on ES.code = OS.FK_ecole
inner join etablissement on etab_code = ES.FK_etablissement
where OS.archive = 0 and OS.descriptionOrtho = 0 and len(OS.description) > 1
group by etab_nom, etab_code
order by ETAB_NOM

My class(condensed):
 public class tbl_offreSec
 {
     public int id { get; set; }
     public int FK_ecole { get; set; }
     public string description { get; set; }
     public Nullable<int> descriptionOrtho { get; set; }
     public int archive { get; set; }
 }

publi class tbl_ecoleSec
{
    public int id { get; set; }
    public int code { get; set; }
    public int FK_etablissement { get; set; }
}

public partial class ETABLISSEMENT
{
    public int ETAB_ID { get; set; }
    public int ETAB_CODE { get; set; }
    public string ETAB_NOM { get; set; }
}

UPDATE
In connection with the answer of Svyatoslav:
   IQueryable<ValidOrthoSecList> query = (from OS in db.tbl_offreSec
                                                   join ES in db.tbl_ecoleSec on OS.FK_ecole equals ES.code into gj
                                                   from ES in gj.DefaultIfEmpty()
                                                   join ET in db.ETABLISSEMENTs on ES.FK_etablissement equals ET.ETAB_CODE
                                                   where OS.archive == 0 && OS.descriptionOrtho == 0 && OS.description.Length > 1
                                                   group ET by new { ET.ETAB_NOM, ET.ETAB_CODE } into g
                                                   select new ValidOrthoSecList
                                                   {
                                                       ETAB_NOM = g.Key.ETAB_NOM,
                                                       ETAB_CODE = g.Key.ETAB_CODE,
                                                       nbFiche = g.Sum(x => x.ETAB_NOM == null ? 0 : 1)
                                                   }).OrderBy(e => e.ETAB_NOM);

A: So there is your query:
var query =
   from os in ctx.tbl_offreSec
   join es in ctx.tbl_offreSec on os.FK_ecole equals es.code into gj
   from es in gj.DefaultIfEmpty()
   join et in ctx.ETABLISSEMENT on es.FK_etablissement equals et.ETAB_CODE
   where os.archive == 0 && os.descriptionOrtho == 0 and os.description.Length > 1
   group et by new { et.ETAB_NOM, et.ETAB_CODE } into g
   select new
   {
      g.Key.ETAB_NOM,
      g.Key.ETAB_CODE,
      nbFiches = g.Sum(x => x.ETAB_NOM == null ? 0 : 1)
   }

var query = query.OrderBy(e => e.ETAB_NOM);

Also consider to do not use LEFT JOIN, since following INNER JOIN will filter out empty records.


text:
Q: segmentation fault 11 in C++ code for my bucket sort, I don't know why the out put is segmentation fault: 11 when I try to print out sorted distance. It should be running well on win pc, but I try running it on mac, but i just get error. where am I wrong?
using namespace std;
void bucketSort(vector<double> &arr, int n)
{
    vector<double> distance;
    vector<double> b[n];

    for (int i=1; i<=n/2; i++)
    {
    double c = sqrt(i)/sqrt(n/2);
    cout<<c<<endl;
    }

    for (int i=0; i<n; i++)
    {
    double dist = sqrt(pow((arr[i]-0), 2) + pow((arr[i+1]-0), 2));
    i = i+1;
    distance.push_back(dist);
    }

    for (int i=0; i<n; i++)
    {
    int bi = n*distance[i]; // Index in bucket
       b[bi].push_back(distance[i]);
    }

    for (int i=0; i<n; i++)
    {
    sort(b[i].begin(), b[i].end());
    }

    int index = 0;
    for (int i = 0; i < n; i++)
    {
    for (int j = 0; j < b[i].size(); j++)
    {
        distance[index++] = b[i][j];
    }
    }

    for (int i = 0; i < n/2; i++)
    {
    cout<<distance[i]<<endl;
    }
}
int main()
{
    vector<double> A;

    double numbers;

    while (cin>>numbers)
    {
    A.push_back(numbers);
    }

    int n = A.size();
    bucketSort(A, n);
}

Here is the out put:
Claudes-MBP:desktop BengDai$ ./a.out < n.txt
0.5
0.707107
0.866025
1
Segmentation fault: 11
Claudes-MBP:desktop BengDai$

A: In your code you use arr[i+1] in a loop where is in the range 0 to n-1.
This means you will try and use arr[n] which is beyond the end of the array.
This block is also suspect:
for (int i=0; i<n; i++)
    {
    int bi = n*distance[i]; // Index in bucket
       b[bi].push_back(distance[i]);
    }

b[bi]: The value of bi could be bigger than the array size of b and probably is?


text:
Q: Error message failed to launch + IOS/cordova I am using cordova(phonegap) 2.1.0 for IOS app development.
When i execute my code through xcode, i get the following error message:
failed to launch '/Users/blah/Library/Developer/Xcode/DerivedData/testapp1-gpcoqhtpqjazwsbkyzcvoxwukjmy/Build/Products/Debug-iphoneos/testapp1.app/testapp1

I am not able to figure out why this error is coming because i have not made any code changes and before it was not coming.

A: Try with:
1 - remove the app from the iPhone Simulator
2 - remove the contents of the DerivedData folder
3 - Clean & Build the project, restart Xcode, and reboot your device.


text:
Q: MPMoviePlayerController Won't Play Video The following MPMoviePlayerController will not present in my iOS application.
I am trying to make it appear when my tableView row is selected:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath    *)indexPath  {

MPMoviePlayerController *player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL URLWithString:videoUrl]];
[player setFullscreen:YES];
[player play];
[self.tableView addSubview:player.view];
}

Any ideas?

A: Instead try:
MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL URLWithString:videoUrl]];
[player prepareToPlay];
[self presentViewController:player animated:YES completion:nil];

A: *

*I wouldn't add the view as a subview of a table view if I were you.

*You have forgotten to give player.view a size.

*You have forgotten to say prepareToPlay to the player. An MPMoviePlayerController absolutely will not play until you have done that.


text:
Q: Set of all endomorphisms that commute with given endomorhphism $F$, with $\mu_F = \chi_F$ is the same as $\mathbb{k}[F]$. Let $F$ be an endomorphism of $V$ over some field $\mathbb{k}$ and characteristic polynomial of $F$ is the same as its minimal polynomial.  Is that true that $Z_F \overset{\operatorname{def}}{=} \{G \in End(V) | FG = GF\}$ is the same as $\mathbb{k}[F]$?
I know that $V $ is the same as $\mathbb{k}[t]$-module $\mathbb{k}[t]/(f_1) \oplus \dots \oplus \mathbb{k}[t]/(f_k)$ with operation of multiplication by $[t]$ being operator F, and because $\mu_F = \chi_F$, all $f_i$ are mutually prime.
Multiplication by some polynomial $P$ commutes with multiplication by $[t]$, so $\mathbb{k}[t] \subseteq Z_F$
How do i proove that there are none operators that commute with $F$ and do not represent multiplication by some polynomial in $\mathbb{k}[t]$-module?
I need to somehow use that $F$ is diagonazable, and can't think of a way to use it.


text:
Q: How to center the bar plot to show the difference of a certain column? How to center the bar plot to show the difference of a certain column?
I have the following bar plot, done with matplotlib :
Note how the barplot is really bad. The difference between each bar cant really be seen properly. So what I want, is to use the red bar as the origin in the y-axis. That way, the other bars would show the difference (blue_bar(i) - redbar).
In other words, I want the value of the red bar in the y-axis to be the y-origin of the plot.
Again, in another words, the red bar is the accuracy obtained by my academic work. I want to plot the other article results compared/ IN RELATION to mine.
I made the following picture using paint.net to illustrate what I want.
Any other ideas/suggestions are really appreciated.

Appendix :
I used the following code to produce the first graphic :
import numpy as np
import random
from matplotlib import pyplot as plt

accuracies = [0.9630, 0.9597, 0.9563, 0.9533, 0.9527, 0.9480, 0.9477, 0.9472, 0.9472, 0.9466, 0.9452, 0.9452, 0.9442,
              0.9440, 0.9434, 0.9420, 0.9407, 0.9407, 0.9391, 0.9377, 0.9185, 0.9268]

sensitividades = [0.7680, 0.7200, 0.8173, 0.7569, 0.7406, 0.7354, 0.7746, 0.7344, 0.7067, 0.7410, 0.7370, 0.7321,
                  0.7357]

especificidades = [0.9827, 0.9733, 0.9816, 0.9807, 0.9789, 0.9724, 0.9764, 0.9801, 0.9751, 0.9521, 0.9487, 0.9694]

accuracies = [x * 100 for x in accuracies]

y = accuracies

N = len(y)
x = range(N)
width = 1 / 1.1
fig, ax = plt.subplots(1, 1)
ax.grid(zorder=0)

# Plot other articles
ax.bar(x, y, width, color="blue", zorder=3)

# Plot my work
ax.bar(x[len(x) - 1] + 1, 95.30, width, color="red", zorder=3)

plt.title('Accuracy of each article')
plt.xlabel('Article')
plt.ylabel('Accuracy')

plt.savefig('foo.png')
plt.show()

A: You could either set the y limits closer to the interesting values:
import numpy as np
import random
from matplotlib import pyplot as plt

accuracies = [0.9630, 0.9597, 0.9563, 0.9533, 0.9527, 0.9480, 0.9477, 0.9472, 0.9472, 0.9466, 0.9452, 0.9452, 0.9442,
              0.9440, 0.9434, 0.9420, 0.9407, 0.9407, 0.9391, 0.9377, 0.9185, 0.9268]

sensitividades = [0.7680, 0.7200, 0.8173, 0.7569, 0.7406, 0.7354, 0.7746, 0.7344, 0.7067, 0.7410, 0.7370, 0.7321,
                  0.7357]

especificidades = [0.9827, 0.9733, 0.9816, 0.9807, 0.9789, 0.9724, 0.9764, 0.9801, 0.9751, 0.9521, 0.9487, 0.9694]

accuracies = [x * 100 for x in accuracies]

my_acc = 95.30
y = accuracies

N = len(y)
x = range(N)
width = 1 / 1.1
fig, ax = plt.subplots(1, 1)
ax.grid(zorder=0)

# Plot other articles
ax.bar(x, y, width, color="blue", zorder=3)

# Plot my work
ax.bar(x[len(x) - 1] + 1, my_acc, width, color="red", zorder=3)

plt.title('Accuracy of each article')
plt.ylim(min(y) - 0.5, max(y) +0.5)
plt.xlabel('Article')
plt.ylabel('Accuracy')

plt.savefig('foo2.png')
plt.show()

Or you could plot it around zero, with your result being the new origin (but you will have to indicate by how much you shifted the origin somewhere in the legend or somewhere else):
import numpy as np
import random
from matplotlib import pyplot as plt

accuracies = [0.9630, 0.9597, 0.9563, 0.9533, 0.9527, 0.9480, 0.9477, 0.9472, 0.9472, 0.9466, 0.9452, 0.9452, 0.9442,
              0.9440, 0.9434, 0.9420, 0.9407, 0.9407, 0.9391, 0.9377, 0.9185, 0.9268]

sensitividades = [0.7680, 0.7200, 0.8173, 0.7569, 0.7406, 0.7354, 0.7746, 0.7344, 0.7067, 0.7410, 0.7370, 0.7321,
                  0.7357]

especificidades = [0.9827, 0.9733, 0.9816, 0.9807, 0.9789, 0.9724, 0.9764, 0.9801, 0.9751, 0.9521, 0.9487, 0.9694]

accuracies = [x * 100 for x in accuracies]

my_acc = 95.30
y = np.asarray(accuracies) - my_acc

N = len(y)
x = range(N)
width = 1 / 1.1
fig, ax = plt.subplots(1, 1)
ax.grid(zorder=0)

# Plot other articles
bars = ax.bar(x, y, width, color="blue", zorder=3)

# Plot my work
# ax.bar(x[len(x) - 1] + 1, my_acc, width, color="red", zorder=3)

plt.title('Accuracy of each article')
plt.yticks([0, -0.3, -1.3, -2.3, -3.3, 0.7, 1.7], [95.30, 95, 94, 93, 92, 96, 97])
plt.xlabel('Article')
plt.ylabel('Accuracy')
plt.ylim(min(y) - 0.5, max(y) + 0.7)

def autolabel(rects):
    for i in range(len(rects)):
        rect = rects[i]
        height = rect.get_height()
        if (height >= 0):
            ax.text(rect.get_x() + rect.get_width()/2.,
            0.3 + height,'[{}]'.format( i), ha='center', va='bottom',
            fontsize=7.5)
        if (height < 0):
            ax.text(rect.get_x() + rect.get_width()/2.,
            height - 0.3,'[{}]'.format( i), ha='center', va='bottom',
            fontsize=7.5)

autolabel(bars)
plt.savefig('foo.png')
plt.show()

Of course, your own result would not appear in the second plot, since it would have height zero.

A: I actually think the way you have it represented now is actually best -- meaning there isn't a huge difference in accuracy on a cursory level.
However, if you want to set the value of the red bar as the origin, try this:
...
plt.title('Accuracy of each article')
plt.xlabel('Article')
plt.ylabel('Accuracy')

plt.ylim(95.30) # Sets the value of the red bar as the origin.

plt.savefig('foo.png')
plt.show()

Perhaps setting the minimum value of lowest accuracy of the article might make this graph more digestible.
...
plt.title('Accuracy of each article')
plt.xlabel('Article')
plt.ylabel('Accuracy')

plt.ylim(min(accuracies), 100) # Sets the value of minimum accuracy as the origin and the max value as 100.

plt.savefig('foo.png')
plt.show()


text:
Q: SparkPi running slow with more than 1 slice Relatively new on spark and have tried running SparkPi example on a standalone 12 core three machine cluster. What I'm failing to understand is, that running this example with a single slice gives better performance as compared to using 12 slices. Same was the case when I was using parallelize function. The time is scaling almost linearly with adding each slice. Please let me know if I'm doing anything wrong. The code snippet is given below:
val spark = new SparkContext("spark://telecom:7077", "SparkPi",
  System.getenv("SPARK_HOME"), List("target/scala-2.10/sparkpii_2.10-1.0.jar"))
val slices = 1
val n = 10000000 * slices
val count = spark.parallelize(1 to n, slices).map {
  i =>
    val x = random * 2 - 1
    val y = random * 2 - 1
    if (x * x + y * y < 1) 1 else 0
}.reduce(_ + _)
println("Pi is roughly " + 4.0 * count / n)
spark.stop()

Update: Problem was with random function, since it was a synchronized method, it couldn't scale to multiple cores.

A: The random function used in sparkpi example is a synchronized method and can't scale to multiple cores. It's an easy enough example to deploy on your cluster but don't use it to check Spark's performance and scalability.

A: As Ahsan mentioned in his answer, the problem was with 'scala.math.random'.
I have replaced it with 'org.apache.spark.util.random.XORShiftRandom', and now using multiple processors makes the Pi calculations to run much faster.
Below is my code, which is a modified version of SparkPi example from Spark distribution:
// scalastyle:off println
package org.apache.spark.examples

import org.apache.spark.util.random.XORShiftRandom

import org.apache.spark._

/** Computes an approximation to pi */
object SparkPi {
  def main(args: Array[String]) {
    val conf = new SparkConf().setAppName("Spark Pi").setMaster(args(0))
    val spark = new SparkContext(conf)
    val slices = if (args.length > 1) args(1).toInt else 2
    val n = math.min(100000000L * slices, Int.MaxValue).toInt // avoid overflow
    val rand = new XORShiftRandom()

    val count = spark.parallelize(1 until n, slices).map { i =>
        val x = rand.nextDouble * 2 - 1
        val y = rand.nextDouble * 2 - 1
        if (x*x + y*y < 1) 1 else 0
      }.reduce(_ + _)

    println("Pi is roughly " + 4.0 * count / n)
    spark.stop()
  }
}
// scalastyle:on println

When I run the program above using one core with parameters 'local[1] 16' it takes about 60 seconds on my laptop. Same program using 8 cores ('local[*] 16') it takes 17 seconds.


text:
Q: Typescript Cannot find module (TS2307) I know this is a common question but I have gone through almost every "TS cannot find module" question and none of the solutions worked for me or didnt apply to my case.
I am debugging sln on VS2019. When I first cloned the repo I ran into this TS error saying it couldnt find modules. I ran npm install which didnt work. I tried installing each one manually and that just led to more problems. The modules should be there since the build is successful right?
The project uses typescript 3.7 so I tried updating that to see if it does anything. Still no good.
Here is the tsconfig:
{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [ "es2015", "dom" ],
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "typeRoots": ["node_modules/@types"]
  },
  "include":[
    "node_modules/angular2-masonry",
    "app/**/*"
  ]
}

Just to add, this project works fine on my partners machine, so I think it is some package or something related I am missing, but I dont know what. Let me know if there is more information I can provide.

A: Try to do as follow,

*

*Delete node_modules folder

*Delete package-lock.json file

*Run: npm install


text:
Q: Small performance test on a web service I'm trying to develop a small application that tests how many requests per second my service can support but I think I'm doing something wrong. The service is in an early development stage, but I'd like to have this test handy in order to check from time to time I'm not doing something that decrease the performance. The problem is that I cannot get the web server or the database server go to the 100% of CPU.
I'm using three different computers, in one is the web server (WinSrv Standard 2008 x64 IIS7), in other the database (Win 2K, SQL Server 2005) and the last is my computer (Win7 x64 Ultimate), where I'll run the test. The computers are connected through a 100 ethernet switch. The request POST is 9 bytes and the response will be 842 bytes.
The test launches several threads, and each thread has a while loop, in each loop it creates a WebRequest object, performs a call, increment a common counter and waits between 1 and 5 milliseconds, then it do it again:
static int counter = 0;

static void Main(string[] args)
{
    ServicePointManager.DefaultConnectionLimit = 250;

    Console.WriteLine("Ready. Press any key...");
    Console.ReadKey();
    Console.WriteLine("Running...");

    string localhost = "localhost";
    string linuxmono = "192.168.1.74";
    string server = "192.168.1.5:8080";

    DateTime start = DateTime.Now;

    Random r = new Random(DateTime.Now.Millisecond);
    for (int i = 0; i < 50; i++)
    {
        new Thread(new ParameterizedThreadStart(Test)).Start(server);
        Thread.Sleep(r.Next(1, 3));
    }

    Thread.Sleep(2000);

    while (true)
    {
        Console.WriteLine("Request per second :"
            + counter / DateTime.Now.Subtract(start).TotalSeconds);
        Thread.Sleep(3000);
    }
}

public static void Test(object ip)
{
    Guid guid = Guid.NewGuid();

    Random r = new Random(DateTime.Now.Millisecond);
    while (true)
    {
        String test = "<lalala/>";
        WebRequest req = WebRequest.Create("http://"
            + (string) ip + "/WebApp/" + guid.ToString()
            + "/Data/Tables=whatever");
        req.Method = "POST";
        req.ContentType = "application/xml";
        req.Credentials = new NetworkCredential("aaa", "aaa","domain");
        byte[] array = Encoding.UTF8.GetBytes(test);
        req.ContentLength = array.Length;
        using (Stream reqStream = req.GetRequestStream())
        {
            reqStream.Write(array, 0, array.Length);
            reqStream.Close();
        }

        using (Stream responseStream = req.GetResponse().GetResponseStream())
        {
            String response = new StreamReader(responseStream).ReadToEnd();
            if (response.Length != 842) Console.Write(" EEEE ");
        }

        Interlocked.Increment(ref counter);

        Thread.Sleep(r.Next(1,5));
    }
}

If I run the test neither of the computers do an excessive CPU usage. Let's say I get a X requests per second, if I run the console application two times at the same moment, I get X/2 request per second in each one... but still the web server is on 30% of CPU, the database server on 25%...
I've tried to remove the Thread.Sleep in the loop, but it doesn't make a big difference.
I'd like to put the machines to the maximum, to check how may requests per second they can provide. I guessed that I could do it in this way... but apparently I'm missing something here... What is the problem?
Kind regards.

A: IMO, you're better off using SoapUI for the test. You can easily adjust the test case for the number of threads, number of iterations, etc.. And it'll graph the results.  When you hit the plateau where you overwhelm the server, you'll see it on the graph.  If one PC isn't enough, just run more of them on other PCs.  You can do all of this with the free version.

A: There are a lot of limiting factors besides the CPU on a web server.  There are a lot of IIS settings which throttle the number of connections can be served.
I would read this:
http://www.eggheadcafe.com/articles/20050613.asp
I know it is for IIS 6, but there are things that will still apply.
If you have access to MSDN and have VS 2010 ultimate, I would check out their load testing tools.  Purchasing the load testing program can be expensive, but if you need to test something specific, you can use the trial version to accomplish what you need.  You can use it to monitor and response time, server utilization, etc.  Well worth looking into.

A: I agree with Chris, and would go a step further to recommend JMeter, as it can also test the database and webapp, all within the same script.